text:
Crash your favorite compiler
Write a perfectly legal code in a decent language of your choice whose compiling will either crash the compiler or send it into an infinite loop (infinite compile time).
Restrictions:

Use a standard language that is used in real world.
Use a standard, well-developed compiler (no answers like "I wrote my C compiler that crashes on everything").
The code must be legal in the language (so most likely you'll have to exploit a compiler or a language bug).
Give your compiler version and options used so that others can replicate it.
Explain why the compiler crashed, if possible.

Have fun :)

Could you elaborate on what you mean by "crash"?

@GigaWatt I mean that the compiler stops in an uninteded way. Neither by successfully compiling the input nor by issuing an error message. It has to really crash, like segfault, eating up all the memory, throwing an unchecked exception etc.

http://wiki.python.org/moin/CrashingPython

This contest is mostly just an exercise in searching bug reports for test cases :/

Is crashing an interpreter permitted?

I refer the honorable gentleman to my answer here http://codegolf.stackexchange.com/questions/69189/build-a-compiler-bomb/69279#69279 which crashes the compiler by running it out of RAM.

Vote to reopen!

I'm pretty sure it's been fixed now, but it used to be that you could crash the Java compiler (or, crash Eclipse) by writing
class Foo {
  static double d = 2.2250738585072012e-308;
}

http://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/
Actually, according to that page, the compiler will just hang, not crash. Still, I thought that was pretty fun.

My favorite solution for GHC:

data Bad a = C (Bad a -> a)

xx :: Bad a -> a
xx (x@(C x')) = x' x

omega :: a
omega = xx (C xx)

main = omega

For GHC 6.12.1 both ghci Bad.hs and ghc Bad.hs loop infinitely.
GHC 7.4.1 loops infinitely when ghc -O2 Bad.hs is executed.
Explanation: omega is defined using an infinite recursion (the only way it can inhabit any type). Compiler's inliner sees xx as a simple, non-recursive function, so it tries to inline it in the definition of omega. It results in (\x@(C x') -> x' x) (C xx). Seeing a pattern match on a constructor the compiler tries to reduce it, getting xx (C xx) again and loops. The trick is that xx is actually recursive, but the recursion is hidden within the data type.
Note: While writing the puzzle, I forgot I left GHC running in the infinite loop. It took all my memory, crashed Firefox and I barely managed to kill it without hard reset.

+1 just for the trouble you went through for the answer :P

@UnkwnTech :-) Actually I discovered this by an accident when trying to implement recursion using a recursive data type only.

This is easy in any dependently-typed language. Type-checking general dependent types is undecidable since it may require arbitrarily complex computations (Turing-complete). You can simply encode in a dependent type a too-large value. Then the type-checker will use all available memory and crash. For instance, in Coq, ReyCharles gives the example of Compute 70000., which causes the type-checker to construct a giant Peano numeral and crash.
In more common languages that support some sort of macro expansion or metaprogramming, you can do something similar. For example, you can use all available memory in C:
#include <stdio.h>
#define a printf("%s", "Hello, world!\n");
#define b a a a a a a a a a a a a a a a a
#define c b b b b b b b b b b b b b b b b
#define d c c c c c c c c c c c c c c c c
#define e d d d d d d d d d d d d d d d d
#define f e e e e e e e e e e e e e e e e
// ...
#define z y y y y y y y y y y y y y y y y
int main() { z }

The D programming language allows compile-time function execution. This can be used to compute something at compile time that is too large to fit in memory. Something similar can be achieved using C++ template metaprogramming.
In XML (not a compiled programming language, but an XML processor is analogous to a compiler), expanding entities can make the processor run out of memory:
<?xml version="1.0"?>
<!DOCTYPE lolz [
 <!ENTITY lol "lol">
 <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
 <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
 <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
...
]>
<lolz>&lol999;</lolz>

This is called the billion laughs attack.

Note that <lolz>&lol999;</lolz> is 10^999 laughs, not a billion. The linked references uses <lolz>&lol9;</lolz>, which is actually a billion.

Note that the Coq issue has nothing to do with Turing completeness; Coq's type system is specifically designed so that type-checking is decidable and not Turing complete. Type checking will always be possible with a constant amount of memory (and it will always terminate), but that constant is dependent on the code in question, and can be made arbitrarily large.

C#
Found this on a stackoverflow question:
using System;
using System.Linq;

public class Test
{
    public static void Main()
    {
        Enumerable.Range(0, 1).Sum(a =>
        Enumerable.Range(0, 1).Sum(b =>
        Enumerable.Range(0, 1).Sum(c =>
        Enumerable.Range(0, 1).Sum(d =>
        Enumerable.Range(0, 1).Sum(e =>
        Enumerable.Range(0, 1).Sum(f =>
        Enumerable.Range(0, 1).Count(g => true)))))));
    }
}

The compiler eventually will crash.
The issue seems related to type inference and/or lambda generation combined with overload resolution.

+1 for making Visual Studio's intellisense consume all available memory and crash the IDE. This is a prank I shall use only for the power of good.

VBA
how about if you can crash the IDE by typing in code?
in any Microsoft Office application, try this:
ALT+F11 to get to the VBA window, then try the following code
sub foo()
dim v(1 to 3, 1 to 3)
redim preserve v(,1 to 5)

and behold:

You can simply type redim preserve v(,1 to 5) into the immediate window, and it will crash after you press ENTER !

nice, but more like "crash your favourite interpreter"

Could I get a quick rundown on why this works?

@GigaWatt, it's discussed in a little more depth here, but it appears that the IDE cannot cope with errors (unexpected symbol , and expected ,)

Perl (15)
BEGIN{1while 1}

This creates an infinite loop at compile time:

A BEGIN code block is executed as soon as possible, that is, the moment it is completely defined, even before the rest of the containing file (or string) is parsed.

(from perlmod)
And that's why Perl isn't able to complete parsing the code. This doesn't terminate:
$ perl -MO=Deparse -e 'BEGIN{1while 1}'

TeX
\def\x{\x}\x

TeX is a macro-expansion language. Here we define the expansion of the macro \x to be \x again, and then we add afterwards an invocation of \x. TeX gets stuck endlessly replacing \x with \x.

Note: this isn't the shortest way to achieve this. TeX has a notion of "active characters", which essentially are characters that are treated as macro names. So you can shave off 3 characters from this.

Scheme
(define-syntax s
    (syntax-rules ()
        ((_ (t) ...) (s (t t) ... (t t) ...))
        ((_ (t u) ...) (s (t) ... (u) ...))))
(s (+))

My compiler, Chicken, made the mistake of attempting to expand macros at compile time for "run-time performance" or something. So it payed the price of expanding this one. I've read R5RS. No one said macros had to be expanded at compile time.
Essentially what's going on is the macro expands to an expression of infinite size, constantly doubling in size. Well, to be technical, doubling every other expansion. The compiler's fate is sealed. At least on my system, Chicken caps at 2GB, stalls for a long time trying to garbage collect, then crashes after the garbage collector gives up. It does take a while though because of all the computationally expensive hygienic magic occurring.
Switching between expressions of the form
(s (+) (+) (+) (+) ....

and
(s (+ +) (+ +) (+ +) (+ +) ....

seems to very, very dramatically increase the rate of memory consumption as compared to:
(define-syntax s
    (syntax-rules ()
        ((_ t ...) (s t ... t ...))))
(s +)

I suspect Chicken is a pretty hardy compiler that has some ways of avoiding deep analysis of syntactic expressions when it can get away with it, but my final solution forces the pattern matcher to really dive in.

Woah. +1, and welcome to Programming Puzzles and Code Golf Stack Exchange. If you need any help, or just want to talk, feel free to reply to this comment with @wizzwizz4.

J
This segfaults the J interpreter (at least on Linux):
15!:1[3#2

It tries to read from memory address 2. Interestingly, if you try it with 0 or 1, you get domain error.

Smalltalk (Squeak dialect, version 4.x)
Very easy, just evaluate this, or accept a method with this literal
1.0e99999999999999999999

It will try to evaluate the power of 10 in Large Integer arithmetic, just for correctly rounding inf Tsss ;)
Edit: how many 9 are necessary?
Since 2^10 is 1024, approximately 10^3, we can roughly approximate 10^n by 2^(10*n/3). That means that 10^n require 10*n/3 bits to be represented in binary. We would like to have 10^n not representable.
Assuming 32 bit pointers for the object memory, we know that we cannot address more than 2^32 bytes, that is 2^35 bits. So let's reverse the problem: 2^35 is approximately 32 * 2^30, 32*10^9. That requires about 11 decimal digits, so with eleven 9, we are sure to generate an error on 32bits Squeak. In 64 bits that would be twenty one 9.
We can also exhaust memory with less 9s, the whole addressable space is not necessarily available, but it's deadly slow to test, the Squeak VM is not optimized for such giant arithmetic unlike GMP.

Do you need more than four 9s?

@JoeZ. yes more than 4 nines.Smalltalk has LargeInteger arithmetic and machine have big RAM now... testing the exact limit is boring, above 6 nines, compiler start to be sloooowwww

Clang++
I just came across this fun bug.
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>

std::stringstream prog;

constexpr unsigned c_strlen( char const* str, unsigned count = 0 )
{
    return ('\0' == str[0]) ? count : c_strlen(str+1, count+1);
}

template < char t_c, char... tt_c >
struct rec_eval
{
    static void eval()
    {
        rec_eval<t_c>::eval();
        rec_eval < tt_c... > :: eval ();
    }
};
template < char t_c >
struct rec_eval < t_c >
{
    static void eval() {
        switch(t_c) {
            case '+':
                prog<<"++t[i];";
                break;
            case '-':
                prog<<"--t[i];";
                break;
            case '>':
                prog<<"++i;";
                break;
            case '<':
                prog<<"--i;";
                break;
            case '[':
                prog<<"while(t[i]){";
                break;
            case ']':
                prog<<"}";
                break;
            case '.':
                prog<<"putc(t[i],stdout);";
                break;
            case ',':
                prog<<"t[i]=getchar();";
                break;
        }
    }
};

template < char... tt_c >
struct exploded_string
{
    static void eval()
    {
        rec_eval < tt_c... > :: eval();
    }
};
template < typename T_StrProvider, unsigned t_len, char... tt_c >
struct explode_impl
{
    using result =
        typename explode_impl < T_StrProvider, t_len-1,
                                T_StrProvider::str()[t_len-1],
                                tt_c... > :: result;
};

template < typename T_StrProvider, char... tt_c >
struct explode_impl < T_StrProvider, 0, tt_c... >
{
     using result = exploded_string < tt_c... >;
};

template < typename T_StrProvider >
using explode =
    typename explode_impl < T_StrProvider,
                            c_strlen(T_StrProvider::str()) > :: result;

int main(int argc, char** argv)
{
    if(argc < 2) return 1;
    prog << "#include <stdio.h>\n#include <stdlib.h>\nint main(){unsigned char* t=calloc(";
    prog << (1 << sizeof(unsigned short));
    prog << ",sizeof(unsigned short));unsigned short i=0;";

    struct my_str_provider
    {
        constexpr static char const* str() { return "++++[>+++++<-]>+++[[>+>+<<-]>++++++[<+>-]+++++++++[<++++++++++>-]>[<+>-]<-]+++>+++++++++[<+++++++++>-]>++++++[<++++++++>-]<--[>+>+<<-]>>[<<+>>-]<-->>++++[<++++++++>-]++++++++++>+++++++++[>+++++++++++<-]>[[>+>+>+<<<-]>[<+>-]>>[[>+>+<<-]>>[<<+>>-]<[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<<<+>---------->->[-]]]]]]]]]]]<]<<[>>++++++++++++[<++++<++++>>-]<<[.[-]>]<<]>[<++++++[>++++++++<-]>.[-]]<<<<<.<<<<<.[<]>>>>>>>>>.<<<<<..>>>>>>>>.>>>>>>>.[>]>[>+>+<<-]>[<+>-]>[-[[-]+++++++++[<+++++++++++++>-]<--.[-]>]]<<<<<.[<]>>>>>>>>>.>>>>>>>>>.[>]<<.<<<<<.<<<..[<]>>>>>>.[>]<<.[<]>>>>>>>>>.>.[>]<<.[<]>>>>.>>>>>>>>>>>>.>>>.[>]<<.[<]>.[>]<<<<<<.<<<<<<<<<<<..[>]<<<.>.[>]>[>+>+>+<<<-]>[<+>-]>>[[>+>+<<-]>>[<<+>>-]<[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<<<+>---------->->[-]]]]]]]]]]]<]<<[>>++++++++++++[<++++<++++>>-]<<[.[-]>]<<]>[<++++++[>++++++++<-]>.[-]]<<<<<.<<<<<.[<]>>>>>>>>>.<<<<<..>>>>>>>>.>>>>>>>.[>]>[>+>+<<-]>[<+>-]>[-[[-]+++++++++[<+++++++++++++>-]<--.[-]>]]<<<<<.[<]>>>>>>>>>.>>>>>>>>>.[>]<<.<<<<<.<<<..[<]>>>>>>.[>]<<<<.>>>.<<<<.<.<<<<<<<<<<.>>>>>>.[>]<<.[<]>>>>>>>>>.>.>>>>>>>>>.[>]<<.<<<<<<<.[<]>>>>>>>>>.[<]>.>>>>>>>>>.[>]<<.<<<<.<<<<<<<<<<<<<.[>]<<<<<<<<<.[>]<<.[<]>>>>>>>>.[>]<<<<<<.[<]>>>>>..[>]<<.<<<<<<<<<<<<.[<]>>>>.[>]<<.<<<<.[<]>>>>>>.>>>.<<<<<<.>>>>>>>.>>>>>>>>>>.[>]<<<.>.>>>-[>+>+>+<<<-]>[<+>-]>>[[>+>+<<-]>>[<<+>>-]<[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<->-[<<<+>---------->->[-]]]]]]]]]]]<]<<[>>++++++++++++[<++++<++++>>-]<<[.[-]>]<<]>[<++++++[>++++++++<-]>.[-]]<<[>+>+<<-]>[<+>-]+>[<->[-]]<[-<<<[<]>>>>>>>>>>.<.[>]<<.[<]>>>>>>>>>>>.<<.<<<.[>]<<<<<<<<<<.[>]>>]<<<<.<<<<<.[<]>>>>>>>>>.<<<<<..>>>>>>>>.>>>>>>>.[>]>[>+>+<<-]>[<+>-]+>[<->-[<+>[-]]]<[++++++++[>+++++++++++++<-]>--.[-]<]<<<<.[<]>>>>>>>>>.>>>>>>>>>.[>]<<.<<<<<.<<<..[<]>>>>>>.[>]<<.[<]>>>>>>>>>.>.[>]<<.[<]>>>>.>>>>>>>>>>>>.>>>.[>]<<.[<]>.[>]<<<<<<.<<<<<<<<<<<..[>]<<<<.>>>..>>]"; }
    };

    auto my_str = explode < my_str_provider >{};
    my_str.eval();

    prog << "}";

    std::ofstream ofs(argv[1]);
    if(!ofs) return 2;
    ofs << prog.str() << std::endl;
    ofs.close();

    return 0;
}

The goal is to translate Brainfuck into C, using template meta-programming to do most of the work. This code works for smaller Brainfuck programs, such as Hello World, but when I tried to run it with 99 Bottles...
$ clang++ -std=c++11 -fconstexpr-depth=1000 bf_static.cpp
clang: error: unable to execute command: Segmentation fault (core dumped)
clang: error: clang frontend command failed due to signal (use -v to see invocation)
clang version 3.5.2 (tags/RELEASE_352/final)
Target: i386-pc-windows-cygnus
Thread model: posix
clang: note: diagnostic msg: PLEASE submit a bug report to http://llvm.org/bugs/ and include the crash backtrace, preprocessed source, and associated run script.
clang: note: diagnostic msg:
********************

PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:
Preprocessed source(s) and associated run script(s) are located at:
clang: note: diagnostic msg: /tmp/bf_static-afa982.cpp
clang: note: diagnostic msg: /tmp/bf_static-afa982.sh
clang: note: diagnostic msg:

********************

It will successfully compile in GCC (after about 2 minutes), but linking it causes another issue...
/usr/lib/gcc/i686-pc-cygwin/4.9.3/../../../../i686-pc-cygwin/bin/as: /tmp/cc0W7cJu.o:
section .eh_frame$_ZN8rec_eval<giant mangled name removed>: string table overflow at offset 10004228
/tmp/cc3JeiMp.s: Assembler messages:
/tmp/cc3JeiMp.s: Fatal error: can't close /tmp/cc0W7cJu.o: File too big

Oops.

Common Lisp
Macros make it easy:
(defmacro loop-forever ()
  (loop for x from 0 collecting x))

(defun compile-me ()
  (loop-forever))

Compiling compile-me calls loop-forever, which exhausts heap memory during its expansion and crashes the compiler. If you just want to make the compiler hang indefinitely, then this definition of loop-forever will do it:
(defmacro loop-forever ()
  (loop))

This should work using any CL implementation, unless yours is extremely clever and can detect simple infinite loops, but I seriously doubt any do this. Full protection against this is impossible, of course.

meh. Lisp makes writing compile-time infinite loops too easy. Now if you had actually crashed the compiler...

@JanDvorak The only way to crash a Lisp is to call a C library through FFI ;-)

@coredump Please do. At compile time :-)

(defmacro loop-forever () (loop)) (defun compile-me () (loop-forever)) should be sufficient. It hangs CCL for me.

This is my original and concise method to crash GolfScript:
{1.}do

What this does is set up a forever loop that keeps on pushing 1 onto the stack until memory runs out.
In C/C++, I believe that this original piece of code would crash the compiler:
#define a bb
#define b aa
int main(){a}

This would get the compiler stuck doubling the amount of a's and turning them into b's and vice versa, so the compiler would pretty soon run out of memory and crash.
Another one is for batch on Windows, if completely freezing the computer rather than just the batch script itself counts. You should type in the following:
:a
start %0
goto a

This gets into an infinite loop of making copies of itself, which make copies of themselves and so on. This would most likely eventually crash your computer if you ran this little bit of code.
One last one is a VBS bomb. It is another bomb, like the last one, but it instead opens an infinite amount of dialog boxes.
set oshell = wscript.createobject("wscript.shell")
do
oshell.run "wscript " & wscript.scriptname
msgbox "blah"
loop

This continuously creates a copy of itself and opens up a message box in an infinite loop, which the clones do as well. Running these last two programs is not recommended, as they can freeze your computer and cause you to have to hard boot your computer.
Note that I came up with all of these programs myself.

C macros do not recurse; you cannot crash the C or C++ preprocessor that way.

Perl
This defines operator overloading at compile time, and runs code at compile time which adds the instances of class together.
(by the way, normally infinite recursion would eat all the memory, but with overloading, it just crashes)
package MyAmazingClass;
use 5.010;

use overload '+' => sub {
    my ($first, $second) = @_;
    return $first + $second;
};

sub new {
    my $self = shift;
    return bless {}, $self;
}

# BEGIN runs code at compile time
BEGIN {
    my $instance = MyAmazingClass->new;
    my $sum = $instance + $instance;
    say $sum;
}

Output:
fish: Job 1, 'perl' terminated by signal SIGSEGV (Address boundary error)

D
(DMD32 D Compiler v2.067.1, Windows build)
enum x = "mixin(x);";
mixin(x);

Note that this will send the compiler into an infinite loop and crash it.

Error: out of memory

Mechanical snail suggested that compile-time programming features in D could be abused for this purpose, but the solution is perhaps simpler than the kind of techniques he had in mind.

For those who aren't familiar with 'string mixins', it's a fairly straightforward macro feature. When the compiler encounters mixin("asdf"), it substitutes it with the contents of the string, asdf, and tries to compile it again.
The solution above will be expanded like:
mixin(x);  ->  mixin("mixin(x);");  ->  mixin(x);

So unless the compiler tries to detect this expand-to-same case, it'll enter an infinite loop of expansion.

Simplex v.0.5, 2 bytes
Too bad this isn't a code-golf:
2Q

Let me explain. From the docs:

[Q]   Adds program source code to outer program, from the beginning (exclusive of ! characters, if the current byte is not zero) If byte is 2, duplicates current command as well.

So:
2 ~~ Manhattan adds 2 to the current byte: 10*0 + 2 = 2.
Q ~~ Adds program source code to the outer program, with Q

The outer program is a neat little feature in Simplex: it is evaluated at the end of the program. So, if we keep track...:
P1  P2  P3  P4  ...
2Q->2Q->2Q->2Q->...

Eventually, memory will run out and the world will end.

x86 asm
"nasm -v" returns "NASM version 2.11.08 compiled on Feb 21 2015" (I'm running it under win7)
The assembler has been running for 1:12:27 so far on an i7, totally saturating one of the cores. The output file is sitting at 0 bytes, memory consumption has been stable at 1,004K - it seems safe to say I've beaten nasm up, rather than just giving it a really, really long task. :)
The key to the trick is the repeat value in the macro - 0xFFFFFFFF.
Though, I'm not familiar enough with Nasm's internals to know why exactly it's choking on this. I expected to get a ~16GB output an hour ago.
%MACRO INVOKE 1-*
;  %REP    %0 - 1
  %REP     0xffffffff
    %ROTATE   -1
    PUSH    DWORD %1
  %ENDREP
  %ROTATE -1
  CALL    %1
%ENDMACRO

[section .text]
bits 32
org 0x10000

EntryPoint:
    INVOKE dword 666
    ret

EDIT: Just checked the task manager, Nasm has been running for 7:40:41 and the memory is now up to 1,016K

Gnu assembler, generating huge output files
This macro attempts to fill the output file with garbage (usually null bytes) until a 4 GB boundary is reached, adds an int to get past that boundary, and recursively calls itself to keep filling the output with 4 GB chunks of garbage. This will fill your hard drive until it is full, at which point the assembler will likely crash.
.macro f n #Define a macro named f, taking argument n.
.p2align 32 #Fill file with 0x00's until current address is divisible by 2^32
.long 0 #Add a long after the current address, throwing it off alignment.
.if \n #If n > 0, recursively tail-call itself, decrementing n.
f "(\n-1)"
.endif
.endm #End macro definition.
f 32 #Expand macro f, with n = 32 (output size 4GB*32 = 128GB)

Note that infinite recursion cannot be used, as the assembler will catch that special case and stop expanding the macro.
Compilation can be done with as -o crash.out crash.s on most Linux distributions.

Can you comment the source? I really don't understand what this's doing.

You should post this as an answer to Build a compiler bomb! :D

PHP 5.3.1 (Segfaults interpreter) (Bug 50261, fixed in 5.3.3)

   class testClass
   {
       function testClass ()
       {
           echo 'Output string!';
       }
   }

   class testClass2 extends testClass
   {
       function __construct ()
       {
           call_user_func(array('parent', '__construct'));
       }
   }

   new testClass2;

This one was a bit of a problem, because the code above was common in a lot of the code I was working with, making this a fairly widespread issue for us.
(If I recall correctly, at one point this was the only way to call parent constructors in PHP.)

Common Lisp, 8 bytes
Shorter than the other Common Lisp answer :-)
#.(loop)

Loop while reading your form.
The Common Lisp standard has no mention of a portable way to make it crash, so I guess we need to have an implementation-defined way. Still 8 bytes:
#.(quit) ; ccl

... or,
#.(exit) ; sbcl

When you call (compile-file "crash.lisp"), the environments mysteriously "crash".
Joking apart, I am still trying to find a way to really crash the environment (and shortly), but it is really hard. All I get is a nice interaction with the debugger.

Common Lisp, 29 bytes
Implementation: Clozure CL
WARNING: Be careful when running this code, it may kill processes that you don't want it to!
#.(run-program"pkill"'("cl"))

This runs the shell command pkill cl on compile time, which will kill the Lisp process doing the compiling. Not technically a crash, but it has the same effect.
Example usage:
$ cat /tmp/t.lisp
#.(run-program "pkill" '("cl"))
$ ccl -n
Welcome to Clozure Common Lisp Version 1.11-dev-r16513-trunk  (LinuxX8664)!

? (compile-file "/tmp/t.lisp")
#P"/tmp/t.lx64fsl"
NIL
NIL
?
zsh: terminated  ccl -n
$

Felix
This doesn't work anymore, but at one point, this code:
include "std/control/pchannels";

fun is_square(v: int) => let s = int$ sqrt$ v.float + 0.5f in s*s == v;
fun is_median(v: int) => v % 4 == 0 and (v/4).is_square;

struct Message { value: int; };

proc process(c: int, chan: pchannel[Message]) {
    var i = 0;
    for var b in (c+1)/2 upto c do
        for var a in c - b + 1 upto b do
            if is_median(2*(b*b+c*c)-a*a) or
               is_median(2*(a*a+c*c)-b*b) or
               is_median(2*(a*a+b*b)-c*c) do ++i; done;
        done
    done
    write(chan, Message i);
};

proc main() {
    n := int$ System::argv 1;
    var count = n;
    chan := #mk_pchannel[Message];
    var ntri = 0;

    for var c in 1 upto n perform spawn_pthread { process(c, chan); };

    while count > 0 do
        let v = chan.read in ntri += v.value;
        --count;
    done
    ntri.println;
}

main;

This would give a big error:
inner_bind_expression raised Not_found [BUG] e=(&((main_mf_60270<60270> ())), (value v))

SYSTEM FAILURE
    bind_expression' raised Not_found [BUG]
    Felix compilation "/media/ryan/stuff/felix/build/release/host/bin/flxg" "-q" "--optimise" "--inline=100" "--output_dir=/home/ryan/stuff/.felix/text" "--cache_dir=/home/ryan/stuff/.felix/cache" "-I/media/ryan/stuff/felix/build/release/share/lib" "-I/media/ryan/stuff/felix/build/release/host/lib" "--syntax=@/media/ryan/stuff/felix/build/release/share/lib/grammar/grammar.files" "--automaton=/home/ryan/stuff/.felix/cache/media/ryan/stuff/felix/build/release/share/lib/grammar/grammar.files/syntax.automaton" "--import=plat/flx.flxh" "std" "/home/ryan/golf/itri/sl.flx" failed
    Error 1 in flx: [strerror_r] Failed to find text for error number 1
The issue was here:
let v = chan.read in ntri += v.value;

let expected an expression to follow it, but I put a statement instead. So the compiler freaked out a tad.
More info at https://groups.google.com/forum/m/#!topic/felix-language/J3Hs4j6E0gM.

JavaScript
while (true === true){
console.log(0);
}

This sends it into an infinite loop.
I used the Codecademy JS compiler and it crashed my browser.

Is that the compiler or the runtime crashing?  The web browser includes both, but I'd argue they're still separate components.

The compiler crashed, freezing my browser. @Hand-E-Food

This is not crashing the compiler; it's hanging your webpage. Also, you could just write while(1){}; this is also an infinite loop.

An even shorter example is while(1);.

Javascript
function crash(){
  window.location.hash=Math.random(),onhashchange=function(){crash()}
}

This one crashes web browsers in a seriously effective fashion. USE AT YOUR OWN RISK!!!

What is the exact means of the crash? In particular, this question is about crashing compilers, and this seems it just makes the browser die, not its JS internal compiler.

FF refuses to crash; running this in Chrome hung my system.

Hassium
File1.has:
use "File2.has";

File2.has:
use "File1.has";

This causes Hassium to load and begin compiling File2.has, which tells it to load File1.has, which causes it to load File2.has, and so on.

LOLCODE 1.2, LOLCODE Common Interpreter/Compiler (lci)
I know this isn't code-golf but it's extremely short anyways.
OBTW

This causes Signal 11:
Segmentation fault (core dumped)

Why? HAI1.2 denotes the start of the program, and OBTW initiates a multiline comment. But the compiler expects a KTHXBYE to close the HAI, and a TLDR to close the multiline comment.
Note that this will still work to cause segfault with anything other than TLDR after OBTW.

(By wikipedia's standards, LOLCODE is a just a Weirdlang, not actually esoteric.)

You can grab the interpreter from git/justinmeza/lci.

"Use a standard language that is used in real world." Do you mean to tell me that you'd use lolcode to write a legitimate program?

@PatrickRoberts Yes, I would. /s


text:
List prime-factorized natural numbers up to N in ascending order
For a given n list prime factorization of all natural numbers between 1 and n in ascending order. For example, for n = 10 the output would be:
1:
2: 2^1
3: 3^1
4: 2^2
5: 5^1
6: 2^1 3^1
7: 7^1
8: 2^3
9: 3^2
10: 2^1 5^1

Requirements:

You cannot just iterate over the numbers and factor each of them. (Unless you know how to factor a number in logarithmic time, and then I doubt you'd be wasting your time solving puzzles.) This is too inefficient.
The output should be as in the example above: On each line the number and the list of its prime factors.
Consider that n can be very large, so it might be infeasible to generate all the factorizations into memory and then sort them at the end. (But if you have a clever solution that violates this, post it too.)

Below is my attempt, in R5RS scheme (disclaimer: I'm not actually a Schemer (yet!), so pardon the (probably) terrible code).
(define count 10)

; `factors` is our vector of linked-lists of factors.  We're adding to these
; as we go on.
(define factors (make-vector count 'not-found))
(vector-set! factors 0 '())

; `primes-so-far` contains all the prime numbers we've discovered thus far.
; We use this list to speed up the dividing of numbers.
;   `primes-so-far-last` is a ref to the last entry in the `primes-so-far`
; list, for O(1) appending to the list.
(define primes-so-far '(dummy))
(define primes-so-far-last primes-so-far)

;; Helpers
(define (factor-ref n)
  (vector-ref factors (- n 1)))

(define (factor-cached? n)
  (not (eq? (vector-ref factors (- n 1)) 'not-found)))

(define (factor-put n factor)
  (let* ((rest        (/ n factor))
         (factor-cell (cons factor (factor-ref rest))))
    (vector-set! factors (- n 1) factor-cell)
    factor-cell))

(define (prime-append n)
  (let ((new-prime-cell (cons n '())))
    (set-cdr! primes-so-far-last new-prime-cell)
    (set!     primes-so-far-last new-prime-cell)
    new-prime-cell))

;; The factor procedure (assumes that `[1..n-1]` have already been factorized).
(define (factor n)
  (define (divides? m n)
    (= (modulo n m) 0))

  ; n       the number to factor.
  ; primes  the list of primes to try to divide with.
  (define (iter n primes)
    (cond ((factor-cached? n)
           (factor-ref n))

          ((null? primes)
           ; no primes left to divide with; n is prime.
           (prime-append n)
           (factor-put n n)) ; the only prime factor in a prime is itself

          ((divides? (car primes) n)
           (factor-put n (car primes))
           (factor-ref n))

          (else
           (iter n (cdr primes)))))

  (iter n (cdr primes-so-far)))

(define (print-loop i)
  (if (<= i count)
      (begin
        (display i)
        (display ": ")
        (display (factor i))
        (newline)
        (print-loop (+ i 1)))))

(print-loop 1)

Prints as:
1: ()
2: (2)
3: (3)
4: (2 2)
5: (5)
6: (2 3)
7: (7)
8: (2 2 2)
9: (3 3)
10: (2 5)

(Not exactly like in the task description, but all you'd have to do to get that output is to fold the list and merge repetitions of the same number, during the output part of the code.  The internal representation/algorithm would still be the same.)
The idea is to cache the previously computed values, but make use of the fact that the factors of n is the first prime factor of n and the prime factors of (n / first-factor).  But the latter is already known, so we just re-use the already existing list of factors for that smaller number.  Thus, for each number in [1..n] which is not prime, a single cons cell is stored.
For each number, a single cons cell is created and stored.  Thus, this approach should run with O(n) storage usage.  I've no clue if it's possible to neatly express the time-complexity.

C++
Implements a sieve using primes up to sqrt(n).  Maintains a list of linked lists to keep track of which primes divide which upcoming numbers.  Each time a prime p is used, its Factor structure is moved p slots down the list.
Most of the time is spent in just printfing the answer.
#include <stdio.h>
#include <stdlib.h>

// lists of Factors represent known prime factors of a number
struct Factor {
  Factor(int p) : prime(p), next(NULL) { }
  int prime;
  Factor *next;
};

int main(int argc, char *argv[]) {
  long long n = atoll(argv[1]);

  // figure out the maximum prime we need to sieve with
  int maxp = 1;
  while ((long long)maxp * maxp < n) maxp++;
  maxp--;

  // find next power of two up from that for our circular buffer size
  int size = 1;
  while (size < maxp) size *= 2;
  int mask = size - 1;

  // allocate circular buffer of lists of sieving prime factors for upcoming numbers
  Factor **factors = new Factor*[size]();

  printf("1:\n");

  for (long long x = 2; x < n; x++) {
    Factor *list = factors[x & mask];
    factors[x & mask] = NULL; // reset so it can hold the list for x + size

    if (!list && x <= maxp) { // x is a prime we need to sieve with - make new list with just itself
      list = new Factor(x);
    }

    // print factor list, push each Factor along to the next list.
    printf("%lld:", x);
    long long y = x;
    while (list) {
      Factor *f = list;
      list = f->next;
      int p = f->prime;

      // count how many factors of p are in x
      int k = 1;
      y /= p;
      while (y % p == 0) {
        k++;
        y /= p;
      }
      printf(" %d^%d", p, k);

      // splice f into the list for the next number it divides
      long long z = x + f->prime;
      f->next = factors[z & mask];
      factors[z & mask] = f;
    }
    // remaining part of x must be prime
    if (y != 1) printf(" %lld^1", y);
    printf("\n");
  }
}

C (gcc)
#include <stdio.h>
#include <stdlib.h>

#define true 1
#define false 0

int square(int a){
	return a * a;
}

void prime_factors(int n){
	// this is an array of n elements, which will contain all found primes.
	// curprime stores the index of the last found prime, which saves us searching for where to insert the next one and things.
	int* primes = calloc(sizeof(int), n);
	int curprime = 0;

	printf("1:\n"); // Micro optimization, and rids me of the messing around that is 1.
	for(int i=2; i<=n; i++){
		// Print the current i.
		printf("%i: ",i);

		// Define val, which we'll slowly make smaller and smaller. Mwahaha.
		int val = i;
		int isprime = true;	// This will be set to false if it's divisible by any primes, which of course, means it's also not a prime.

		// Loop through primes, this loop stops if we've reached either more than sqrt(count) primes, or val is equal to zero (as such, it's fully prime factorized).
		for(int*prime_pointer = primes; val && square((int)(prime_pointer-primes)) < curprime; prime_pointer++){
			int prime = *prime_pointer;
			// if the current val is divisible by the current prime.
			while(val%prime == 0){
				isprime = false; 	// We know that this number isn't prime.
				val = val / prime;	// Divide val by it.
				printf("%i ",prime);// And write this prime.
			}
		}
		if(isprime){	// If this number is a prime.
			printf("%i ",i);	// Append it to its own list.
			primes[curprime++] = i;	// And append this new prime to our list of primes.
		}
		printf("\n");	// Terminate the line with a newline. Duh...
	}
}

int main(int argc, char** argv){
	prime_factors(1000);
}

Defines the function prime_factors which takes an integer n and outputs via printf in the following format:
1:
2: 2
3: 3
4: 2 2
5: 5
6: 2 3
7: 7
8: 2 2 2
9: 3 3
10: 2

This uses O(n) extra memory, and I'm not sure the time complexity.
Try it online!

source: Stack Exchange

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

sort: votes


text:
List ALL prime-factorized natural numbers in ANY order
This is a variant of List prime-factorized natural numbers up to N in ascending order, but the solutions can be very different.
Write a program that outputs prime factorizations of all natural numbers in any order. For example, the output could look like:
1:
4: 2^2
8: 2^3
2: 2^1
3: 3^1
5: 5^1
6: 2^1 3^1
21: 3^1 7^1
9: 3^2
...

Requirements:

You cannot just iterate over the numbers and factor each of them. This is too inefficient.
The output should be as in the example above: On each line the number and the list of its prime factors.
There is no given order in which the number appear in the list. However:
Each number must appear exactly once in the list (explain that your code satisfies this condition).

Edit - remark: Of course the program never finishes. But since (4) requires each number to appear in the list, for any n there is time t such that the list produced by the program within time t contains the factorization of n. (We don't care if t is comparable to the age of our universe or anything else.)
Note: This is not code-golf, it's code-challenge. This puzzle is about clever ideas, not code size. So please don't give the shortest solutions, give commented solutions that are easy to read and where the idea is easily understandable.

Please specify a range of natural numbers to be factored. Factoring ALL natural numbers isn't feasible during the lifespan of our known universe.

You could add this requirement to the answers: Your program should, for each number n output its factorization in not more than O(n log n) time. IIRC prime factorization is not possible in O(log n).

I’m voting to close this question because "you cannot just iterate over the numbers and factor each of them" is an unobservable requirement and there's no objective winning criterion.

Haskell
import Data.List

merge :: [[a]] -> [[a]] -> [[a]]
merge [] ys = ys
merge (x:xs) ys = x : merge ys xs

atmostonefromeach :: [[a]]-> [[a]]
atmostonefromeach = foldr weave undefined

weave :: [a] -> [[a]] -> [[a]]
weave pwrs odds = merge (map (:[]) pwrs) $
foldr (\odd -> merge (odd: (map (:odd) (pwrs)))) undefined odds

primes = nubBy (\x y->gcd x y > 1) [2..]

shw factors = show (product (map (\(p,k)->p^k) factors)) ++ ":" ++ concatMap(\(p,k) -> ' ': show p ++ '^': show k) factors

powers p = map (\x->(p,x)) [1..]

main = mapM_ (putStrLn . shw) $ ([]:) $ atmostonefromeach $ map powers primes

output:
1:
2: 2^1
3: 3^1
4: 2^2
5: 5^1
8: 2^3
6: 2^1 3^1

...

The program constructs,
from the list Q=[q0,q1,..] of composite numbers with all prime factors > p,
the list of those with primes factors >= p, as
merge(P, merge((map(q0*)P1), merge(map(q1*)P1),...
where P=[p^1,p^2,...] and P1=[p^0,p^1,..].
The name odds in function weave describes the case p==2,
where Q is the set of all odd numbers > 1.

Generates the list by iterating over N.  Each iteration generates all numbers which are the product of up-to-Nth powers of the first N primes.  Starts with N=1 and keeps growing N.  To avoid duplicates, each iteration makes sure not to generate anything generated in previous iterations.  Those are exactly the numbers that don't include the Nth prime and which don't have at least one exponent equal to N.
import itertools

print '1 ='

n = 0
primes = []
while 1:
  n += 1

  # generate next prime
  q = primes[-1] if primes else 1
  while 1:
    q += 1
    if all(q % p != 0 for p in primes):
      primes.append(q)
      break

  # generate all exponents of at most n of first n primes
  for e in itertools.product(*(xrange(n+1) for i in xrange(n))):
    if max(e) == n or e[-1] > 0:  # we didn't do this in iteration n-1
      print reduce(lambda x, y: x * y, (primes[i]**e[i] for i in xrange(n))), '=', ' '.join('%d^%d' % (primes[i], e[i]) for i in xrange(n))

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


text:
Win a virtual fencing match (against your fellow stack exchangers)
WARNING: this is a fairly complex problem, in a king-of-the-hill combat style, with an added randomness to it, the best code may not always win. Please read all rules in full, as it is quite complex!
Flavor text
Bill and Steve decided to have a "friendly" duel, however being so rich and smart, decided to let their best programmers try their hand at coming up with the code to beat each other. You are said programmer.
Objective
In fencing, your goal is to score the most hits on your opponent, while getting hit the least yourself
Moves
Your code will have the following choices of "moves"

Attack
Parry
Block
Lunge

AND

Head
Chest
Feet

Scoring
Attacking beats Parrying, for 1 point
Lunging beats Blocking, for 1 point
Parrying Beats Lunging, for 1 point
Blocking beats Attacking, for 1 point
Lunging ties Attacking, with the lunging player unable to block or parry the next round, and the attacking player unable to attack or lunge the next round
Blocking ties Parrying, with the parrying player unable to block or parry the next round, and the blocking player unable to attack or lunge the next round
Height of action
You will also choose a "height" for your action, whereupon the outcomes above only take place if the heights of both players match the attack height. if the heights do not match, both players may no longer select the same action (height is not restricted) as the previous tying rounds, until a point is scored, or all 4 actions have been filled (once a tie is broken, all actions are available again)
Code requirements
For each round, it should prompt the move of the opponent the previous round (barring round 1), compare it with its own, determine the outcome of the previous round, then output the next round number, the score, and its choice / position for that round
ex:
INPUT: LC (lunge chest)
OUTPUT: previous round: PM vs LC - PM scores! score is now 2-1, action for next round is AH (attack head)
Winner
The game ends after 50 rounds, or after 3 points have been scored
Against other players
The first answer will be given an instant guaranteed win, as long as it functions to actually work/play. Each answer will be evaluated, in order of posting, against the previous winner, and if winning, will be declared the new winner. I ask that while winning, or waiting to compete, that you do NOT change your code. Once being defeated, you may no longer compete for championship status with that same language, you may however submit a different language answer (must be significantly different, no using variations of the same base stuff).
I will attempt to run each challenge and will post the results in the comments of the champion and challenger, as well as declare a new winner - as I may not be able to run every language, especially some of the more obscure ones, I ask any possible help you can give to make sure your answer gets run be taken into consideration.

note: targetting the current winners algorithm to counter that player is in the nature of fencing, and this is king-of-the-hill, so such action is not only allowed, but also ENCOURAGED! - try to come up with some method of generating results, obfuscating your code, or some other way to "guard" yourself, and figure the best way to "attack" the other player's code! -- PLEASE KEEP ALL DISCUSSION CIVIL --

once defeated, if you want to offer insight into how you did things, why you did things a certain way, etc, in comments or by modifying your answer, feel free to. While your code is in line, however, please refrain from editing :)

Is your example correct? It seems to mangle an input of LC into an action of LM.

What about randomness in the solution? Must the match be deterministic? If not, how will the judge select the seed, and how many games will be played between two programs, just one? The robocode competitions usually have 10, to limit the effects of blind chance.

this.hits=0;opponent.hits=Infinity; :)

@PeterTaylor updated example, originally it was top, middle, bottom, however I changed to head feet chest to avoid the bottom and block being same letters - as for randomness, the program must be able to run "out of the box" - as in no prompt for the "seed" should occur etc
as for blind chance, I will run a best of 5
I am also partially doing this as I don't know how to run scripts/programs in all the various languages, so I hope to use the results in this as a learning experience myself :)

What happens if both choose the same action at the same height?

@Quasimodo tie, the round is ignored.

is this roughly the algorithm? while rounds < 50 and myscore < 3 and yourscore < 3: choose my move, and output; input opponent's move; score my move against opponent's move, and output

@Griffin Yes, that would be about right, so long as input and output follows basic rules

I don't really like how this is designed. I think you should come up with the code to run the match by running 2 submitted programs, relaying the moves and calculating the scores. The fencing programs should just print their moves to stdout and read the opponent's moves form stdin.

Python
En garde!
My warrior combines unpredictability with a keen eye for weakness in his opponent's stance.  He's pretty confident he'll be able to dispose of aggressive foes but his trainer (me) may have failed to anticipate certain scenarios or, perhaps more worrying, may have misinterpreted the rules (bugs!!).
Anyway I'm new so hopefully this is an ok format for the code:
from random import choice, random

def cleverly_pick_move(me_allowed,op_allowed,opp_last_move=None) :
    """ Behold the genius you're up against!
    Pretty much everything else is just flavour text or match rules
    so you'll probably only want to read this...
    """
    heights = ['head','chest','feet']
    rand_choice = lambda a,h : {'type':choice([t for t in a if a[t]]),
                                'height':choice(h)}

    if opp_last_move is None or feeling_like_a_lucky_punk():
        return rand_choice(me_allowed,heights)

    if sum(1 for x in op_allowed if op_allowed[x]) == 3 :
        for i in op_allowed:
            if not op_allowed[i] :
                weakness = i
                break
        return {'type':exploit_weakness(weakness,me_allowed),
                'height':choice(heights)}
    return rand_choice(me_allowed,heights)

def exploit_weakness(weakness,me_allowed) :
    moves = ['attack','parry','lunge','block']
    for i,move in enumerate(moves) :
        if move == weakness :
            if me_allowed[moves[(i+1) % 4]] :
                return moves[(i+1) % 4]
            break
    if me_allowed[weakness] :
        return weakness
    return choice([x for x in me_allowed if me_allowed[x]])

def feeling_like_a_lucky_punk() :
    return random() > 0.8

def main():

    this_round = 1
    opp_last_move = None
    score   = {'myself':0, 'the blaggard':0}
    quips   = ['blaggard', 'fool', 'scum', 'raggamuffin']
    adverbs = ['deftly', 'skillfully', 'gracefully', 'clumsily']

    me_allowed = {'attack':True,'block':True,'lunge':True,'parry':True}
    op_allowed = {'attack':True,'block':True,'lunge':True,'parry':True}

    while (this_round <= 50 and
           all([points < 3 for points in score.values()])) :

        if this_round == 1 :
            move = cleverly_pick_move(me_allowed,op_allowed)
        else:
            move = cleverly_pick_move(me_allowed,op_allowed,
                                      opp_last_move=opp_last_move)

        print "Our hero %s %ss at the %s's %s" % (
            choice(adverbs),
            move['type'],
            choice(quips),
            move['height']
            )
        print "We await the %s's response..." % choice(quips)
        print "Our hero's move: " + (move['type'][0]+move['height'][0]).upper()

        opp_move = parse_move(raw_input("Opponent's move: "))

        outcome,me_allowed,op_allowed = get_outcome(move,opp_move,me_allowed,
                                                    op_allowed)
        if outcome == 'WIN' :
            print "Our hero pulls off an excellent round!"
            score['myself'] += 1
        elif outcome == 'LOSE' :
            print "Never before have we seen such blatant cheating!"
            score['the blaggard'] += 1
        else :
            print "Our hero is clearly toying with his opponent as he allows \
a drawn round."

        print ("""The score after round %d:\nOur hero:\t%d\nHis opponent:\t%d"""
                % (this_round, score['myself'], score['the blaggard']))
        opp_last_move = opp_move
        this_round += 1

    print "Match over, surely the victory is mine!"
    print """Final score:\n
             Our hero:\t%d\nOpponent:\t%d""" % (score['myself'],
                                                score['the blaggard'])

    if score['myself'] > score['the blaggard'] :
        print "My victory was inevitable!"
    elif score['myself'] == score['the blaggard'] :
        print "An even match! Huzzar!"
    else :
        print ""
    return

def reset_allowed(dictionary) :
    return dict((x,True) for x in dictionary)

def get_outcome(mymove,opmove,me_allowed,op_allowed) :
    result = ''

    if not me_allowed[mymove['type']] :
        print "Whoops, I forgot I couldn't do that..."
        result = 'LOSE'

    if not op_allowed[opmove['type']] :
        print "Haha! What a clutz!"
        result = 'WIN'

    if mymove['height'] != opmove['height'] :
        print "The combatants flail at each other with little effect!"
        print "They'll have to try something else next round!"
        result = 'DRAW'

    if mymove['type'] == opmove['type'] :
        if mymove['type'] in ['attack','lunge']:
            print "The combatants' blades clash dramatically!"
        else :
            print "Both combatants take a moment to practice their \
defensive stance..."
        result = 'DRAW'

    if result :
        me_allowed, op_allowed = (reset_allowed(me_allowed),
                                  reset_allowed(op_allowed))
        if mymove['height'] != opmove['height'] :
            me_allowed[mymove['type']] = op_allowed[opmove['type']] = False
        return (result, me_allowed,op_allowed)
    else :
        return compare_attacks(mymove,opmove,me_allowed,op_allowed)

def compare_attacks(mymove,opmove,me_allowed,op_allowed) :
    """
    0 A > P 1
     ^  x  v
    3 B < L 2
    """
    print "Our hero %ss, his opponent %ss!" % (mymove['type'],opmove['type'])

    move_val = {'attack':0,'parry':1,'lunge':2,'block':3}
    result_num = (move_val[opmove['type']] - move_val[mymove['type']]) % 4
    results = ['DRAW','WIN','DRAW','LOSE']

    me_allowed, op_allowed = (reset_allowed(me_allowed),
                              reset_allowed(op_allowed))
    if result_num == 1 :
        print "Our hero easily outwits his foe! *Huge cheers from crowd*"
        return ('WIN',me_allowed,op_allowed)
    elif result_num == 3 :
        print "Our hero graciously allows his opponent a charity point.\
*A torrent of boos from the crowd*"
        return ('LOSE',me_allowed,op_allowed)
    else:
        # Combatants drew and will have their moves restricted next round.
        if mymove['type'] in ['attack','parry'] :
            me_allowed['attack'] = me_allowed['lunge'] = False
            me_allowed['parry']  = me_allowed['block'] = True
            op_allowed['parry']  = op_allowed['block'] = False
            op_allowed['attack'] = op_allowed['lunge'] = True
        else :
            me_allowed['parry']  = me_allowed['block'] = False
            me_allowed['attack'] = me_allowed['lunge'] = True
            op_allowed['attack'] = me_allowed['lunge'] = False
            op_allowed['parry']  = op_allowed['block'] = True
        return ('DRAW',me_allowed,op_allowed)

def parse_move(move_string) :
    m_types = {'A':'attack','B':'block','L':'lunge','P':'parry'}
    m_heights = {'C':'chest','H':'head','F':'feet'}

    move_string = move_string.strip().upper()
    if not move_string :
        print "Couldn't understand your input: %s" % move_string
        return parse_move(raw_input("Opponent's move: "))

    if move_string[0] not in m_types :
        move_string = move_string[::-1]

    try :
        move = {'type':m_types[move_string[0]],
                'height':m_heights[move_string[1]]}
        return move
    except KeyError :
        print "Couldn't understand your input: %s" % move_string
        return parse_move(raw_input("Opponent's move: "))

if __name__ == '__main__' :
    main()

love the flavor text! ill hopefully get around to getting these to duke it out here this weekend. Unfortunately its been a very long time since this was posted and its just now gaining traction, so im a bit ill-prepared right now to do, but I should be able to here within a few days!

No worries. To be honest I didn't check the dates of the posts above.  That barbarian of @Arkady 's must be feeling pretty cocky/lonely up on that hill for 8 weeks.  I'll use that to my advantage !

I'll check this later (I don't have a Python interpreter at work) and possibly counter-attack later. Be "on guard" as they might say in France.

I claim the hill!
This includes a framework which takes care of the match, input and output. All you have to do is define your own versions of two functions in the "A.I.h" header which define the first move and every other move.
This compiles in VS2012 (free version). To the best of my knowledge it will compile in any standards-compliant compiler.
I call this A.I. "Unsophisticated Barbarian." I'm sure it won't take long for someone to beat it.
// A.I.h
    #pragma once

    #include "Fencer.h"

    #include <algorithm>

    Move Fencer::chooseFirstMove() const
    {
        // Choose first move here.
        return Move( Action::Attack , Height::Head );
    }

    Move Fencer::chooseNextMove() const
    {
        using namespace std;

        // Implement A.I. here.
        auto legalActions = match.legalActions();
        auto isLegal = [&legalActions]( Action a ) {
            return find( begin(legalActions) , end(legalActions) , a ) == end(legalActions);
        };

        if( isLegal( Action::Attack ) )
            return Move( Action::Attack , Height::Head );
        if( isLegal( Action::Lunge ) )
            return Move( Action::Lunge , Height::Head );
        if( isLegal( Action::Block ) )
            return Move( Action::Lunge , Height::Head );
        if( isLegal( Action::Parry ) )
            return Move( Action::Parry , Height::Head );

    }

    // Fencer.h
    #pragma once

    #include "Match.h"

    class Fencer
    {
    public:
        std::string nextRound( const std::string& oppsMove );
        std::string getNextMove() const { return nextMove.toStr(); }
        bool matchInProgress() const { return match.inProgress(); }
        Fencer( unsigned int targetScore = 3 , unsigned int match_rounds = 50 );
    private:
        Move chooseNextMove() const;
        Move chooseFirstMove() const;
        Move nextMove;
        Match match;
    };

    // Match.h
    #pragma once

    #include <vector>
    #include <string>

    enum class Action : char
    {
        Attack,
        Parry,
        Block,
        Lunge,
        UNITIALIZED
    };

    enum class Height : char
    {
        Head,
        Chest,
        Feet,
        UNITIALIZED
    };

    enum class Result : char
    {
        Win,
        Tie,
        Lose,
        UNITIALIZED
    };

    struct Move
    {
        Action action;
        Height height;
        Move( Action a , Height h )
            : action(a) , height(h) {}
        std::string toStr() const;

        // For the STL. Please don't use these.
        Move() : action( Action::UNITIALIZED ) , height( Height::UNITIALIZED ) {}
        Move operator=( const Move& );
    };

    Result scoreRound( Move me , Move opp );

    struct Round
    {
        Move myMove;
        Move oppsMove;
        Result result;
        Round( Move me , Move opp )
            : myMove(me) , oppsMove(opp) , result(scoreRound(me,opp)) {}

        // For the STL. Please don't use these.
        Round() : myMove() , oppsMove() , result( Result::UNITIALIZED ) {}
        Round operator=( const Round& );
    };

    class Match
    {
    public:
        // Constructor.
        Match( unsigned int winningScore, unsigned int rounds );

        // Generate a list of legal actions.
        std::vector<Action> legalActions() const;

        // Get a copy of all previous rounds.
        std::vector<Round> getHistory() const { return results; }

        // Gets the scores
        unsigned int myScore() const;
        unsigned int oppsScore() const;
        bool inProgress() const { return in_progress; }

        // Perform next round. Returns the TTY for the round.
        std::string nextRound( const std::string& myMove , const std::string& oppsMove );
    private:
        const unsigned int winning_score;
        const unsigned int n_rounds;
        std::vector<Round> results;
        bool in_progress;
    };

    // Fencer.cpp
    #include "AI.h"

    #include <algorithm>

    using namespace std;

    Fencer::Fencer( unsigned int target , unsigned int rounds ) :
        match( target , rounds ) , nextMove( chooseFirstMove() )
    {}

    string Fencer::nextRound( const string& oppsMove )
    {
        string output = match.nextRound( nextMove.toStr() , oppsMove );
        if( match.inProgress() ) {
            nextMove = chooseNextMove();
            vector<Action> legalActions = match.legalActions();
            auto it = find( legalActions.begin() , legalActions.end() , nextMove.action );
            auto it2 = legalActions.end();
            if( legalActions.end() == it ) {
                output += "\n\nWARNING! Chosen move is illegal!\n\n";
            }
            output += " Action for next round is " + getNextMove() + ".";
        }
        return output;
    }

    // Match.cpp
    #include "Match.h"

    #include <algorithm>
    #include <sstream>
    #include <cassert>
    #include <functional>

    using namespace std;

    string Move::toStr() const
    {
        string str;
        switch( action )
        {
        case Action::Attack:
            str.push_back( 'A' );
            break;
        case Action::Block:
            str.push_back( 'B' );
            break;
        case Action::Lunge:
            str.push_back( 'L' );
            break;
        case Action::Parry:
            str.push_back( 'P' );
            break;
        default:
            assert( false );
            break;
        }
        switch( height )
        {
        case Height::Head:
            str.push_back( 'H' );
            break;
        case Height::Chest:
            str.push_back( 'C' );
            break;
        case Height::Feet:
            str.push_back( 'F' );
            break;
        default:
            assert( false );
            break;
        }
        return str;
    }

    Move Move::operator=( const Move& rhs )
    {
        action = rhs.action;
        height = rhs.height;
        return *this;
    }

    Result scoreRound( Move me , Move opp )
    {
        if( me.height != opp.height ) {
            return Result::Tie;
        }
        if( me.action == opp.action ) {
            return Result::Tie;
        }
        switch ( me.action ) {
        case Action::Attack:
            switch( opp.action ) {
            case Action::Parry:
                return Result::Win;
            case Action::Lunge:
                return Result::Tie;
            case Action::Block:
                return Result::Lose;
            default:
                assert( false );
            }
        case Action::Lunge:
            switch( opp.action ) {
            case Action::Block:
                return Result::Win;
            case Action::Attack:
                return Result::Tie;
            case Action::Parry:
                return Result::Lose;
            default:
                assert( false );
            }
        case Action::Parry:
            switch( opp.action ) {
            case Action::Lunge:
                return Result::Win;
            case Action::Block:
                return Result::Tie;
            case Action::Attack:
                return Result::Lose;
            default:
                assert( false );
            }
        case Action::Block:
            switch( opp.action ) {
            case Action::Attack:
                return Result::Win;
            case Action::Parry:
                return Result::Tie;
            case Action::Lunge:
                return Result::Lose;
            default:
                assert( false );
            }
        default:
            assert( false );
        }
        return Result::Tie;
    }

    Round Round::operator=( const Round& rhs )
    {
        myMove = rhs.myMove;
        oppsMove = rhs.oppsMove;
        result = rhs.result;
        return *this;
    }

    Match::Match( unsigned int targetScore , unsigned int rounds ) :
        winning_score( targetScore ) , n_rounds( rounds) , results() , in_progress( true )
    {
        results.reserve( rounds );
    }

    vector<Action> Match::legalActions() const
    {
        typedef unsigned int ActionBits;

        // Make a bitfield representing the four legal actions.
        const ActionBits ATTACK = 0x1;
        const ActionBits PARRY = 0x2;
        const ActionBits BLOCK = 0x4;
        const ActionBits LUNGE = 0x8;

        const auto actionBitsToVector = [=](ActionBits ab) -> vector<Action> {
            vector<Action> vec;
            if( ab == 0 ) // Nothing is allowed
                ab = ATTACK | PARRY | BLOCK | LUNGE; // So allow all actions
            if( (ATTACK & ab) == ATTACK )
                vec.push_back( Action::Attack );
            if( (PARRY & ab) == PARRY )
                vec.push_back( Action::Parry );
            if( (BLOCK & ab) == BLOCK )
                vec.push_back( Action::Block );
            if( (LUNGE & ab) == LUNGE )
                vec.push_back( Action::Lunge );
            return vec;
        };

        auto availableActions = ATTACK | PARRY | BLOCK | LUNGE;

        const auto lastResult = *results.rbegin();

        // If a point was scored in the last round all actions are available.
        if( lastResult.result != Result::Tie ) {
            return actionBitsToVector( availableActions );
        }

        // If the heights do not match, both players may no longer
        // select the same action (height is not restricted)
        // as the previous tying rounds, until a point is scored,
        // or all 4 actions have been filled.
        if( lastResult.myMove.height != lastResult.oppsMove.height ) {
            for( auto it = results.rbegin() ; it!= results.rend() ; ++it ) {
                if( it->result != Result::Tie )
                    break;
                else {
                    switch( it->myMove.action )
                    {
                    case Action::Attack:
                        availableActions &= ~ATTACK;
                        break;
                    case Action::Parry:
                        availableActions &= ~PARRY;
                        break;
                    case Action::Block:
                        availableActions &= ~BLOCK;
                        break;
                    case Action::Lunge:
                        availableActions &= ~LUNGE;
                        break;
                    default:
                        break;
                    }
                }
            }
            return actionBitsToVector( availableActions );
        }

        // Attack vs. Lunge
        if( lastResult.myMove.action == Action::Attack &&
            lastResult.oppsMove.action == Action::Lunge ) {
                return actionBitsToVector( PARRY | BLOCK );
        }
        if( lastResult.myMove.action == Action::Lunge &&
            lastResult.oppsMove.action == Action::Attack ) {
                return actionBitsToVector( ATTACK | LUNGE );
        }

        // Block vs Parry
        if( lastResult.myMove.action == Action::Block &&
            lastResult.oppsMove.action == Action::Parry ) {
                return actionBitsToVector( ATTACK | LUNGE );
        }
        if( lastResult.myMove.action == Action::Parry &&
            lastResult.oppsMove.action == Action::Block ) {
                return actionBitsToVector( BLOCK | PARRY );
        }
        return actionBitsToVector( availableActions );
    }

    unsigned int Match::myScore() const
    {
        return count_if( begin(results) , end(results) ,
            [=](const Round& r) {
                return r.result == Result::Win;
        });
    }

    unsigned int Match::oppsScore() const
    {
        return count_if( begin(results) , end(results) ,
            [=](const Round& r) {
                return r.result == Result::Lose;
        });
    }

    string Match::nextRound( const string& myMove , const string& oppsMove )
    {
        if( !in_progress )
            return "Match has already finished.\n";

        stringstream output;
        output << "Round " << results.size()+1 << ": ";
        bool parseSuccessful = true;
        auto getMove = [&]( const string& s ) {
            if( s.length() < 2 ) {
                output << "\nError: Move " << s << " does not have enough characters.";
                return Move();
            }
            Action a = Action::UNITIALIZED;
            switch( s[0] )
            {
            case 'a':
            case 'A':
                a = Action::Attack;
                break;
            case 'b':
            case 'B':
                a = Action::Block;
                break;
            case 'l':
            case 'L':
                a = Action::Lunge;
                break;
            case 'p':
            case 'P':
                a = Action::Parry;
                break;
            default:
                parseSuccessful = false;
                output << "\nFailed to parse action part (" << s[0] << ") of " << s;
                break;
            }

            Height h = Height::UNITIALIZED;
            switch( s[1] )
            {
            case 'h':
            case 'H':
                h = Height::Head;
                break;
            case 'c':
            case 'C':
                h = Height::Chest;
                break;
            case 'f':
            case 'F':
                h = Height::Feet;
                break;
            default:
                parseSuccessful = false;
                output << "\nFailed to parse height part (" << s[1] << ") of " << s;
                break;
            }

            if( a == Action::UNITIALIZED || h == Height::UNITIALIZED )
                return Move();
            else
                return Move( a , h );
            };

        Round thisRound( getMove( myMove ),  getMove( oppsMove ) );

        if ( parseSuccessful ) {
            output << "Previous round: " << myMove << " vs " << oppsMove << " - ";
            switch( thisRound.result )
            {
            case Result::Win:
                output << myMove + " Wins! ";
                break;
            case Result::Lose:
                output << oppsMove + " Wins! ";
                break;
            case Result::Tie:
                output << "Tie! ";
                break;
            default:
                assert( false );
                break;
            }

            results.push_back( thisRound );
            const auto score_me = myScore();
            const auto score_opp = oppsScore();
            output << "Score is now " << score_me << "-" << score_opp << ".";

            if( score_me >= winning_score ) {
                output << "\n\tI win! ";
                in_progress = false;
            }
            if( score_opp >= winning_score ) {
                output << "\n\tI lose. ";
                in_progress = false;
            }
            if( results.size() >= n_rounds ) {
                output << "\n\tTime's up. ";
                if( score_me == score_opp )
                    output << "Match drawn. ";
                else
                    output << "I " << (score_me > score_opp ? "win! " : "lose. " );
                in_progress = false;
            }

            if (!in_progress ) {
                output << "Final score: " << score_me << "-" << score_opp << endl;
            }
        }
        return output.str();
    }

just noticing a potential code flaw - when you code for a block, it still returns the move of a lunge! -- remember, per the rules, no editing is allowed until you are defeated

Good point. That may mean the AI attempts illegal moves. What happens in that situation?

I'd also like to add that I consider the framework public and all who wish to borrow it and just rewrite the two AI functions are free to do so.

any illegal move is an instant round loss.

UNITIALIZED?!

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


text:
Generate N number of "Go First" dice
Background
As described here http://www.ericharshbarger.org/dice/#gofirst_4d12, "Go First" Dice is a set of four dice, each with unique numbering, so that:

There will never be a tie. Each die has a unique set of numbers.
Regardless of what subset of dice are rolled against one another, each player will always have an equal chance of rolling the high number.

Here is the specific numbering for the four dice mentioned, as an example:
DICE COUNT: 4
FACE COUNT: 12
D1: 1,8,11,14,19,22,27,30,35,38,41,48
D2: 2,7,10,15,18,23,26,31,34,39,42,47
D3: 3,6,12,13,17,24,25,32,36,37,43,46
D4: 4,5, 9,16,20,21,28,29,33,40,44,45

(via)
Goal
Without requiring any particular result, I would like to be able to generate a set of N "Go First" dice... Such that, example output might look like so (formatted, python console):
    >>> generate_dice(players=4)
    [[1,8,11,14,19,22,27,30,35,38,41,48],
     [2,7,10,15,18,23,26,31,34,39,42,47],
     [3,6,12,13,17,24,25,32,36,37,43,46],
     [4,5,9,16,20,21,28,29,33,40,44,45]]

The number of sides here is chosen just for example purposes, because it matches the other example given. The number of sides of the dice can be determined by the algorithm used.
Ideally the solution would be in Python, but I can also read PHP, Javascript, some Ruby, quite well.
I'm honestly puzzling over this, and would love to understand what terminology/math I should have studied to figure this out. I've tried to explain it before, but seem to be having trouble not using words that imply too many things about what should be generated, and what odds should be, etc. I'm specifically interested in being able to generate "a set of N 'Go First' dice".
Extra
Here's some ugly python, to "prove" the dice, and perhaps give an example.
def fair_chance(die1, die2):
    wins = 0
    losses = 0
    ties = 0
    for i in die1:
        for x in die2:
            if cmp(i, x) < 0:
                losses += 1
            if cmp(i, x) > 0:
                wins += 1
            if cmp(i, x) == 0:
                ties += 1
    if wins == losses and losses != 0 and ties == 0:
        return True
    return False

Give the above example dice:
D1 = [1,8,11,14,19,22,27,30,35,38,41,48]
D2 = [2,7,10,15,18,23,26,31,34,39,42,47]
D3 = [3,6,12,13,17,24,25,32,36,37,43,46]
D4 = [4,5, 9,16,20,21,28,29,33,40,44,45]

fair_chance(D1, D2)  # True
fair_chance(D1, D3)  # True
fair_chance(D1, D4)  # True
fair_chance(D2, D3)  # True
fair_chance(D2, D4)  # True
fair_chance(D3, D4)  # True

Thus, the function generate_dice should work, such that output in a Python shell would look like this:
>>> dice = generate_dice(players=4)
>>> D1 = dice[0]
>>> D2 = dice[1]
>>> D3 = dice[2]
>>> D4 = dice[3]
>>> fair_chance(D1, D2)
True
>>> fair_chance(D1, D3)
True
>>> fair_chance(D1, D4)
True
>>> fair_chance(D2, D3)
True
>>> fair_chance(D2, D4)
True
>>> fair_chance(D3, D4)
True

What is the objective winning criterion?

Also note: your "proving" code only checks pairs, but the spec requires that "Regardless of what subset of dice are rolled against one another, each player will always have an equal chance of rolling the high number" (my emphasis).

It's fairly easy to prove a basic constraint on the number of sides the dice must have (assuming they each have the same number of sides). If we have N dice each having D sides and we want a fair result for any 1 < M <= N subset, we require D^M == 0 (mod M). Therefore D must be a multiple of the Nth primorial number.

My python is a little rusty because I haven't used it in a very long time, but how about something like this:
def generate_dice(count, sides = 12):
  dice = []
  for i in range(count):
    dice.append([])

  value = 0
  for sindex in range(sides):
    if sindex % 2:
      for dindex in range(count):
        value += 1
        dice[dindex].append(value)
    else:
      for dindex in reversed(range(count)):
        value += 1
        dice[dindex].append(value)
  return dice

The pattern here is simpler than the one you linked, but it appears to work as long as the number of sides on the dice is even. I originally did this in C# and then converted it to python.

The spec requires that "Regardless of what subset of dice are rolled against one another, each player will always have an equal chance of rolling the high number"; your generate_dice with count=3 and sides=12 produces dice which are fair in pairs but in triples win in proportion 584:572:572.

Well, I believe that this deals with telescoping series. As it turns out, the number of dice and number of sides you use is very important. For example, try to make 4, 4 sided dice that fits the same requirement.
Using the numbers from 1 to 16, one of the dice has to get the number 16.
Which ever dice has 16 already has a 25% chance of landing on the highest number when all 4 are rolled. However, the chance that any particular dice is first must = 25%. Thus, the remaining numbers must have 0% chance of being the highest number. This makes the first dice [1,2,3,16]. However this doesn't fit the requirement that when rolling 2 dice, you still have a equal probability of going first. Now you only have 25% instead of 50%. Thus when you have 4 dice, you must have more than 4 sides for these requirements to work.
I think the fact that they used 4 d12 is not just by chance. I would bet it's the minimum number of sides for 4 dice that works. I think if 4d8 or 4d6 worked, they would have just done that, because it's simpler to prove correct.
Thus, with 4 dice, you need a number of sides which is >=12 to meet all the properties.
In the example, the die with the highest number (48) has only a 1/12 of getting that number. Since this die has a 1/12 of going first, it should also have a 1/12 of going last, so it gets a (1).
Notice that the relative order of the numbers of each dice forms a sort of palindrome of pairs.
(1 4) (3 2) (3 2) (3 2) (3 2) (1 4) the first dice sequence
This is obviously on purpose. I'd check to see if other palindromes have the same property.

Your analysis is slightly flawed. In your case of rolling 4 dice, the die with the 16 doesn't have to be [1,2,3,16] because it's rolled against 3 others. If it's e.g. [4,5,6,16] and one of the others is [1,2,x,y] then it can only win with the 16. I believe it's still impossible to make 4 4-side dice which work (at a guess you would need to use http://oeis.org/A003418 for the number of sides), but proving it requires a more detailed analysis or a different insight.

Different insight posted as a comment to the question.


text:
Recreate the classic snake Game
The challenge is to create the classic Snake game using as few bytes as possible.
Here are the requirements:

The game must be implemented in a typical 2-dimensional layout. The snake should be able to grow significantly within the bounds of the map (this really means, don't make your map too small, use your discretion here).
A user may move the snake using keys of your choosing, however, the snake cannot double back on itself (e.g. if it is going West it cannot go East without first going North or South). A snake ought to be able to travel in all 4 directions: up, down, left, right (North, South, West, East).
Snake starts off as length 1, each time it eats a "food" object it grows +1 in length
Food objects are randomly placed in locations other than those occupied by the snake
If the Snake hits itself or a wall the game is ended
When the game has been ended the literal "Score: [score]" is displayed where [score] is the number of food items eaten during the game. So, for example, if the snake has eaten 4 "foods" (and therefore has a length of 5) when the game ends, "Score: 4" will be printed.
No compression algorithms unless they are explicitly defined in your code.

Here's my solution, 908 Bytes, Python 2.7
import random as r
import curses as c
def g(s,w,l):
 while 1:
  p=[r.randrange(0,w),r.randrange(0,l)]
  for l in s:
   if l==p:continue
  return p
s=[]
d=[0,1]
p=k=n=0
e=100
v={65:[-1,0],66:[1,0],68:[0,-1],67:[0,1]}
z=c.initscr()
w,l=z.getmaxyx()[0],z.getmaxyx()[1]
c.noecho()
z.clear()
x=g(s,w,l)
s.append([w/2,l/2])
z.nodelay(1)
q=lambda h,i:range(h,len(i))
while k!=101:
 k=z.getch()
 if k in v and not (d[0]==(v[k][0]*-1) and d[1]==(v[k][1]*-1)):d=v[k]
 f=[0,0]
 for i in q(0,s):
  if i == 0:
   f=[s[i][0],s[i][1]]
   s[i][0]+=d[0]
   s[i][1]+=d[1]
  else:s[i],f=f,s[i]
 if s[0]==x:
  n+=1
  s.append(f)
  x=g(s,w,l)
 z.clear()
 if s[0][0]>=w or s[0][1]>=l or s[0][0]<0 or s[0][1]<0:break
 for i in q(1,s):
  if s[0] == s[i]: k = 101
 for i in q(0,s):z.addch(s[i][0],s[i][1],"X")
 z.addch(x[0],x[1],"O")
 z.move(0,0)
 z.refresh()
 if d[1]!=0:c.napms(e/2)
 else:c.napms(e)
c.endwin()
print 'Score: %s'%n

possible duplicate of Recreate a 'Snake' game in a console/terminal

@copy some people don't like to be restricted to terminals.

does the 'snake cannot double back' rule apply if the snake is length=1?

@chron, yes it does. At all times, snakes may only (truly) turn two ways, left and right.

Ruby 1.9 + SDL (341 324 316)
Here's a first attempt at a Ruby version using the SDL library.  I can save 6 characters if I'm allowed to load the SDL library using -rsdl on the command line instead of the require statement.
require'sdl'
f=o=d=3
s=SDL::Screen.open l=32,l,0,0
r=*0..l*l
loop{f==o ?f=(r-$*).sample: $*.shift
/yU/=~"#{e=SDL::Event.poll}"&&(v=e.sym%4)&&d+v!=3&&d=v
$><<"Score #{$*.size}"&&exit if$*.index(n=o+[-1,-l,l,1][d])||n<0||n>=l*l||d%3<1&&n/l!=o/l
$*<<o=n
r.map{|i|s[i%l,i/l]=[[f,*$*].index(i)?0:255]*3}
s.flip
sleep 0.1}

The snake segments and food pieces are represented using black pixels, the grid size is currently 32*32.  You can control with the arrow keys (or any keys really, the keycode mod 4 indexes the direction array [LEFT, UP, DOWN, RIGHT]).  I think there's definitely room for improvement here, especially in the death-checking IF statement.
I've vastly improved this over the previous version, hopefully it more closely matches the spirit of the question now.  There's one thing I need to fix to comply with the spec, which is that food can currently spawn inside the tail. Fixed!
Prints the score to stdout after the game is completed.

APL (dzaima/APL), 244 233 bytes
s←2⌿⊂2⌿25
d←?x←2⌿50
o←⍳2
G←P5.G
P5.draw←{G.bg¯1
G.fill←0
s⊢←(1↓s),⊂o+f←⊃⌽s
((⊢≢∪)s)∨~f⊂⍛∊a←⍳x:P5.exit 0⊣⍞←'Score: ',⍕2-⍨≢s
d≡f:s⊢←s,⊂f+2×o⊣d⊢←?x
(t←'center'G.rect,∘2 2)¨2×s
G.fill←'f00'
t+⍨d}
P5.kp←{o≢-n←('sdwa'⍳⍵)⊃1-↓⍬2⍴3⊤2320:o⊢←n}

Golfed from 294 → 244 bytes with the help of dzaima.
Uses WASD controls.
Uses ⎕IO←0 (0-indexing).
The grid is 50x50, on the default 100x100 canvas Processing uses.
Displays score to the console.
Explanation done!
Explanation
s←2⌿⊂2⌿25 snake starts at \$(25,25)\$
d←?x←2⌿50 first food position: 2 random ints in (0,50)
x←2⌿50 save (50,50) in x
o←⍳2 initial snake direction: (0,1)
G←P5.G save namespace as G
P5.draw←{ execute the following each frame:
  G.bg¯1 display white background
  G.fill←0 set fill to black
  s⊢←(1↓s),⊂o+f←⊃⌽s calculate next snake position:
    (1↓s) remove the last tail segment
    ,⊂o+f←⊃⌽s add direction to the front, and append that
    f←⊃⌽s assign head coordinates to f
  ((⊢≢∪)s)∨~f⊂⍛∊a←⍳x:(...) check if the player has lost:
    ((⊢≢∪)s)∨ if snake does not match itself uniquified, or
    ~f⊂⍛∊a←⍳x: head is not within 50x50 grid:
    ⍞←'Score: ',⍕2-⍨≢s display the score in console, and
    P5.exit 0⊣ exit, displaying nothing
  d≡f:s⊢←s,⊂f+2×o⊣d⊢←?x if head matches food, then change food position and increase snake length.
  (t←'center'G.rect,∘2 2)¨2×s draw each position of the snake
    t←'center'G.rect,∘2 2 create function t for drawing the blocks
  G.fill←'f00' set fill to red`
  t+⍨d draw the food
} close draw loop
P5.kp←{...} execute the following each time a key is pressed (⍵ is key name):
  1-↓⍬2⍴3⊤2320 array of directions │0 1│1 0│0 ¯1│¯1 0│
  ('sdwa'⍳⍵)⊃ get key number, index into directions
  n← store direction in n
  o≢- if snake direction is not the opposite of n,(prevents moving backward)
  o⊢←n then change snake direction
Gameplay
(recorded at low fps)

The tio link reports errors for me.

@Anush the tio link isn't supposed to run it, it needs to be run on your system. I left that in by mistake.

JavaScript, 609 bytes

document.write`<canvas id=C width=40 height=40 style='width:180px;height:180px;border:4px solid'`
s=[l={x:9,y:9}]
h=t=0,v=1
r=(x,y,w,h,f)=>{c.fillStyle=f,c.fillRect(x,y,w,h)}
m=n=>{g=4,i=0|38*(R=Math.random)()+1,j=0|38*R()+1,s.map(b=>b.x^i|b.y^j?0:m())},m()
onkeydown=k=>{f={d:[0,1],a:[0,-1],w:[-1,0],s:[1,0]}[k.key],f?(v=f[0],h=f[1]):0}
z=setInterval(w=>z?(focus(),c=C.getContext`2d`,r(0,0,80,80,'#fff'),s.push(l={x:l.x+h,y:l.y+v}),s.splice(0,0>g--),l.x^i|l.y^j?0:t+=!m(),s.map(b=>z&&(0>l.x||0>l.y||39<l.x||39<l.y||b!=l&&b.x==l.x&&b.y==l.y)?z=alert('Score:'+t):r(b.x,b.y,1,1,'#000')),r(i,j,1,1,'#f0f')):0,75)

Use WASD for controls.
JSFiddle

You can remove all the windows and replace the addEventListener with onkeydown=...

Also, parseInt(...) is way longer than ...|0, and you might be able to save some bytes by replacing document with (D=document and then D. Other than that this is a really cool answer!

@Redwolf, cool thanks! I'll update it a bit later, first have to get some actual work done ;-)

-13 bytes: https://pastebin.com/3xZtyEH2

Bugs: Trying to double the snake back on itself ends the game, and there is a missing space between Score: and the score

Bash: 537 533 507 characters
C=$COLUMNS;L=$LINES;D=-1;c=9;r=9;z=(9\ 9);l=;h=1;v=;s=1;d=1
t(){ echo -en "\e[$2;$1H$3";}
b(){ ((f=RANDOM%C+1));((g=RANDOM%L+1));for i in "${z[@]}";do [[ $f\ $g = $i ]]&&b;done;t $f $g F;}
echo $'\e[2J';b
while :;do
read -sn1 -t.1 k
case $k in
w|s)((h))&&h=&&v=${D:$k};;
a|d)((v))&&v=&&h=${D:$k};;
esac
((c+=h));((r+=v))
((c==f&&r==g&&++l))&&b
((c<1||r<1||c>C||r>L))&&break
for i in "${z[@]}";do [[ $c\ $r = $i ]]&&break 2;done
t ${z[-1]} \ ;t $c $r X
z=($c\ $r "${z[@]::l}")
done
echo $'\e[2J\e[H'Score: $l

As it uses the $COLUMNS and $LINES shell variables, it must be run sourced: . snake.sh. The snake can be controlled with the w/a/s/d keys.
I know, it can be easily reduced to 493 characters by using clear to clear the screen, but I prefer to keep it pure bash, without using any external tool.

Very cool solution!

I love bash solutions!

Python 2.7: 869 816 818 817 816 Characters
I hacked this together in the last few hours. It should meet the requirements and is a few characters shorter than mjgpy3's solution (Tried hard, but couldn't get it much shorter. Now I'm tired). Surprisingly, using a game development library like pygame didn't get the python-snake much shorter. Suggestions and tips how to make it shorter are highly appreciated. I hope it's not too cryptic.
This is the result:
import pygame as p
from random import randint as r
p.init();l=20
c=p.time.Clock()
dp=p.display;w=p.display.set_mode((500,)*2)
C=p.Color;b=C(0,0,0);g=C(0,99,0)
D=(0,1);U=(0,-1);L=(-1,0);R=(1,0)
S=[R];d=R;n=[]
O=lambda t:{U:D,R:L,D:U,L:R}[t]
def Q(e):print "Score: %i"%(len(S)-1);p.quit()
def K(e):global d;_={276:L,273:U,274:D,275:R}.get(e.key,(0,0));d=not _==O(d) and _ or d
def N(S):[p.draw.rect(w,g,[x[0]*l,x[1]*l,l,l]) for x in S+n]
def M():n=(r(0,24),r(0,24));return n not in S and n or M()
A=lambda s,o:tuple(x+y for x,y in zip(s,o))
n=[M()]
while True:
 w.fill(b);[{12:Q,2:K}.get(e.type,lambda e:e)(e) for e in p.event.get()]
 if not (0<=S[-1][0]<25 and 0<=S[-1][1]<25) or A(S[-1],d) in S: Q(e)
 if A(S[-1],d) in n: S.append(A(S[-1],d));n=[M()]
 else: S.append(A(S[-1],d));S.pop(0)
 N(S);dp.update();c.tick(6)

EDIT: I could reduce it to 816 Bytes, yay! :) Fixed the score
EDIT2: Pasted the wrong version accidentally
Here is a commented version:
import pygame as p
from random import randint as r

# initialize pygame
p.init()

# the game consists of 25*25 blocks,with each block 20*20 pixels
l=20

# initialize the main loop clock
c=p.time.Clock()

# open the window
dp=p.display;w=p.display.set_mode((500,)*2)

# define black and green colors
C=p.Color;b=C(0,0,0);g=C(0,99,0)

# Directions of the snake: down, up, left, right
D=(0,1);U=(0,-1);L=(-1,0);R=(1,0)

# S is the snake, d is the current direction and n is the array of foods
S=[R];d=R;n=[]

# get the opposite direction of a direction to forbid double backing
O=lambda t:{U:D,R:L,D:U,L:R}[t]

# print the score and quit
def Q(e):print "Score: %i"%(len(S)-1);p.quit()

# update the direction (this is a key press handler)
def K(e):global d;_={276:L,273:U,274:D,275:R}.get(e.key,(0,0));d=not _==O(d) and _ or d

# draw the snake and food boxes
def N(S):[p.draw.rect(w,g,[x[0]*l,x[1]*l,l,l]) for x in S+n]

# place new food on the map not colliding with the snake
def M():n=(r(0,24),r(0,24));return n not in S and n or M()

# A((1,1), (-2, 1)) -> (-1,2)
A=lambda s,o:tuple(x+y for x,y in zip(s,o))

# initialize food array
n=[M()]

while True:
 # fill the screen black
 w.fill(b)
 # get quit or key press events and execute the event handlers
 [{12:Q,2:K}.get(e.type,lambda e:e)(e) for e in p.event.get()]

 # check if snake hits map boundaries or itself
 if not (0<=S[-1][0]<25 and 0<=S[-1][1]<25) or A(S[-1],d) in S: Q(e)

 # check if snake is eating food at the moment and append one to the snake's length
 if A(S[-1],d) in n: S.append(A(S[-1],d));n=[M()]

 # move the snake in the current direction
 else: S.append(A(S[-1],d));S.pop(0)

 # draw the map and limit the main loop to 6 frames per second
 N(S);dp.update();c.tick(6)

I kept getting this error message "Segmentation fault (core dumped)." And it seems like the score is off by 1 (not really a big deal. Very cool answer though.

Thanks :) I get that Segmentation fauklt message too. Didn't figure it out yet. Fixed the score and reduced the size :) this is fun.

you could make the green darker, instead of 255, use 99, then that'll be a byte taken off

@KrystosTheOverlord hahah yes good point :D

Java, 2343 2239
Not exactly concise, but I believe it follows all the requirements.
Snake class
import javax.swing.*;
public class S extends JFrame{
S(){add(new B());setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setSize(320,340);setVisible(true);}
public static void main(String[]a){new S();}}

Board class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class B extends JPanel implements ActionListener{
int W=300;int H=300;int DS=10;int AD=900;int RP=29;int D=140;int x[]=new int[AD];int y[]=new int[AD];int d;int ax;int ay;boolean l=false;boolean r=true;boolean u=false;boolean dn=false;boolean ig=true;Timer t;Image b;Image a;Image h;
B(){addKeyListener(new T());setBackground(Color.black);ImageIcon id=new ImageIcon(this.getClass().getResource("d.png"));b=id.getImage();ImageIcon ia=new ImageIcon(this.getClass().getResource("a.png"));a=ia.getImage();ImageIcon ih=new ImageIcon(this.getClass().getResource("h.png"));h=ih.getImage();setFocusable(true);i();}
void i(){d=3;for(int z=0;z<d;z++){x[z]=50-z*10;y[z]=50;}l();t=new Timer(D,this);t.start();}
public void p(Graphics g){super.paint(g);if(i){g.drawImage(a,ax,ay,this);for(int z=0;z<d;z++){if(z==0)g.drawImage(h,x[z],y[z],this);else g.drawImage(b,x[z],y[z],this);}Toolkit.getDefaultToolkit().sync();g.dispose();}else{g(g);}}
void g(Graphics g){String ms="Score:";Font sm=new Font("Courier",Font.PLAIN,12);FontMetrics me=this.getFontMetrics(sm);g.setColor(Color.white);g.setFont(sm);g.drawString(ms+d,(W-me.stringWidth(ms)),H);}
void c(){if((x[0]==ax)&&(y[0]==ay)){d++;l();}}
void m(){for(int z=d;z>0;z--){x[z]=x[(z-1)]; y[z]=y[(z-1)];}if(l){x[0]-=DS;}if (r){x[0]+=DS;}if(u){y[0]-=DS;}if(dn){y[0]+=DS;}}
void cc(){for(int z=d;z>0;z--){if((z>4)&&(x[0]==x[z])&&(y[0]==y[z])){ig=false;}}if(y[0]>H){ig=false;}if(y[0]<0){ig=false;}if(x[0]> W){ig=false;}if(x[0]<0){ig=false;}}
void l(){int r=(int)(Math.random()*RP);ax=((r*DS));r=(int)(Math.random()*RP);ay=((r*DS));}
public void actionPerformed(ActionEvent e){if(ig){c();cc();m();}repaint();}
class T extends KeyAdapter{public void keyPressed(KeyEvent e){int k=e.getKeyCode();if((k==KeyEvent.VK_LEFT)&&(!r)){l=true;u=false;dn=false;}if((k==KeyEvent.VK_RIGHT)&&(!l)){r=true;u=false;dn=false;}if((k==KeyEvent.VK_UP)&&(!dn)){u=true;r=false;l=false;}if((k==KeyEvent.VK_DOWN)&&(!u)){dn=true;r=false;l=false;}}}}

Screenshot

Commentary
A while back I visited a website called zetcode which provided some tutorials for creating classic 2D games in Java.  The code provided is strongly influenced by the tutorial that was provided for the Snake game... I think at this time I just started coding classic games and followed the tutorial to a 'T'.
I'll make an edit later and add a link to an executable so people can play the game.

EDITS

9/9/12: I am unable to properly load the images from the resource folder.  I'll continue to work through this issue in an attempt to prove that my code works and meets all criteria of the question.
9/11/12: I am going to continue working on getting the pictures to load from the resource file.  I added a picture provided from the ZetCode tutorial.

Great, I look forward to trying it!

Is there a link to the executable en-route:)

@BrianBishop Sorry dude, I never did figure out what I was doing incorrectly with my image files in the resource file.  Everything compiles, but the images never popup.

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