text:
Syntax Highlighting for Greater Golf!
Golfers.
Together, we have banded together to produce code that is concise, is functionally beautiful and is uglier then the Phantom of the Opera from the original novel.
The time has come for us to bring beauty back to the world of programming. With color. In a way that is concise, functionally beautiful is uglier then the Phantom of the Opera from the original novel.
We're gonna be coding a colorful syntax highlighter. In the shortest amount of code possible.
You will receive via an input file or Stdin a valid C file. The C file will use the line convention of your choice, and will only contain ASCII characters 32-126. You have to turn it into a HTML file that displays correctly at least in Chrome, that shows the source code  with syntax highlighting. The output may be in a file or to Stdout.
You must highlight:

All strings and characters (including the quote characters) in Green (#00FF00). The strings may contain escaped characters.
All C reserved words in Blue (#0000FF).
All comments in Yellow (#FFFF00).
All C preprocessor directives in Pink (#FF00FF).

The output when displayed in Chrome must:

Be in a fixed-width font
Display new lines wherever they appeared in the original source
Accurately reproduce whitespace. A tab character should be taken as being 4 spaces.

Bonuses

x 0.9 if you include line numbers. Line numbers must be able to reach at least 99999. All source must still be aligned - so, source code with smaller line numbers should still start at the same position as source code with higher line numbers
x 0.8 if background of each line is alternated between light gray (#C0C0C0) and white (#FFFFFF)
x 0.9 if your source code is written in C, and can correctly format itself.

Scoring
This is code golf. Your score is the amount of bytes of your source code multiplied by any bonuses. The winner is the golfer with the lowest score.

what if a preprocessor directive includes a reserved word?  What if a string or comment includes a reserved word?

@Charles the standard behaviour of the bigger IDE's is, that comments will not be further highlighted, meaning comments stay comments. haven't been working with preprocessor directives much, but wikipedia also here does not further highlight code... also strings are strings, they need no further evaluation...

Confirming what Vogel612 says is the correct behaviour

"valid at least in Chrome", or "displays correctly at least in Chrome"?

Displays correctly. Editing now.

I think there should be a bonus if you write this thing in C.

Actually... so did I - providing that it could highlight itself. I was concerned non-c folk might think it unfair. Does a x 0.9 sound fair?

I think so.  That seems like a fair amount.

"Your score is the amount of bytes of your source code multiplied by any bonuses." Um? Doesn't this mean your score will be higher if you use more characters? If lower means better, doesn't getting bonuses then make your score worse?

@Trimsty Wait a second, I'm an idiot. xD Nevermind.

Worst colors ever!

Perl 769 chars * 0.9 * 0.8 = 554
Probably still some improvements to be made on some of the regexes, but it's slowly getting there!
$_=join"",<>;$s="<tt class";$c="</tt>";$d=counter;$e=color;s/\t/    /g;s!<!<!g;s!>!>!g;s!^#.+(?=$|
)!$s=d>$&$c!gm;s!//.+!$s=c>$&$c!g;s|(['"]).*?(?<!\\)(\\\\)*\1|($h=$&)=~s!/!/!g;"$s=s>$h$c"|smeg;s!/\*.*?\*/!$s=c>$&$c!smg;s!\b(_Packed|(au|go)to|break|c(ase|har|onst|ontinue)|d(efault|o|ouble)|e(lse|num|xtern)|f(loat|or)|if|int|long|re(gister|turn)|short|(un)?signed|s(izeof|tatic|truct|witch)|typedef|union|vo(id|latile)|while)\b!$s=r>$&$c!g;s!=(\w)>.+?$c!join"$c
$s=$1>",split$/,$&!smeg;s!
!
!g;print"

$_"

Slightly less obfuscated version with comments:
$_=join"",<>; # slurp file
$s="<tt class"; # used later - use <tt/> instead of , fewer chars!
$c="</tt>";
$d=counter;
$e=color;
s/\t/    /g; # convert tabs to spaces
s!<!<!g; # htmlentity < and >
s!>!>!g;
s!^#.+(?=$|\n)!$s=d>$&$c!gm; # directives
s!//.+!$s=c>$&$c!g; # inline comments
s|(['"]).*?(?<!\\)(\\\\)*\1|($h=$&)=~s!/!/!g;"$s=s>$h$c"|smeg; # strings, might have 0 length - thanks @Einacio; work-around string that contain /* by converting them to HTML entities
s!/\*.*?\*/!$s=c>$&$c!smg; # multi-line comments
s!\b(_Packed|(au|go)to|break|c(ase|har|onst|ontinue)|d(efault|o|ouble)|e(lse|num|xtern)|f(loat|or)|if|int|long|re(gister|turn)|short|(un)?signed|s(izeof|tatic|truct|witch)|typedef|union|vo(id|latile)|while)\b!$s=r>$&$c!g; # reserved words, don't optimise this too much! - thanks @bwoebi
s!=(\w)>.+?$c!join"$c
$s=$1>",split$/,$&!smeg; # any multi-line string/comment, ensure s are repeated
s!\n!
!g; # strip newlines, replace with
, don't need 	 _or_
 - thanks @xfix!
print"

$_"

Now successfully highlights @xfix's entry.
Borrowed the idea to drop
 from @xfix's entry, thank you!
Example of output for @xfix's solution.

Your solution cannot highlight my solution correctly, because it doesn't escape HTML markup, and doesn't show whitespace properly.

Ahhh! I forgot white-space: pre, I'll get that added and work on some other escaping. Still much to be done on this I feel!

In HTML5,
 and 	 are completely optional, so I simply ignored them.

You actually could save some chars by using sometimes the full keyword name in regex. E.g. if|int is one char less than i(f|nt). Or d(efault|o|ouble) is another char less than d(efault|o(uble)?).

on the fiddle the '\' on line 61 is not marked as string. is an error of the example or an edge case failing?

@xfix, I'm sure I should have known that! Thank you!

@bwoebi, you're right! Trying to group too much, I'll update shortly, thank you!

@Einacio, I think it's an oversight, well spotted! I'll get on to that as well! Thanks!

The code will still work if you move the

1");while(~(c=getchar())){if(!e&&q){if(q==c){printf("%c",c);q=0;continue;}}else if(isalpha(c)&&p<8){b[p++]=c;continue;}else if(b[0]){for(i=0;i<32;i++){s!=2&&!strcmp(k[i],b)&&(printf("%s",b),b[0]=0);}printf("%s",b);memset(b,0,9);}p=0;switch(c){case'<':printf("<");goto e;case'&':printf("&");goto e;case 92:putchar(c);e^=1;goto e;case'/':q||1==s?putchar('/'):3==s?(printf("*/"),s=0):(s=1);break;case'*':if(s==1){s=2;printf("/*");}else if(s==2){s=3;}else{goto d;}break;case 39:case'"':e||q||(q=c,printf(""));e=0;goto d;case 10:l+=1;printf("
%d",l);if(p&&e){case'#':e=0;q||(p=1,printf(""));}else{p=0;}default:d:10!=c&&putchar(c);e:s=s/2*2;}}puts(b);}

And the longer version (which is as readable as real program, aside of few code golf tricks I didn't think I could apply easily while golfing the program.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define ARRAY_SIZE(array) (sizeof(array) / sizeof *(array))
/* Sample comment. */
int main(void) {
    const char *keywords[] = {
        "auto",     "break",    "case",     "char",     "const",
        "continue", "default",  "do",       "double",   "else",
        "enum",     "extern",   "float",    "for",      "goto",
        "if",       "int",      "long",     "register", "return",
        "short",    "signed",   "sizeof",   "static",   "struct",
        "switch",   "typedef",  "union",    "unsigned", "void",
        "volatile", "while",
    };
    int character;
    int preprocessor = 0;
    int escape = 0;
    char buffer[9] = {0};
    int pos = 0;
    int line = 1;
    int quote = 0;
    int comment_state = 0;
    printf("

1");
    while ((character = getchar()) != EOF) {
        if (!escape && quote) {
            if (quote == character) {
                printf("%c", character);
                quote = 0;
                continue;
            }
        }
        else if (isalpha(character) && pos < 8) {
            buffer[pos] = character;
            pos += 1;
            continue;
        }
        else if (buffer[0]) {
            int i;
            for (i = 0; i < ARRAY_SIZE(keywords); i++) {
                if (comment_state != 2 && strcmp(keywords[i], buffer) == 0) {
                    printf("%s", buffer);
                    buffer[0] = 0;
                }
            }
            printf("%s", buffer);
            memset(buffer, 0, 9);
        }
        pos = 0;
        switch (character) {
        case '<':
            printf("<");
            goto e;
        case '&':
            printf("&");
            goto e;
        case '\\':
            putchar(character);
            escape ^= 1;
            goto e;
        case '/':
            if (quote || comment_state == 1) {
                putchar('/');
            }
            else if (comment_state == 3) {
                printf("*/");
                comment_state = 0;
            }
            else {
                comment_state = 1;
            }
            break;
        case '*':
            if (comment_state == 1) {
                comment_state = 2;
                printf("/*");
            }
            else if (comment_state == 2) {
                comment_state = 3;
            }
            else {
                goto d;
            }
            break;
        case '\'':
        case '"':
            if (!escape && !quote) {
                quote = character;
                printf("");
            }
            escape = 0;
            goto d;
        case '\n':
            line += 1;
            printf("
%d", line);

            /* Execute next only if conditions match. */
            if (preprocessor && escape) {
        case '#':
                escape = 0;
                if (!quote) {
                    preprocessor = 1;
                    printf("");
                }
            }
            else {
                preprocessor = 0;
            }
            /* fallthru */
        default:
        d:
            if (character != '\n') putchar(character);
        e:
            comment_state = comment_state / 2 * 2;
        }
    }
    printf("%s
", buffer);
}

The output looks fantastic!

@lochok: And it's now shortened to 1200 bytes. This is still longer than Perl solution, but now the gap is smaller.

Your code doesn't seem to work with multiline comments.

PHP 606 bytes × 0.9 × 0.8 = 436

<?php $p='preg_match';preg_match_all('_\w+|("|\')(\\\\?.)*?\1|#(.(?!/[/*]))*|//.*|(?s)/\*.*?\*/|.+?_',stream_get_contents(STDIN),$m);foreach($m[0]as$t)echo''.preg_replace("/\r?\n/",'
',htmlentities($t));

Formatted:

<?php
$p='preg_match';
preg_match_all('_\w+|("|\')(\\\\?.)*?\1|#(.(?!/[/*]))*|//.*|(?s)/\*.*?\*/|.+?_',
    stream_get_contents(STDIN),$m);
foreach($m[0]as$t)
    echo''.preg_replace("/\r?\n/",'
',htmlentities($t));

Reads from stdin and writes to stdout.
Accepted line endings are \n and \r\n.
Does line numbers and line color alternation.
I used slightly different colors so I could bear to look at it, though not in a way that affects the byte count.
I don't have Chrome to test it although it's fine in Firefox.

C++ - 5067 bytes4612 * 0.9 * 0.8 = 3320 (* 0.9 = 2988 if being able to format itself counts - it's written in C++)
I realize that this is larger than the solutions already presented here, but I've decided to post this anyway because I started working on my version before the C solution by xfix was posted.

It works with multiline comments
It outputs HTML that has errors (but it displays correctly in Chrome)
It reads out of input.c and produces output.html

A half of this is the large array of C and C++ keywords.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <locale>
#define B break
#define Z(a,b)if(s[i]==a){z=b;o+=OP+p(s[i]);i++;B;}
#define V(a,b)if(e(s,i,a)){z=b;o+=OC+p(s.substr(i,2));i+=2;B;}
#define N(a) if(s[i]=='\n'){a;o+=nl();i++;B;}
#define Q(a)if(e(s,i,"\\")){o+=p(s.substr(i,2));i+=2;B;}if(s[i]==a){z=0;o+=p(s[i])+CL;i++;B;}
#define C case
using namespace std;string k[]={"__abstract","__alignof","_Alignas","_alignof","and","and_eq","__asm","_asm","asm","__assume","_assume","auto","__based","_based","bitand","bitor","bool","_Bool","__box","break","__builtin_alignof","_builtin_alignof","__builtin_isfloat","case","catch","__cdecl","_cdecl","_Complex","cdecl","char","class","__compileBreak","_compileBreak","compl","const","const_cast","continue","__declspec","_declspec","default","__delegate","delete","do","double","dynamic_cast","else","enum","__event","__except","_except","explicit","__export","_export","extern","false","__far","_far","far","__far16","_far16","__fastcall","_fastcall","__feacpBreak","_feacpBreak","__finally","_finally","float","for","__forceinline","_forceinline","__fortran","_fortran","fortran","friend","_Generic","__gc","goto","__hook","__huge","_huge","huge","_Imaginary","__identifier","if","__if_exists","__if_not_exists","__inline","_inline","inline","int","__int128","__int16","_int16","__int32","_int32","__int64","_int64","__int8","_int8","__interface","__leave","_leave","long","__multiple_inheritance","_multiple_inheritance","mutable","namespace","__near","_near","near","new","_Noreturn","__nodefault","__nogc","__nontemporal","not","not_eq","__nounwind","__novtordisp","_novtordisp","operator","or","or_eq","__pascal","_pascal","pascal","__pin","__pragma","_pragma","private","__probability","__property","protected","__ptr32","_ptr32","__ptr64","_ptr64","public","__raise","register","reinterpret_cast","restrict","__restrict","__resume","return","__sealed","__serializable","_serializable","short","signed","__single_inheritance","_single_inheritance","sizeof","static","static_cast","_Static_assert","__stdcall","_stdcall","struct","__super","switch","__sysapi","__syscall","_syscall","template","this","__thiscall","_thiscall","throw","_Thread_local","__transient","_transient","true","__try","_try","try","__try_cast","typedef","typeid","typename","__typeof","__unaligned","__unhook","union","unsigned","using","__uuidof","_uuidof","__value","virtual","__virtual_inheritance","_virtual_inheritance","void","volatile","__w64","_w64","__wchar_t","wchar_t","while","xor","xor_eq"};string OS="";string OC="";string OK="";string OP="";string CL="";string NL[]={ "
","
" };bool lo=1;string nl() {lo=!lo;return "
"+NL[lo];}bool r(char c,string s) {for (size_t i=0; i<s.size(); i++)if (c==s[i])return 0;return 0;}bool is(string s,int i) {return !(i<0||i>=s.size())&&((s[i]=='_')||isalpha(s[i]));}bool ic(string s,int i){return !(i<0||i>=s.size())&&(is(s,i)||('0'<=s[i]&&s[i]<='9'));}bool e(string a,int s,string b) {return !(a.size()-s<b.size())&&a.substr(s,b.size())==b;}string p(char c) {switch (c) {C  '&':return "&";C  '\"':return """;C  '\'':return "'";C  '<':return "<";C  '>':return ">";}stringstream s;s<<c;return s.str();}string p(string s) {string ans="";for (size_t i=0; i<s.size(); i++) {ans+=p(s[i]);}return ans;}string h(string s) {int z=0;size_t i=0;string o ="
";o+=NL[1];for (; i<s.size();) {switch (z) {C 0:{Z('#',6)Z('"',3)Z('\'',2)V("//",4)V("/*",5)N()for (size_t j=0; j<201; j++)if (e(s,i,k[j])&&!ic(s,i+k[j].size())) {o+=OK+p(k[j])+CL;i+=k[j].size();B;}if (is(s,i)) {z=7;o+=p(s[i]);i++;if (i+1==s.size()||!ic(s,i+1)) {z=0;}B;}o+=p(s[i]);i++;B;}o+=p(s[i]);i++;B;C  2:Q('\'')C  3:Q('"')C 4:{N(z=0)o+=p(s[i]); i++;B;}C 5:{if (e(s,i,"*/")) {z=0;o+=p(s.substr(i,2))+CL;i+=2;B;}N()o+=p(s[i]);i++;B;}C 6:{if (s[i]=='\n') {int j=i-1;for (; j>=0&&r(s[j],"\n\t "); j--);if (j<0||s[j] != '\\') {z=0;o+=CL+nl();i++;B;}o+=nl();i++;B;}o+=p(s[i]);i++;B;}C 7:{if (i+1==s.size()||!ic(s,i+1)) {z=0;}o+=p(s[i]);i++;B;}}}o+="
";return o;}int main() {ifstream i("input.c");ofstream o("output.html");string cCode((istreambuf_iterator<char>(i)),istreambuf_iterator<char>());o<<h(cCode)<<endl;}

Readable version:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

//The 201 keywords from C and C++. Not sure if all of them are listed here!
const size_t NUMBER_OF_KEYWORDS = 201;
string keywords[] = { "__abstract", "__alignof", "_Alignas", "_alignof", "and",
        "and_eq", "__asm", "_asm", "asm", "__assume", "_assume", "auto",
        "__based", "_based", "bitand", "bitor", "bool", "_Bool", "__box",
        "break", "__builtin_alignof", "_builtin_alignof", "__builtin_isfloat",
        "case", "catch", "__cdecl", "_cdecl", "_Complex", "cdecl", "char",
        "class", "__compileBreak", "_compileBreak", "compl", "const",
        "const_cast", "continue", "__declspec", "_declspec", "default",
        "__delegate", "delete", "do", "double", "dynamic_cast", "else", "enum",
        "__event", "__except", "_except", "explicit", "__export", "_export",
        "extern", "false", "__far", "_far", "far", "__far16", "_far16",
        "__fastcall", "_fastcall", "__feacpBreak", "_feacpBreak", "__finally",
        "_finally", "float", "for", "__forceinline", "_forceinline",
        "__fortran", "_fortran", "fortran", "friend", "_Generic", "__gc",
        "goto", "__hook", "__huge", "_huge", "huge", "_Imaginary",
        "__identifier", "if", "__if_exists", "__if_not_exists", "__inline",
        "_inline", "inline", "int", "__int128", "__int16", "_int16", "__int32",
        "_int32", "__int64", "_int64", "__int8", "_int8", "__interface",
        "__leave", "_leave", "long", "__multiple_inheritance",
        "_multiple_inheritance", "mutable", "namespace", "__near", "_near",
        "near", "new", "_Noreturn", "__nodefault", "__nogc", "__nontemporal",
        "not", "not_eq", "__nounwind", "__novtordisp", "_novtordisp",
        "operator", "or", "or_eq", "__pascal", "_pascal", "pascal", "__pin",
        "__pragma", "_pragma", "private", "__probability", "__property",
        "protected", "__ptr32", "_ptr32", "__ptr64", "_ptr64", "public",
        "__raise", "register", "reinterpret_cast", "restrict", "__restrict",
        "__resume", "return", "__sealed", "__serializable", "_serializable",
        "short", "signed", "__single_inheritance", "_single_inheritance",
        "sizeof", "static", "static_cast", "_Static_assert", "__stdcall",
        "_stdcall", "struct", "__super", "switch", "__sysapi", "__syscall",
        "_syscall", "template", "this", "__thiscall", "_thiscall", "throw",
        "_Thread_local", "__transient", "_transient", "true", "__try", "_try",
        "try", "__try_cast", "typedef", "typeid", "typename", "__typeof",
        "__unaligned", "__unhook", "union", "unsigned", "using", "__uuidof",
        "_uuidof", "__value", "virtual", "__virtual_inheritance",
        "_virtual_inheritance", "void", "volatile", "__w64", "_w64",
        "__wchar_t", "wchar_t", "while", "xor", "xor_eq" };

// Different states
const int NONE = 0;
const int WHITESPACE = 1;
const int CHAR_UNCLOSED = 2;
const int STRING_UNCLOSED = 3;
const int LINE_COMMENT_UNCLOSED = 4;
const int MULTILINE_COMMENT_UNCLOSED = 5;
const int PREPROCESSOR_UNCLOSED = 6;
const int IDENTIFIER = 7;

//Different elements
const string OPEN_STRING = "";
const string CLOSE_STRING = "";
const string OPEN_COMMENT = "";
const string CLOSE_COMMENT = "";
const string OPEN_KEYWORD = "";
const string CLOSE_KEYWORD = "";
const string OPEN_PREPROCESSOR = "";
const string CLOSE_PREPROCESSOR = "";

//Alternating background
const string NEW_LINE[] = { "
", "
" };
bool lineOdd = true;
string getNewLineHTML() {
    lineOdd = !lineOdd;
    return "
" + NEW_LINE[lineOdd];
}

//Check if the character is in the string chars
bool inRange(char c, string chars) {
    for (size_t i = 0; i < chars.size(); i++)
        if (c == chars[i])
            return true;
    return false;
}

//Check if the character is the start of an identifier
bool isIdentifierStart(string input, int i) {
    if (i < 0 || i >= input.size())
        return false;
    return (input[i] == '_') || ('a' <= input[i] && input[i] <= 'z')
            || ('A' <= input[i] && input[i] <= 'Z');
}
//Check if the character is the continuation of an identifier
bool isIdentifierCont(string input, int i) {
    if (i < 0 || i >= input.size())
        return false;
    return ('0' <= input[i] && input[i] <= '9') || isIdentifierStart(input, i);
}
//Check if a[start + i] == b[i], i<b.size()
bool eqRange(string a, int start, string b) {
    if (a.size() - start < b.size())
        return false;
    return a.substr(start, b.size()) == b;
}
//Escape the sourcecode for HTML
string escape(char c) {
    switch (c) {
    case '&':
        return "&";
    case '\"':
        return """;
    case '\'':
        return "'";
    case '<':
        return "<";
    case '>':
        return ">";
    }
    //Is there a better way to do this?
    stringstream strm;
    strm << c;
    return strm.str();
}
string escape(string str) {
    string ans = "";
    for (size_t i = 0; i < str.size(); i++) {
        ans += escape(str[i]);
    }
    return ans;
}
string highlight(string input) {
    //The current state
    int state = NONE;
    //The current position
    size_t i = 0;
    //Styles
    string output =
            "
";
    output += NEW_LINE[1];
    for (; i < input.size();) {
        switch (state) {
        case NONE: {
            if (input[i] == '#') { //Start a preprocessor statement
                state = PREPROCESSOR_UNCLOSED;
                output += OPEN_PREPROCESSOR + escape(input[i]);
                i++;
                break;
            }
            if (input[i] == '"') { //Start a string
                state = STRING_UNCLOSED;
                output += OPEN_STRING + escape(input[i]);
                i++;
                break;
            }
            if (input[i] == '\'') { //Start a character
                state = CHAR_UNCLOSED;
                output += OPEN_STRING + escape(input[i]);
                i++;
                break;
            }
            if (eqRange(input, i, "//")) { //Start a single line comment
                state = LINE_COMMENT_UNCLOSED;
                output += OPEN_COMMENT + escape(input.substr(i, 2));
                i += 2;
                break;
            }
            if (eqRange(input, i, "/*")) { //Start a multi-line comment
                state = MULTILINE_COMMENT_UNCLOSED;
                output += OPEN_COMMENT + escape(input.substr(i, 2));
                i += 2;
                break;
            }
            if (input[i] == '\n') { //New lines are special!
                output += getNewLineHTML();
                i++;
                break;
            }
            for (size_t j = 0; j < NUMBER_OF_KEYWORDS; j++) //Iterate through keywords
                if (eqRange(input, i, keywords[j])
                        && !isIdentifierCont(input, i + keywords[j].size())) { // The keyword can't be a prefix of an identifier, so test for that
                    output += OPEN_KEYWORD + escape(keywords[j])
                            + CLOSE_KEYWORD;
                    i += keywords[j].size();
                    break;
                }
            //Treat identifiers separately because we need to separate identifiers from keywords.
            if (isIdentifierStart(input, i)) {
                state = IDENTIFIER;
                output += escape(input[i]);
                i++;
                //If the next character is not a part of the identifier, go to the NONE state
                if (i + 1 == input.size() || !isIdentifierCont(input, i + 1)) {
                    state = NONE;
                }
                break;
            }
            //Other characters
            output += escape(input[i]);
            i++;
            break;
        }
        case CHAR_UNCLOSED: {
            if (eqRange(input, i, "\\")) { //Treat escape sequences inside quotes
                output += escape(input.substr(i, 2));
                i += 2;
                break;
            }
            if (input[i] == '\'') { //Close quote
                state = NONE;
                output += escape(input[i]) + CLOSE_STRING;
                i++;
                break;
            }
            output += escape(input[i]); //Other characters go into the literal
            i++;
            break;
        }
        case STRING_UNCLOSED: {
            if (eqRange(input, i, "\\")) { //Treat escape sequences inside quotes
                output += escape(input.substr(i, 2));
                i += 2;
                break;
            }
            if (input[i] == '"') { //Close quote
                state = NONE;
                output += escape(input[i]) + CLOSE_STRING;
                i++;
                break;
            }
            output += escape(input[i]); //Other characters go into the literal
            i++;
            break;
        }
        case LINE_COMMENT_UNCLOSED: {
            if (input[i] == '\n') { //Close comment with new line
                state = NONE;
                output += CLOSE_COMMENT + getNewLineHTML();
                i++;
                break;
            }
            output += escape(input[i]); //Comment body
            i++;
            break;
        }
        case MULTILINE_COMMENT_UNCLOSED: {
            if (eqRange(input, i, "*/")) { //Close multiline comment
                state = NONE;
                output += escape(input.substr(i, 2)) + CLOSE_COMMENT;
                i += 2;
                break;
            }
            if (input[i] == '\n') { //New lines are special!
                output += getNewLineHTML();
                i++;
                break;
            }
            output += escape(input[i]); //Comment body
            i++;
            break;
        }
        case PREPROCESSOR_UNCLOSED: {
            if (input[i] == '\n') { //Close preprocessor statement or go to next line
                int j = i - 1;
                for (; j >= 0 && inRange(input[j], "\n\t "); j--)
                    //Seek las non-whitespace character
                    ;
                if (j < 0 || input[j] != '\\') { //Check if the last non-whitespace character is a backslash
                    state = NONE; //... If it isn't, close the preprocessor statement
                    output += CLOSE_PREPROCESSOR + getNewLineHTML();
                    i++;
                    break;
                }
                output += getNewLineHTML(); //... If it is, we need to extend the preprocessor statement to the next line
                i++;
                break;
            }
            output += escape(input[i]);
            i++;
            break;
        }
        case IDENTIFIER: {
            //If the next character is not a part of the identifier, go to the NONE state
            if (i + 1 == input.size() || !isIdentifierCont(input, i + 1)) {
                state = NONE;
            }
            output += escape(input[i]);
            i++;
            break;
        }
        }
    }
    output += "
";
    return output;
}
int main() {
    ifstream input("input.c");
    ofstream output("output.html");
    std::string cCode((std::istreambuf_iterator<char>(input)),
            std::istreambuf_iterator<char>());
    output << highlight(cCode) << endl;
}

Is it really neccessary to highlight compiler keywords. They aren't standard. But if you really want to, assume anything starting with __ (two underscores) to be a keyword, as specification says that it reserved for implementation purposes.


text:
calculate the combinatorial
Given two integers - n and r, your task is to calculate the combinatorial nCr.
nCr = n! / r! (n-r)!

The caveat is that you have to write code to do this calculation in minimum number of characters.
Input
The first line will be number of testcases T. Then T lines follow, each containing two positive integers - n and r.
output
Print T lines, each line containing the value of nCr.
Constraints
1 <= T <= 100
1 <= r <= n <= 1000

You can assume that the value nCr will fit into a signed 64 bit integer.

Golfscript, 31 characters
n%(;{~.@.@-]{1\,{)*}/}%~/\/}%n*

Explanation:

n/(;{...}%n* splits the input by a newline, discards the first row (number of testcases), maps the rest and finally joins by a newline.

~.@.@- evals the input, rearranges it to r n n r, then subtracts r from n.
]{...}%~ collects everything on the stack into and array, maps it and explodes the array

1\,{)*}/ is the factorial function: push a 1 below the number, then create an array 0...n, then for each element, multiply the accumulator by the value + 1. The map-reduce implementation is one char longer: ,{)}%{*}*

/\/ divides n! first by factorial of the difference, then by r!.

Hm, for input 1\n5 5\n I get undefined method-' for nil:NilClass (NoMethodError)`. Am I misunderstanding the format of the input? :-/

no trailing newline please

Easily fixed by changing the first / to %.

Done, thanks. [tag:facepalm]

source: Stack Exchange

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

sort: votes


text:
Determine which value represents which direction in a path
Important edit: Earlier, there was an incorrect value in Example 1.  It has been fixed.
You are given a two-dimensional array in which each cell contains one of four values.
Examples:
1 2 2 2 2 1        @ . .        X X V
1 3 1 4 1 4        e . @        I C V
2 3 1 3 4 2        H H @        X I V
1 4 4 2 1 3                     V C C
2 2 2 3 2 3                     X X X

The four values represent directional arrows (up, down, left, and right), although you don't know which value represents which direction.
The directional arrows form an unbroken path that includes every cell in the array, although you don't know where the start or end points are.
Write some code that determines which direction each of the four values represents and where the start and end points are.
An acceptable return value for an array that contains the values A, B, C, and D would be something like:
{ up: A, down: C, left: D, right: B, start: [2, 0], end: [4, 2] }

Because you can traverse the path both ways (from start to end and from end to start), there will always be more than one correct solution, and there might be more than two.  Assume that the inputs you receive (as in the above examples) always have at least one correct solution.  In cases where there is more than one correct solution, returning just one of the correct solutions is sufficient.
Shortest code wins.  I'll pick the winner after 7 days or 24 hours without a new submission, whichever comes first.
I'm including solutions to the examples above, but I'd encourage you to only check them once you've written your code:
One:

 { up: 3, down: 1, left: 4, right: 2, start: [0,0], end: [2,5] }

Two:

 { up: '@', down: 'e', left: '.', right: 'H', start: [1,1], end: [0,0] }

Three:

 { up: 'I', down: 'V', left: 'C', right: 'X', start: [0,2], end: [4,2] }

"you can traverse the path both ways" -- if the directions are absolute, not relative, this is not true. Are the directions absolute, or relative? Also, are the start and end known to be outside the array?

@JanDvorak The start and end points are cells within the array.  As for the directions, assume they always indicate movement into an adjacent cell (north, south, east, or west).

In which case it's not possible to traverse a path backwards. I can't see any guarantee there will always be more than one solution.

I assume we can do anything at all if there's no solution?

@JanDvorak I've updated the description to address the questions you've raised.

Could you please include the answers for the three examples?

If we "assume they always indicate movement into an adjacent cell", is your second example still valid?  I may be missing something but it seems like @ could not be any of the four directions without going "out of bounds".

@NickSarabyn  Thanks for that catch.  I neglected to consider the end point.  The final cell in the path may violate the "always point to an adjacent cell" rule.  Obviously, once you've reached the final cell, you will not go any further, so it doesn't matter in which direction it's pointing.  But I should have been more clear about that.

Example 1 has no solution.

The solutions ending points have the coordinates swapped

C#
EDIT: Fixed a division and formatting. And added the helper class.
This is the golfed code, 807 chars
class M{public int c,x,y,u;}
void G(string[] z){
M K;int[]x={0,0,-1,1},y={-1,1,0,0},I={0,0,0,0};
string[]T={"Up","Down","Left","Right"};
int X,Y,R,n=0,H=z.Length,W=z[0].Length;W-=W/2;var D= string.Join(" ", z).Where(c=>c!=' ').Select(c=>new M(){c=c,x=n%W,y=n++/W}).ToList();n=0;var S=D.GroupBy(k=>k.c).ToDictionary(k=>k.Key,k =>n++);
for(;I[0]<4;I[0]++)for(I[1]=0;I[1]<4;I[1]++)for(I[2]=0;I[2]<4;I[2]++)for(I[3]=0;I[3]<4;I[3]++){
if ((1<<I[0]|1<<I[1]|1<<I[2]|1<<I[3])!=15)continue;
foreach (var Q in D){D.ForEach(p=>p.u=-1);R=1;K=Q;j:if((X=K.x+x[n=I[S[K.c]]])>=0&&X<W&&(Y=K.y+y[n])>=0&&Y<H&&(K=D[X+Y*W]).u<0){
K.u=1;if(++R==D.Count){Console.WriteLine("{4} Start({0}:{1}) End({2}:{3})",Q.x,Q.y,K.x,K.y,string.Join(", ",S.Select(k=>string.Format("{1}: '{0}'",(char)k.Key,T[I[k.Value]])).ToArray()));return;}goto j;}}}
}

Results for the three test cases:

Down: '1', Right: '2', Up: '3', Left: '4' Start(0:0) End(5:2)
  Up: '@', Left: '.', Down: 'e', Right: 'H' Start(1:1) End(0:0)
  Right: 'X', Down: 'V', Up: 'I', Left: 'C' Start(0:2) End(2:4)

This is the raw code without "golf", almost 4,000 characters:
class Program
{
    static string[] input1 =  { "1 2 2 2 2 1",
               "1 3 4 4 1 4",
               "2 3 1 3 4 2",
               "1 4 4 2 1 3",
               "2 2 2 3 2 3"};

    static string[] input2 =  { "@ . .",
                                "e . @",
                                "H H @",
               };

    static string[] input3 =  { "0 0 1",
                                "0 0 1",
                                "3 2 2",
               };

    static void Main(string[] args)
    {
        Resolve(input1);
        Resolve(input2);
        Resolve(input3);
        Console.ReadLine();
    }

    class N { public int c; public int x, y, i, u; }

    static void Resolve(string[] input)
    {
        int[] ox = { -1, 1, 0, 0 }, oy = { 0, 0, -1, 1 }, I = { 0, 0, 0, 0 };
        string[] TXT = { "Left", "Right", "Up", "Down" };
        int X, Y, R, n = 0, H = input.Length, W = input[0].Length;
        W -= W / 2;
        N K = null;
        var data = string.Join(" ", input).Where(c => c != ' ').Select(c => new N() { c = c, x = (n % W), y = (n / W), i = n++, u = -1 }).ToList();
        n = 0;
       var S = data.GroupBy(k => k.c).ToDictionary(k => k.Key, k => n++);

        for (; I[0] < 4; I[0]++)
            for (I[1] = 0; I[1] < 4; I[1]++)
                for (I[2] = 0; I[2] < 4; I[2]++)
                    for (I[3] = 0; I[3] < 4; I[3]++)
                    {
                        if (((1 << I[0]) | (1 << I[1]) | (1 << I[2]) | (1 << I[3])) != 15) continue;
                        foreach(var Q in data)
                        {
                            data.ForEach(p => p.u = -1);
                            R = 0;
                            K = Q;
                            while (K != null)
                            {
                                n = I[S[K.c]];
                                X = K.x + ox[n];
                                Y = K.y + oy[n];
                                if (X >= 0 && X < W && Y >= 0 && Y < H)
                                {
                                    n = X + Y * W;
                                    if (data[n].u < 0)
                                    {
                                         data[n].u = K.i;
                                         K = data[n];
                                        R++;
                                        if (R == data.Count - 1)
                                        {
                                            Console.WriteLine();
                                            Console.WriteLine("Start({0}:{1}) End({2}:{3})", Q.x, Q.y, K.x, K.y);
                                            Console.WriteLine(string.Join(", ", S.Select(k => string.Format("'{0}': {1}", (char)k.Key, TXT[I[k.Value]])).ToArray()));
                                            Action<N> Write = null;
                                            Write = (k) =>
                                             {
                                                 if (k.u != -1)
                                                 {
                                                     Write(data[k.u]);
                                                 }
                                                 Console.Write(string.Format("({0}:{1}){2}", k.x, k.y, k == K ? "\n" : " => "));
                                             };

                                            Write(K);
                                            return;
                                        }
                                        continue;
                                    }
                                }
                                K = null;
                            }
                        }
                    }
        Console.WriteLine("Solution not found");
    }
 }
}

These are the results for the three examples:

Solution not found
Start(1:1) End(0:0) '@': Up, '.': Left, 'e': Down, 'H': Right
(1:1) => (0:1) => (0:2) => (1:2) => (2:2) => (2:1) => (2:0) => (1:0) => (0:0)
Start(0:0) End(1:1) '0': Right, '1': Down, '3': Up, '2': Left
(0:0) => (1:0) => (2:0) => (2:1) => (2:2) => (1:2) => (0:2) => (0:1) => (1:1)

You may want to golf your code, as this is a code-golf competition.

I'm doing it :)

Okay, no rush :) It's just that some people see a new user without golfed code and tend to downvote.

It's my first time... but I advise that is not golfed yet... although I think I won't beat matemathica code... :)

Any answer to this question requires skill. +1

Mathematica 278
Spaces added for "clarity"
k@l_ := (s = #~Join~-# &@{{1, 0}, {0, 1}};
         f@r_ := Flatten[MapIndexed[#2 -> #2 + (#1 /. r) &, l, {2}], 1];
         g     = Subgraph[#, t = Tuples@Range@Dimensions@l] & /@
                       Graph /@ f /@ (r = Thread[# -> s] & /@ Permutations[Union @@ l]);
        {t[[#]] & /@ Ordering[Tr /@ IncidenceMatrix@g[[#]]][[{1, -1}]], r[[#]]} & @@@
                                                                 Position[PathGraphQ /@ g, True])

Session & Output:
 l = l1 = {{1, 2, 2, 2, 2, 1}, {1, 3, 1, 4, 1, 4}, {2, 3, 1, 3, 4, 2},
            {1, 4, 4, 2, 1, 3}, {2, 2, 2, 3, 2, 3}}; ;
 k@l1
 {{{{1, 1}, {3, 6}},
    {1 -> {1, 0}, 2 -> {0, 1}, 3 -> {-1, 0},  4 -> {0, -1}}}}

Which is the start Vertex, End Vertex and the transition rules associated with each symbol.
Here is the complementary code to show the oriented graph:
sol = sg[[Position[PathGraphQ /@ sg, True][[1, 1]]]];
Framed@Graph[
  VertexList@sol,
  EdgeList@sol,
  VertexCoordinates -> VertexList@sol /. {x_, y_} :> {y, -x},
  VertexLabels -> MapThread[Rule, {VertexList@sol, Flatten@l}],
  EdgeShapeFunction -> GraphElementData["FilledArcArrow", "ArrowSize" -> 0.03],
  ImagePadding -> 20]

Mathematica (151)
L = {{1, 2, 2, 2, 2, 1}, {1, 3, 1, 4, 1, 4}, {2, 3, 1, 3, 4, 2},
   {1, 4, 4, 2, 1, 3}, {2, 2, 2, 3, 2, 3}};

PathGraphQ@#~If~Print@{TopologicalSort[#]〚{1,-2}〛,r}&@
Graph@Flatten@MapIndexed[#2->#2+(#/.r)&,L,{2}]~Do~{r,
Thread[Union@@L->#]&/@{-1,0,1}~Tuples~{4,2}}

It returns start point, end point, and transition rules. The first index is row, the second is column
{{{1,1},{3,6}},{1->{1,0},2->{0,1},3->{-1,0},4->{0,-1}}}

Note that my code works even with {-1,0,1}~Tuples~{4,2}. For speeding up you can use Permutations@{{1, 0}, {0, 1}, {-1, 0}, {0, -1}} instead.

APL (207)
I couldn't make it shorter than Mathematica, because I couldn't reason in terms of TopologicalSort and such. Smarter people are welcome to squeeze it further.
Golfed:
{u←∪,t←⍵⋄q r←↑(0≠+/¨r)/⊂[2]p,⍪r←{m←,⍵[u⍳t]⋄v r←⊂[1]⊃{{(↑⍴∪⍵),⊂(↑⍵)(↑⌽⍵)}n↑{3::⍬⋄i←↑⌽⍵⋄⍵,i+i⌷m}⍣n,⍵}¨⍳n←↑⍴,t⋄↑(v=n)/r}¨p←⊂[2]{1≥⍴⍵:⊃,↓⍵⋄⊃⍪/⍵,∘∇¨⍵∘~¨⍵}d←¯1 1,¯1 1×c←¯1↑⍴t⋄⊃('←→↑↓',¨u[q⍳d]),{1+(⌊⍵÷c)(c|⍵)}¨r-1}

Ungolfed:
D←{⎕ML ⎕IO←3 1
    pmat←{1≥⍴⍵:⊃,↓⍵⋄⊃⍪/⍵,∘∇¨⍵∘~¨⍵}   ⍝ utility: permutations of the given vector
    u←∪,t←⍵                    ⍝ the 4 unique symbols in t←⍵
    n←↑⍴,t                     ⍝ number of elements in t
    d←¯1 1,¯1 1×c←¯1↑⍴t        ⍝ the four ∆i (+1, -1, +cols, -cols)
    p←⊂[2]pmat d               ⍝ list of permutations of the four ∆i
    r←{                        ⍝ for each permutation ⍵∊p (=interpretation of the 4 symbols)
        m←,⍵[u⍳t]              ⍝ (ravelled) t-shaped matrix of ∆i, using interpretation ⍵
        v r←⊂[1]⊃{             ⍝ for each starting index ⍵∊⍳n
            v←n↑{              ⍝ trail of visited cells after n steps
                3::⍬           ⍝ if index out of bounds return empty list
                i←↑⌽⍵          ⍝ take last visited index
                ⍵,i+i⌷m        ⍝ follow the directions and add it to the list
            }⍣n,⍵
            (↑⍴∪v),⊂(↑v),↑⌽v   ⍝ number of unique cells, plus start/end indices
        }¨⍳n
        ↑(v=n)/r               ⍝ 1st couple of start/end indices to visit all cells (if any)
    }¨p
    q r←↑(0≠+/¨r)/⊂[2]p,⍪r     ⍝ select first perm. and start/end indices to visit all cells
    ⊃('←→↑↓',¨u[q⍳d]),{1+(⌊⍵÷c)(c|⍵)}¨r-1   ⍝ return char mapping and start/end indices
}

Examples:
(Indices start at 1)
     D⊃'122221' '131414' '231342' '144213' '222323'
 ←  4
 →  2
 ↑  3
 ↓  1
 1  1
 3  6
     D⊃'@..' 'e.@' 'HH@'
 ←  .
 →  H
 ↑  @
 ↓  e
 2  2
 1  1
     D⊃'XXV' 'ICV' 'XIV' 'VCC' 'XXX'
 ←  C
 →  X
 ↑  I
 ↓  V
 3  1
 5  3

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


text:
Quine quine bip quine quine
Write a quine that

Writes its source code to disk
Recursively executes the written source code
Produces some variation to the code the third time (so not a true Quine)
Stops recursively calling itself the fifth time

Bonus points for leaving nothing on disk after execution.

Is this [tag:code-golf], or is there some other winning criterion, making it a [tag:code-challenge]? It doesn't make sense to be both.

@KendallFrey I guess I misunderstood what code-challenge was for. Removing the tag. Thanks!

It's not clear what you consider to be a recursive call (or, for that matter, what "itself" is, given that you're creating imperfect copies), or what you expect to leave on the disk after it finishes.

@PeterTaylor, thanks for the feedback. See clarifying edits.

TCL 220
proc a b {
if {"$b"=="bb"} {
rename puts w
rename p puts
set b \;exit
}
puts [set q [open [incr ::i] w]] "proc a b \{[info body a]\};a b"
catch {rename puts p}
proc puts {n m} "p \$n \${m}$b"
close $q
source $::i
};a b

The code generates files 1, 2, 3 and 4. The variation is only present in 2, the others are equivalent to the original.

PHP 643
<?
$c=1;
$o="<?\n\$c=".($c+1).";\n";
$m="quine";
$s=array(
'$o="<?\n\$c=".($c+1).";\n";',
'$m="quine";',
'$s=array(',
');',
'if($c==3)$s[1]="\$m=\"bip\";";',
'for($i=0;$i<3;$i++)$o.=$s[$i]."\n";',
'for($i=0;$i<count($s);$i++)$o.=chr(39).$s[$i].chr(39).",\n";',
'for($i=3;$i<count($s);$i++)$o.=$s[$i]."\n";',
'echo $m."\n";',
'if($c<5){file_put_contents("q$c.php", $o);echo `php q$c.php`;}',
);
if($c==3)$s[1]="\$m=\"bip\";";
for($i=0;$i<3;$i++)$o.=$s[$i]."\n";
for($i=0;$i<count($s);$i++)$o.=chr(39).$s[$i].chr(39).",\n";
for($i=3;$i<count($s);$i++)$o.=$s[$i]."\n";
echo $m."\n";
if($c<5){file_put_contents("q$c.php", $o);echo `php q$c.php`;}

Output:
quine
quine
quine
bip
bip

The variation in the code is produced in the 3rd iteration and is then only noticeable in the echoes of the 4th and 5th iterations.

Interesting interpretation of the rules! I didn't say whether the variation should be propagated or not. I guess technically a proper quine would propagate the change... +1

GTB, 19
X+1→X@X<15$@X=13:1&

Explanation
X starts by default at 10, so we increment X once. Then, if X<15 check if X=13. If X=13, change the code. Then dump it all to memory.

If you are going to write your own language to answer code golf questions, you at least need to explain what it does... ;)

Okay, I have :)

In Squeak 4.x Smalltalk, it's not golfed, but there is a 299 chars version below
Compile this method in Object:
quine
[| value morph |
value := (((self negated raisedTo: self - 1) / 15) exp exp - 1) reciprocal significand rounded reciprocal.
morph := ToolSet inspect: value.
[(Delay forSeconds: value reciprocal * 5) wait.
morph delete] fork.
World displayWorld.
(Delay forSeconds: 1) wait]
    on: Error
    do: [:exc |
        FileDirectory default deleteFileNamed: 'quine'.
        ^self].
(FileStream forceNewFileNamed: 'quine') nextPutAll: thisContext method getSource; close.
^self class newCompiler
    evaluate: ((FileStream oldFileNamed: 'quine') contentsOfEntireFile lines allButFirst reduce: [:a :b | a , b])
    for: self + 1

Then evaluate '1 quine' where you want.
Each evaluation differs, because it is evaluated with incremented receiver.
( evaluate: ... for: self+1 )
The awfull expression computing the value is different for 3 (lead to a Fraction 1/2 instead of Integer 1) and for 5 (lead to ZeroDivide).
The file is deleted when the exception is caught and 5 is returned.
Otherwise, an inspector is opened on the value, the display is refreshed, the process is paused during 1 second before evaluating next quine.
A process for closing opened inspectors after a longer pause is forked.
The source of quine is retrieved via the current context of execution (thisContext method getSource), written, then re-evaluated without the first line (the name of the method). So the second and successive evaluation do not evaluate #quine, but an anonymous (#Doit) method sharing exactly the same contents.
Based on same principles, this less funny example will print 00100 in Transcript then stop when evaluating 1 quine, but it avoids explicit 3 and 5 in source:
quine|v|v:=self highBit-self lowBit.Transcript show:(1bitAnd:v).(2bitAnd:v)=0or:[^FileDirectory default deleteFileNamed:'q'].(FileStream forceNewFileNamed:'q')nextPutAll:thisContext method getSource;close.^Compiler evaluate:((FileStream oldFileNamed:'q')contentsOfEntireFile allButFirst:5)for:self+1


text:
Convert a repeated decimal to a fraction
This question doesn't need to apply to just terminating decimals - repeating decimals can also be converted to fractions via an algorithm.
Your task is to make a program that takes a repeated decimal as input, and output the corresponding numerator and denominator (in lowest terms) that produces that decimal expansion. Fractions greater than 1 should be represented as improper fractions like 9/5. You can assume that input will be positive.
The repeated decimal will be given in this format:
5.3.87

with everything after the second dot repeated, like this:
5.3878787878787...

Your program will output two integers representing the numerator and denominator, separated by a slash (or the equivalent form in your language if you do not output plain text):
889/165

Note that terminating decimals will have nothing after the second dot, and decimals with no non-repeating decimal portion will have nothing between the two dots.
Test cases
These test cases cover all of the required corner cases:
0..3 = 1/3
0.0.3 = 1/30
0.00.3 = 1/300
0.6875. = 11/16
1.8. = 9/5
2.. = 2/1
5..09 = 56/11
0.1.6 = 1/6
2..142857 = 15/7
0.01041.6 = 1/96
0.2.283950617 = 37/162
0.000000.1 = 1/9000000
0..9 = 1/1
0.0.9 = 1/10
0.24.9 = 1/4

If you wish, you can also assume that fractions without integer parts have nothing to the left of the first dot. You can test that with these optional test cases:
.25. = 1/4
.1.6 = 1/6
..09 = 1/11
.. = 0/1

Is it necessary to simplify the fraction? Or is it reasonable to leave it in an unsimplified form (eg: 9/99)?

(in lowest terms) i.e. the fraction must be simplified.

Am I allowed to output 13 instead of 13/1?

@mniip: No, it has to be 13/1.

@JoeZ. Ok, I edited my answer

What range of numbers does this have to handle? Is it OK to assume the parts of the input are less than 2^31 or something like that?

Be sure to handle this input 1.9999... and output 2/1

I think this piece of J code is much more powerful than what is asked since it doesn't require the second dot as a hint; may I post it (((0:`(%@$:)@.(<&100))@%@-+])x:@<.) 5.3878787878787 (35 characters)?

@ברוכאל How does it handle something like 0.01020408163265306122448979590102040816326530... which looks like 1/98 but actually isn't?

@Joe Z. It actually will tell 1/98.

One more question: is the "slash" symbol a requirement? Could a space be OK as long as it follows other conventions (even the "13/1" convention as "13 1")? I ask because the slash is only a symbol for representing the fraction; anyway the Mathematica solution doesn't use the slash since it outputs a graphical representation of the fraction?

@ברוכאל If it tells 1/98 for my input of 0..0102040816326530612244897959, then your solution is invalid, because the correct answer is just 102040816326530612244897959/9999999999999999999999999999.

Also, the slash symbol is only a requirement if your solution outputs plain text. In the case of the Mathematica solution, the fraction line serves the same purpose.

@Joe Z. Thank you for all your answers; I finally made up a 68-characters APL code; separator is a space because the return value is a 'tuple' numerator+denominator; is it OK? All rules have been strictly followed.

I think that should be okay.

@ThomasEding 1.9999. is 19999/10000, to get 2/1 you need 1..9, isn't it?

Dyalog APL (75 73 69 68 characters)
Here is another and fifth attempt (most probably my last one); I spent the day trying to write some piece of code shorter than 80 characters and being fully consistent with the rules. This challenge made my day!
I finally got a line of APL made of 75 characters, working with Dyalog APL (but not on the online interpreter page because using the ⍎ execute function), which is the following one:
(N,D)÷D∨N←(⍎'0',1↓I/⍨2=+\P)+(⍎'0',I/⍨2>+\P)×D←D+0=D←⍎'0',⌽2↓⍕¯1+10⊥P←'.'=I← '1.2.3'

Of course I could make it a little shorter, but the special cases where one, two or three fields are missing. My code can even handle the .. input case.
I know that APL is difficult to read, and since people enjoy understanding how a piece of code actually works, here are some explanation. Basically, I compute the final denominator in the variable D and the final numerator in the variable N.
APL is parsed from right to left.

First, the string is stored in variable I (I←).
Then it is mapped to a vector of booleans indicating where a dot is, and this vector is called P (P←'.'=). For instance '1.2.3' will be mapped to 0 1 0 1 0.
This vector is digits in base 10 (10⊥); now '1.2.3' is 1010.
Then 1 is substracted from this number (either with 1-⍨ or with ¯1+, here I chose the second). Now '1.2.3' is 1009.
Then this number is converted to a string (⍕), two initial digits are removed (2↓), which makes 09 from our initial '1.2.3' example; the string is reversed (⌽).
Here, as a special case, I add an initial 0 character in front of the string; it makes me sad to use the four characters '0', but I did it for avoiding an error when the second and thirds fields are both empty. The string is converted back to a number (⍎) and it is stored in D, which is the denominator except when both last fields are empty, because in such case D is equal to 0.
The D←D+0= piece of code set D to 1 if it is currently null, and now D contains the denominator (before GCD division however).
This denominator is multiplied (×) with the content of the initial string I up to the second dot with (⍎'0',I/⍨2>+\P) which starts from P again (0 1 0 1 0 in my example), adds the successive numbers by cumulating them (which makes 0 1 1 2 2 in my example), check which values are smaller than 2 (making the boolean vector 1 1 1 0 0), and taking corresponding characters in I; another 0 is added in front of the string for preventing another trap (if the two initial fields are empty) and the whole is converted to a number.
The last part of the input string is added to the previous product with (⍎'0',1↓I/⍨2=+\P), which takes P again, adds by cumulating again, check which values are equal to 2 (see previous explanation), takes the characers, removes the first one which is a dot, adds a preventing initial 0 character and converts to a number.
This product followed with a sum is stored in N which is the numerator.
Finally the GCD is computed with D∨N and both numbers are divided by this GCD.

edit: Here is a fix for 73 characters:
(N,D)÷D∨N←(⍎'0',1↓P/I)+(⍎'0',I/⍨~P←2=+\P)×D←D+0=D←⍎'0',⌽2↓⍕¯1+10⊥P←'.'=I←

The idea of this hack is computing first the case where cumulative addition has values equal to 2, storing them for later and inverting this bitwise mask for getting the first case; thus computing the next case needs less characters.
edit: Here is another fix for 69 characters:
(N,D)÷D∨N←(⍎'0',1↓P/I)+(⍎'0',I/⍨~P←2=+\P)×D←⍎'1⌈0',⌽2↓⍕¯1+10⊥P←'.'=I←

The idea of this hack is to embed the most complicated special case as APL code in the string to be evaluated (at string to number conversion stage).
edit: Here is another fix for 68 characters:
(N,D)÷D∨N←(⍎'0',1↓P/I)+(⍎'0',I/⍨~P←2=+\P)×D←⍎'1⌈0',⌽3↓⍕1-10⊥P←'.'=I←

The idea of this hack is to replace adding -1 to the value for substracting 1 to that value by the operation substracting that value to 1 then remove later one character more at the beginning (which will be the minus sign).
edit: Cosmetic change:
(N,D)÷D∨N←(⍎'0',1↓P/I)+(⍎'0',I/⍨~P←2=+\P)×D←1⌈⍎'0',⌽3↓⍕1-10⊥P←'.'=I←

No improvement in size, but more satisfied to get the maximum function out of the code to be evaluated.

I attempted to run this with tryapl.org and it complains INVALID TOKEN. Do you know why?

@Peter Taylor: Yes, it is even said in my message; this is because I use the "execute" operator which would be unsafe for the server of Dyalog and has been disabled online (safe mode). You have to try it on an installed version of Dyalog APL.

Ah, shame. I'm not going to spend 60€ to be able to test an occasional PCG submission. I've found an alternative online APL tester, but there seems to be something Dyalog-specific in your code because it gives rank errors or length errors.

@Peter Taylor; no ;-) Please, use my own website (still experimental and not official) with GNU APL; but I had to add two characters to make it compatible (parenthesis around one I): see this permalink

We've expanded the capabilities of the online "safe mode", but Dyalog APL is also free for personal use now.

Perl 6 (93 101 100 80 68 66 bytes)
$/=split ".",get;say ($0+($1+$2/(9 x$2.comb||1))/10**$1.comb).nude

The size was increased to handle nothing, instead of just failing. Mouq proposed to use $/, so it's now being used, and the code is 20 bytes shorter. Ayiko proposed replacing / with , so the code is even shorter (by 12 bytes). Then Mouq proposed replacing chars with comb (in numeric context, they are identical, because list of characters after conversion to number is number of characters).
Sample output:
$ perl6 script.p6
5.3.87
889 165
$ perl6 script.p6
2.0.0
2 1
$ perl6 script.p6
0..3
1 3
$ perl6 script.p6
0.0.3
1 30
$ perl6 script.p6
0.0.0
0 1
$ perl6 script.p6
0.1.6
1 6
$ perl6 script.p6
0.01041.6
1 96
$ perl6 script.p6
0.2.283950617
37 162
$ perl6 script.p6
123.456.789
41111111 333000

Unfortunately, it turns out that using zero as a placeholder between two dots is a no-go. 0..09 returns 1/11, but 0.0.09 returns 1/110.

@JoeZ. Oh, ok. I updated my code to handle the case when nothing is typed.

I don't know Perl 6, but am I correct in guessing that given 'a.b.c', your program uses exact rational arithmetic to compute c/99...9, but only uses floating point to compute a.b? In that case if b has many digits it will give an incorrect answer.

@OmarAntolín-Camarena: Not quite. In Perl 6, rationals are default, not floating point numbers. For example, 0.1 + 0.2 == 0.3 in Perl 6.

Oh, cool, I wish more languages made rationals the default, @xfix.

Golfed to 80 chars: $/=split ".",get;say join "/",($0+($1+$2/(9 x chars $2 or 1))/10**$1.chars).nude :)

@Mouq: Thanks, updated. Nice idea about using $/ array, which is magical for Perl 6.

@xfix: given the current accepted answer is allowed to replace the / with a space, this can be shortened to $/=split ".",get;say ($0+($1+$2/(9 x$2.chars||1))/10**$1.chars).nude, also 68 chars.

Technically this is written in Rakudo Perl 6 as the Std parser dies with Unsupported use of $/ variable as input record separator; in Perl 6 please use the filehandle's :irs attribute

@BradGilbertb2gills: Could be fixed with := operator, but I prefer to work with how actual implementation of language works, rather than how it should work according to the specification.

Can't you eliminate the space character after the split and after the say in Perl 6? I know you can in Perl 5.

@ToddLehman: You cannot, this is Perl 6, requiring a space after function call (or opening paren).

J (85 90 89 chars)
My original function, which was 5 characters shorter than the second, had a couple of bugs: it didn't output integers as "n/1" and it gave the wrong answer on numbers with more than a dozen or so digits. Here's a corrected function in J that also incorporates Eelvex's suggestion to save a character:
f=:3 :0
'a t'=.|:(".@('0','x',~]),10x^#);._1'.',y
(,'/'&,)&":/(,%+.)&1+/a%*/\1,0 1-~}.t
)

It receives a string and returns a string. Here's a sample session:
   f '..'
0/1
   f '0.0.0'
0/1
   f '3..'
3/1
   f '..052631578947368421'
1/19
   f '0.2.283950617'
37/162
   f '.0.103092783505154639175257731958762886597938144329896907216494845360824742268041237113402061855670'
1/97

You should fix your function to output 0/1 and 3/1 inf first two test cases, See this comment

I fixed the output for integers at the cost of 5 chars, @mniip.

Use ('0','x',~]) and save a byte.

C, 171
Quite long. Could be further reduced. No scanf, which really can't handle it if there aren't any numbers between the dots. No strtol. Just number crunching:
a,b,c,d,q;main(){while((q=getchar()-48)>-3)q<0?(d=b>0,b+=!b):d?(c=c*10+q,d*=10):(a=a*10+q,b*=10);for(a=a*--d+c,q=b*=d;q>1;a%q+b%q?--q:(a/=q,b/=q));printf("%d/%d\n",a,b);}

Test:
rfc <<< "2..142857"
15/7

DC (not fully general, shortened to 76 characters)
Not fully general, but please, consider I did it with one of the oldest things in the world:
5.3.87 dsaX10r^d1-rla*sasbdscX10r^dlc*rlb*rlb*la+snsdlnld[dSarLa%d0<a]dsax+dldr/rlnr/f

Edit: I edit my solution; it isn't more general, but a little shorter:
sadsbX10r^sclaX10r^dd1-dsdlblc**rla*+dsnrld*dsd[dSarLa%d0<a]dsax+dldr/rlnr/f

Use it as:
5.3.87 sadsbX10r^sclaX10r^dd1-dsdlblc**rla*+dsnrld*dsd[dSarLa%d0<a]dsax+dldr/rlnr/f

First field isn't required:
.1.3 sadsbX10r^sclaX10r^dd1-dsdlblc**rla*+dsnrld*dsd[dSarLa%d0<a]dsax+dldr/rlnr/f

is OK.
Second and thirst field require at least one digit

Javascript, 203
Way too long, but still fun. Newlines because semicolons are unreadable.
s=prompt(b=1).split(".")
P=Math.pow
a=s[0]
c=s[1]
d=P(10,l=c.length)
f=(P(10,s[2].length)-1)*P(10,l)||1
e=s[2]=+s[2]
a=d*a+b*c;b*=d
a=f*a+b*e;b*=f
function g(a,b){return b?g(b,a%b):a}g=g(a,b);a/g+"/"+b/g

I'm getting 889/NaN when I run 5.3.87 ... Am I doing something wrong?

I don't know... If I just paste this code in the Safari console (Firefox or Chrome should do too), hit enter and type "5.3.87", I just get "889/165" in the console. How are you running it? @rafaelcastrocouto

nevermind ... I guess I did something wrong since it is working now ...

You can save 1 character by moving the b=1 part inside prompt().

@user2428118 applied, together with another improvement.

f=(P(10,s[2].length)-1)*P(10,l),f=f?f:1 => f=(P(10,s[2].length)-1)*P(10,l)||1

J (different method)
Another solution based on a very different method; this time it is fully general; only missing is the 1-denominator when an integer is submitted:
   ".((({.~(i.&1)),'+'"_,((":@(10&^)@#,'%~',])@}.@#~~:/\),'+%',((,~(##'9'"_),'%x:0'"_)@}.@#~2:=+/\@]))(=&'.')) '.1.3'
2r15
   ".((({.~(i.&1)),'+'"_,((":@(10&^)@#,'%~',])@}.@#~~:/\),'+%',((,~(##'9'"_),'%x:0'"_)@}.@#~2:=+/\@]))(=&'.')) '.1.'
1r10
   ".((({.~(i.&1)),'+'"_,((":@(10&^)@#,'%~',])@}.@#~~:/\),'+%',((,~(##'9'"_),'%x:0'"_)@}.@#~2:=+/\@]))(=&'.')) '1..'
1
   ".((({.~(i.&1)),'+'"_,((":@(10&^)@#,'%~',])@}.@#~~:/\),'+%',((,~(##'9'"_),'%x:0'"_)@}.@#~2:=+/\@]))(=&'.')) '1..3'
4r3

GolfScript (67 chars)
`{'.'/1$=.10\,?@-).!+0@+~}+3,/1$4$*]-1%~;*+*+].~{.@\%.}do;{/}+/'/'@

NB This supports empty integer parts.
If the string is of the form 'n.p.q' then the value is n + p/E + q/(DE) = ((nD + p)E + q)/DE where D = 10^(len p) and E = 10^(len q) - 1, except when len q = 0, in which case E = 1 (to avoid division by 0).
Dissection:
           # Stack: 'n.p.q'
`{         # Combined with the }+ below this pulls the value into the block
           # Stack: idx 'n.p.q'
    '.'/   # Stack: idx ['n' 'p' 'q']
    1$=    # Stack: idx str   (where str is the indexed element of ['n' 'p' 'q'])
    .10\,? # Stack: idx str 10^(len str)
    @-)    # Stack: str 10^(len str)-idx+1
           #   If idx = 0 we don't care about the top value on the stack
           #   If idx = 1 we compute D = 10^(len 'p')
           #   If idx = 2 we compute E' = 10^(len 'q') - 1
    .!+    # Handle the special case E'=0; note that D is never 0
    0@+~   # Stack: 10^(len str)-idx+1 eval('0'+str) (GolfScript doesn't treat 011 as octal)
}+         # See above
3,/        # Run the block for idx = 0, 1, 2
           # Stack: _ n D p E q
1$4$*      # Stack: _ n D p E q D*E
]-1%~;     # Stack: D*E q E p D n
*+*+       # Stack: D*E q+E*(p+D*n)
].~        # Stack: [denom' num'] denom' num'
{.@\%.}do; # Stack: [denom' num'] gcd
{/}+/      # Stack: denom num
'/'@       # Stack: num '/' denom

Online demo which simulates running the program with each of the test inputs, one at a time.

I tried it, and it doesn't seem to follow all the rules: "Note that terminating decimals will have nothing after the second dot, and decimals with no non-repeating decimal portion will have nothing between the two dots." I couldn't make your code work with input being 0.1.

-1. I retried it another time after having noticed you got the +300 points. It isn't fair, because other solutions have done their best to follow all the rules, which you obviously haven't done.

@ברוכאל, I object to your assertion that I haven't tried to follow the rules. The position of the optional test cases confused me into thinking that the final block covered all of the required cases; it turns out that I was wrong, and I'm going to edit the question shortly to avoid other people making the same mistake. I have now updated my code to handle the previously unhandled corner cases, and updated my link to a test to demonstrate that.

that's OK. You probably deserve the 300 points. Being new to CodeGolf, these 300 points were a challenging target for me, and I am still disappointed not to have got them while I am still thinking that at the deadline time my code was the shortest to perfectly fit the rules. Anyway, I have all my life for winning points. Regards.

@ברוכאל: I wanted to start 500 points (yes, I'm generous like that, it's not that I can give less) bounty, and give you those points, but I guess there is already a bounty started. Well, whatever. I'm wondering when this bounty will end, and who will get those points.

Thank you for all these discussions and clarifications; I am not sure I can do better for this problem anyway; now looking for next problems to come. I removed my downvote because the code seems to work fully now. Regards.

Two python answers using no libraries. First handles the optional input without a digit before the first . and is 162 chars
_=lambda a,b:b and _(b,a%b)or a;i,t,r=raw_input().split(".");b=r!="";d=(10**len(r)-b)*10**len(t);n=int((i+t+r)or 0)-b*int((i+t)or 0);f=_(d,n);print "%i/%i"%(n,d)

Second doesn't handle nothing before the first digit but does handle all required inputs correctly and is 150 chars
_=lambda a,b:b and _(b,a%b)or a;i,t,r=raw_input().split(".");b=r!="";d=(10**len(r)-b)*10**len(t);n=int(i+t+r)-b*int(i+t);f=_(d,n);print "%i/%i"%(n,d)

JavaScript (ECMASCript 6) 180 175
G=(a,d)=>d?G(d,a%d):a;P=a=>+("1e"+a);L=a=>a.length;f=prompt().split(".");B=P(L(b=f[1]));D=P(L(b)+L(c=f[2]))-P(L(b))||1;alert((m=(f[0]+b||0)*D+B*(c||0))/(g=G(m,n=B*D))+"/"+n/g)

While it isn't a clear winner for the 300 bounty... this is the shortest I can come up with:

Changes from previous version: some slight alteration to logic, and changes to the Power P function by altering it to +("1e"+a) instead of Math.pow(10,a) thereby saving a few more characters...

Ruby - 112
x,y,z=gets.chop.split".";y||='0';z||='0';puts((y.to_i+Rational(z.to_i,10**z.length-1))/10**y.length+x.to_i).to_s

This is my first experiment with ruby, so feel free to suggest improvements.
$ ruby20 % <<< '5.3.87'
889/165
$ ruby20 % <<< '0..3'
1/3
$ ruby20 % <<< '0.0.3'
1/30
$ ruby20 % <<< '0.00.3'
1/300
$ ruby20 % <<< '0.6875.0'
11/16
$ ruby20 % <<< '1.8.0'
9/5
$ ruby20 % <<< '2..'
2/1
$ ruby20 % <<< '..'
0/1

Removing support "..' and ".1.2" means you're not following the spec, right? (I would prefer removing them too.)

@OmarAntolín-Camarena On that particular point, the spec says, If you wish. I do not wish, so I'm not supporting fractions without 1st or 3rd group of digits. I am however supporting fractions lacking 2nd group of digits, which matches the spec.

@minip, you misread the spec: it doesn't say "if you wish you can support .. and .1.2", it says, "if you wish, you can assume that 0.. and 0.1.2 are always given as .. and .1.2".

@OmarAntolín-Camarena Point taken. Edited.

Python
No libraries - 156 characters
_=lambda a,b:b and _(b,a%b)or a;a,b,c=raw_input().split('.');d,e=int(a+b+c)-bool(c)*int(a+b),
(10**len(c)-bool(c))*10**len(b);f=_(d,e);print'%i/%i'%(d/f,e/f)

Using fractions - 127 characters
from fractions import*;a,b,c=raw_input().split('.');print Fraction(int(a+b+c)-bool(c)*int(a+b
),(10**len(c)-bool(c))*10**len(b))

The fractions version prints things like "Fraction(7, 5)" instead of "7/5", doesn't it?

It doesn't; I'm not getting the top one working, by the way. _=lambda a,b:b and _(b,a%b)or a;a,b,c=raw_input().split('.');d,e=int(a+b+c)-bool(c)*int(a+b), ValueError: need more than 1 value to unpack

@OmarAntolín-Camarena AFAIK, print uses str when available, not repr. This is the output on my end: http://puu.sh/7w64w.png

@tomsmeding Both are on one line; the line break was added to make them fit in the answer. _=lambda a,b:b and _(b,a%b)or a;a,b,c=raw_input().split('.');d,e=int(a+b+c)-bool(c)*int(a+b),(10**len(c)-bool(c))*10**len(b);f=_(d,e);print'%i/%i'%(d/f,e/f) should go all in one line.

Oh right, @Oberon, as you can probably guess I wasn't at my computer and couldn't run the code.

I count 158 chars, it could be shortened further by replacing raw_input() by input() and defining t=bool(c) giving 152 chars _=lambda a,b:b and _(b,a%b)or a;a,b,c=input().split('.');t=bool(c);d,e=int(a+b+c)-t*int(a+b),(10**len(c)-t)*10**len(b);f=_(d,e);print'%i/%i'%(d/f,e/f)**

neglect the last ** in the previous comment

Mathematica, 143
As usual, Mathematica offers many high-level functions to do the job, but gives them verbose names.
x=StringTake;c=ToExpression;p=s~StringPosition~".";{o,t}=First/@p;u=StringLength@s-t;d=t-o-1;Rationalize@(c@x[s,t-1]+c@x[s,-u]/((10^u)-1)/10^d)

Sample output to be added later when I have time.

It looks to me as if this outputs integers as n, rather than n/1. Is that right? (My solution has the same bug... :()

Ah, now I see....specified in the comments. What an odd requirement...if every other fraction is reduced, why not allow n/1 to reduce to n? I'll add the extra ~50 bytes to convert integers later.

Your approach is fine. Mine makes use of FromDigits so I decided to post it too.

Haskell
import Data.Ratio
f n=case s '.' n of
    [x,y,z]->(r x)%1+(r y)%(10^(length y))+(r z)%((10^t-1)*(10^(length y)))
        where
            r ""=0
            r n=read n
            t = if length z==0 then 9 else length z
s _ []=[[]]
s n (x:xs) | x==n = []:(s n xs)
           | otherwise = let (l:ls)=s n xs in (x:l):ls

Hey, this is code-golf, you aren't even trying!

@mniip I am not good at code golf. Atleast I used single character variable names.

You never specified the language or the total amount of characters/bytes used.

Use {;} to save space on indents, span to implement s, add short aliases for functions, remove space where possible. import Data.Ratio v=span(/='.');w=tail;l=length;f n=(r x)%1+(r y)%p+(r z)%((10^t-1)*p)where{(x,b)=v n;(y,d)=v(w b);z=w d;p=10^(l y);r""=0;r n=read n;t=if null z then 9 else l z} - 178 chars, down from 321. NB True is a synonym for otherwise, null z is length z==0

C, 164
This is similar to orion's C solution, even though I did it from scratch.
I confess however stealing a number of his optimizations.
It is not much shorter, but it handles .25. = 1/4 and 0.000000.1 = 1/9000000.
long a,b,c,d,e;main(){while((c=getchar()-48)>-3)c+2?a=a*10+c,b*=10:b?e=a,d=b:(b=1);
b>d?a-=e,b-=d:0;for(d=2;d<=a;)a%d+b%d?d++:(a/=d,b/=d);printf("%ld/%ld\n",a,b);}

JavaScript (189)
i=prompt().split(".");a=i[0];b=i[1];c=i[2];B=b.length;p=Math.pow;n=a+b+c-(a+b);d=p(10,B+c.length)-p(10,B);f=1;while(f){f=0;for(i=2;i<=n;i++)if(n%i==0&&d%i==0){n/=i;d/=i;f=1}};alert(n+"/"+d)

Example:
Input:
5.3.87

Output:
889/165

Mathematica 175
f@i_:=
If[IntegerQ[g=FromDigits[Map[IntegerDigits@ToExpression@#&,StringSplit[i,"."]/.""-> {}]
/.{a_,b_,c_}:> {{Sequence@@Join[a,b],c},Length@a}]],HoldForm[Evaluate@g]/HoldForm@1,g]

Most of the routine goes to massaging the input.  Approximately 50 chars went to handling integers.

Examples
f["7801.098.765"]

More examples:
TableForm[
 Partition[{#, f[#]} & /@ {"19..87", "19.3.87", "5.3.87", "0.0.3", "0..3", "0.2.283950617",
"123.456.789", "6666.7777.8888", "2.0.0","0.0.0"}, 5], TableSpacing -> {5, 5}]

How it would normally be accomplished in Mathematica
FromDigits can obtain a fraction directly from a recurring repeating decimal, provided that the input is of a particular form.  Integers are displayed as  integers.
z={{{1, 9, {8, 7}}, 2}, {{1, 9, 3, {8, 7}}, 2}, {{5, 3, {8, 7}}, 1}, {{{3}}, -1}, {{{3}}, 0},
{{2, {2, 8, 3, 9, 5, 0, 6, 1, 7}}, 0}, {{1, 2, 3, 4, 5, 6, {7, 8, 9}}, 3},
{{6, 6, 6, 6, 7, 7, 7, 7, {8}}, 4}, {{2}, 1}, {{0}, 1}}

FromDigits/@z

Your output is in the wrong format, it is way too pretty.

Strangely, this is the default format for expressing fractions in Mathematica. It would take several more characters to change this format to the simpler one.

J (96 characters)
I don't use the slash symbol as a separator (but solution in Mathematica doesn't either since it uses a graphical representation which is better anyway); in J language the fraction is displayed with r instead as /:
   (((-.@]#[)((".@[%#@[(10x&^)@-{.@])+({.@](10x&^)@-#@[)*<:@{:@](".%<:@(10x&^)@#)@}.[)I.@])(=&'.')) '1..3'
4r3
   (((-.@]#[)((".@[%#@[(10x&^)@-{.@])+({.@](10x&^)@-#@[)*<:@{:@](".%<:@(10x&^)@#)@}.[)I.@])(=&'.')) '123.456.789'
41111111r333000

APL (not fully general)
Not fully general (like my solution for dc); works with Dyalog APL (but not on the online version of Dyalog APL, not sure why):
(R,F)÷(F←D×N)∨R←(⍎C)+D×(⍎I/⍨2>+\P)×N←10*¯1++/≠\P⊣D←¯1+10*⍴C←1↓I/⍨2=+\P←'.'=I← '123.456.789'

The first field is optional, but at least one digit is required for both other fields.

C (420 characters as written; less after removing unnecessary whitespace)
Note that this assumes 64-bit long (e.g. 64 bit Linux); it will fail for the test case 0.2.283950617 on systems using 32-bit long. This can be fixed at the cost of some characters by changing the type to long long and changing the printf format string accordingly.
#include <stdio.h>

long d[3], n[3], i;

int main(int c, char** v)
{
  while (c = *v[1]++)
    switch(c)
    {
    case '.':
      n[++i] = 1;
      break;
    default:
      d[i] = 10 * d[i] + c - '0';
      n[i] *= 10;
    }

  n[2] -= n[2] != 1;

  while (i--)
    d[2] += d[i] * n[i+1], n[i]*=n[i+1];

  i = d[2];
  *n = n[1];

  while (i)
    *d = i, i = *n%i, *n = *d;
  printf("%ld/%ld\n", d[2]/ *n, n[1]/ *n);
}

Nice. You can shave off 1 character by changing '0' to 48.

I think you could also save a few more by rewriting the switch statement as if(c==46) n[++i]=1; else d[i]=10*d[i]+c-48,n[i]*=10;.

GTB, 81
`_:s;_,1,l?_)-S;_,"."
s;A;,1,S;_,".")-1
s;_,1+S;_,"."),l?_)-S;_,"."))→_
x?A;+_)►Frac

Example
?3.25.
            13/4

Until a compiler is made freely available for this language, I will downvote every answer which uses it.

There seems to be a compiler on the page linked above?

@skibrianski See this post on meta

@Gareth, there are a couple of Mathematica answers for you to downvote, too. :P

@OmarAntolín-Camarena There is a compiler/interpreter for Mathematica. GTB has none. Follow the GTB link above if you don't believe me. You'll get some compressed stuff for a proprietary program, then you'll search for that program and find that the site that claims to provide a download says it's not available. So how do we compile it?

Oh, I'm sorry, I didn't know the GTB situation, I thought you meant there was a compiler or interpreter for it but that it was not freely available. @Gareth

Essentially, it's just a search-replace compiler. I'd have that fixed in under 5 minutes. -- in a normal language.


text:
Packing binary data to source-safe ascii efficiently
Description
Here's a challenge with a somewhat practical use, at least for us golfers.
Your mission, should you choose to accept it, is to write a program that can take arbitrary binary data (either from stdin, or a file) and output some valid source code which provides access to the data. The generator and target languages need not be the same.
Scoring
Your program will be run against two inputs: a 1 KiB file of random characters, and the lyrics of Never Gonna Give You Up by Rick Astley.  The program with the lowest score wins. Your score is calculated as follows:

(A + B) × loge(Z)

Where:

A is the number of bytes in the output for the random data;
B is the number of bytes in the output for Never Gonna Give You Up; and
Z is the number of useful bytes in the target programming language (useful is a very broad definition and may be refined in the future)

For example:

in C++ the generally allowed characters are "\t \r\nABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!\"#%&'()*+,-./:;<=?[\\]^_{|}~" which would give Z = 94
in Brainfuck the only non-ignored characters are "<>+-.,[]" which gives Z = 8

Examples
Two examples in Python, both generating python source:
Python allows files encoded in UTF-16, so the valid python bytes are from 0x00-0xFF
Using Repr
import sys
print 'data=',repr(sys.stdin.read())

Score: (2898 + 2098) × loge(256) = 27,704
Using Base64
import sys
from base64 import b64encode
print 'from base64 import b64decode;data=b64decode("'+b64encode(sys.stdin.read())+'")'

Score: (1416 + 2640) × loge(256) = 22,491
Data
The data is given here encoded in base64, these files should be decoded prior to passing to your program.  The decoding is outside of the scope of this challenge.
Random
2moE8CGQCSSr8V4uHaeKMvtJUtStqVwvgn3xGgCWIlRWaEjVTLmF/fn0heXYh7GIPAUSZmEa2pR5
KTuLfLVtPMi8eUg5903zd/b57BIVJEPGVOyBhzxGTlzYEVG3uaUwnSOlpw9zP5SK/vjDNDCdF4IJ
ZBg8cHloaoxqw1Bm306GV6v6/Gzx+MHcCOsUyT0MyqOAgbuA4t568QTT82zd/nbZQ2BE9Q6bmIwo
tfBCTPwV0TShetCufxZJBbnVrNlDW8BDnKMGzqws/dJT+C03ndd64sszj/Quvri74Earfg6/07ea
Gh5KY8onMhpRiB/k/M6aHpA/glmaFNE5Gu0TsKVgNCHUCP1Dqb9MKR3FU21Dg6fNttR4m+ZJNtbU
yMy6nWTuBx/N7hcUXIdn5FF6X5r+EdUtJxV1pegaDPsKO1Weag1TT5FqeIFEKyw2L9NX7QAsXuva
8Y/6/+iEH/ldIEe/ZHzPc5kqPtuip6l/y2+zleXLw7W4jQ1vLL0xbI4J0lQhpLniCc1K+5699TN8
+k01C16JdSQfEAx+dVlRq6m9Vf0uWonUWgrYsmvtY4hmC1AqKDIr9p6rB6zRL3d/8ctHeKwLZlmh
HCQYqyZURixVJnOkamIk8JP6xk82lC3PyCfP9fwHitguwK4Lnz6x22snqHvk8fW9iZbydWjjFW1+
SX2KE5M4pr7SKs+WzbGWks9FZNoHlGF4Ju1rT8zlYWUwX/3qZ2hHKuc+tXwedb75vj8NDeTiBAgD
/3L3ckt8Xw0JyFKCXv3nCJx3rC7oA1x1U7ZewlQTgCipPkUrRFehKYCjM42h8XCj1yVrbuL5fTvu
ZL5R/xOALz8XK0yxPqN5WgUtD4UFcxsmvAZ6OrbFysciud5hNHkZlr9Tr2oUtFvtx8o6eWH/eHO3
OJFyKiKdqDE/RzwnaPeND9DaZ3A2Jn/5RL+IHfWRlA5Q9i5plOg6v3ZMuGhPJX7tfqjtVW7z5OnR
pTZ2vpDMVwWUdygDbmjXg6xIFuVZzXR+hdoF3dGb0iBOkOlsvASNnmLs+ZSgJFYe03ydjFe8CVG8
Dogi7Ca9FtaGvOem8MqsjVS2sHDdLaQ6AHX0y3HEvhK+O3udAoTztIb/VILyaA9NVnxwiK5MCdfB
l0CHlRxmV2oDYaxxa58U2llEqn9adcTdp/eH/QVhfu32+c1x4pMMDPZxG9HBtOe5oIFEPUYth6zz
ttD/mfa0VRPM+Za1OWpa+SpFsV8spYc38c9d5t8x2ihNf2B0vN/t8Y3R0ge8iq6n/Tt2EGBRop7x
Vv013OMy5UUA7qiGexIv4xS2OUW8gSUbwxt2a+8Q5WQBw1LU7GLT6mDsZvQ+vsHqi34POcI+cQ==

Never Gonna Give You Up
V2UncmUgbm8gc3RyYW5nZXJzIHRvIGxvdmUNCllvdSBrbm93IHRoZSBydWxlcyBhbmQgc28gZG8g
SQ0KQSBmdWxsIGNvbW1pdG1lbnQncyB3aGF0IEknbSB0aGlua2luZyBvZg0KWW91IHdvdWxkbid0
IGdldCB0aGlzIGZyb20gYW55IG90aGVyIGd1eQ0KSSBqdXN0IHdhbm5hIHRlbGwgeW91IGhvdyBJ
J20gZmVlbGluZw0KR290dGEgbWFrZSB5b3UgdW5kZXJzdGFuZA0KDQpOZXZlciBnb25uYSBnaXZl
IHlvdSB1cA0KTmV2ZXIgZ29ubmEgbGV0IHlvdSBkb3duDQpOZXZlciBnb25uYSBydW4gYXJvdW5k
IGFuZCBkZXNlcnQgeW91DQpOZXZlciBnb25uYSBtYWtlIHlvdSBjcnkNCk5ldmVyIGdvbm5hIHNh
eSBnb29kYnllDQpOZXZlciBnb25uYSB0ZWxsIGEgbGllIGFuZCBodXJ0IHlvdQ0KDQpXZSd2ZSBr
bm93biBlYWNoIG90aGVyIGZvciBzbyBsb25nDQpZb3VyIGhlYXJ0J3MgYmVlbiBhY2hpbmcgYnV0
DQpZb3UncmUgdG9vIHNoeSB0byBzYXkgaXQNCkluc2lkZSB3ZSBib3RoIGtub3cgd2hhdCdzIGJl
ZW4gZ29pbmcgb24NCldlIGtub3cgdGhlIGdhbWUgYW5kIHdlJ3JlIGdvbm5hIHBsYXkgaXQNCkFu
ZCBpZiB5b3UgYXNrIG1lIGhvdyBJJ20gZmVlbGluZw0KRG9uJ3QgdGVsbCBtZSB5b3UncmUgdG9v
IGJsaW5kIHRvIHNlZQ0KDQpOZXZlciBnb25uYSBnaXZlIHlvdSB1cA0KTmV2ZXIgZ29ubmEgbGV0
IHlvdSBkb3duDQpOZXZlciBnb25uYSBydW4gYXJvdW5kIGFuZCBkZXNlcnQgeW91DQpOZXZlciBn
b25uYSBtYWtlIHlvdSBjcnkNCk5ldmVyIGdvbm5hIHNheSBnb29kYnllDQpOZXZlciBnb25uYSB0
ZWxsIGEgbGllIGFuZCBodXJ0IHlvdQ0KDQpOZXZlciBnb25uYSBnaXZlIHlvdSB1cA0KTmV2ZXIg
Z29ubmEgbGV0IHlvdSBkb3duDQpOZXZlciBnb25uYSBydW4gYXJvdW5kIGFuZCBkZXNlcnQgeW91
DQpOZXZlciBnb25uYSBtYWtlIHlvdSBjcnkNCk5ldmVyIGdvbm5hIHNheSBnb29kYnllDQpOZXZl
ciBnb25uYSB0ZWxsIGEgbGllIGFuZCBodXJ0IHlvdQ0KDQooT29oLCBnaXZlIHlvdSB1cCkNCihP
b2gsIGdpdmUgeW91IHVwKQ0KKE9vaCkNCk5ldmVyIGdvbm5hIGdpdmUsIG5ldmVyIGdvbm5hIGdp
dmUNCihHaXZlIHlvdSB1cCkNCihPb2gpDQpOZXZlciBnb25uYSBnaXZlLCBuZXZlciBnb25uYSBn
aXZlDQooR2l2ZSB5b3UgdXApDQoNCldlJ3ZlIGtub3cgZWFjaCBvdGhlciBmb3Igc28gbG9uZw0K
WW91ciBoZWFydCdzIGJlZW4gYWNoaW5nIGJ1dA0KWW91J3JlIHRvbyBzaHkgdG8gc2F5IGl0DQpJ
bnNpZGUgd2UgYm90aCBrbm93IHdoYXQncyBiZWVuIGdvaW5nIG9uDQpXZSBrbm93IHRoZSBnYW1l
IGFuZCB3ZSdyZSBnb25uYSBwbGF5IGl0DQoNCkkganVzdCB3YW5uYSB0ZWxsIHlvdSBob3cgSSdt
IGZlZWxpbmcNCkdvdHRhIG1ha2UgeW91IHVuZGVyc3RhbmQNCg0KTmV2ZXIgZ29ubmEgZ2l2ZSB5
b3UgdXANCk5ldmVyIGdvbm5hIGxldCB5b3UgZG93bg0KTmV2ZXIgZ29ubmEgcnVuIGFyb3VuZCBh
bmQgZGVzZXJ0IHlvdQ0KTmV2ZXIgZ29ubmEgbWFrZSB5b3UgY3J5DQpOZXZlciBnb25uYSBzYXkg
Z29vZGJ5ZQ0KTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVydCB5b3UNCg0KTmV2ZXIgZ29u
bmEgZ2l2ZSB5b3UgdXANCk5ldmVyIGdvbm5hIGxldCB5b3UgZG93bg0KTmV2ZXIgZ29ubmEgcnVu
IGFyb3VuZCBhbmQgZGVzZXJ0IHlvdQ0KTmV2ZXIgZ29ubmEgbWFrZSB5b3UgY3J5DQpOZXZlciBn
b25uYSBzYXkgZ29vZGJ5ZQ0KTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVydCB5b3UNCg0K
TmV2ZXIgZ29ubmEgZ2l2ZSB5b3UgdXANCk5ldmVyIGdvbm5hIGxldCB5b3UgZG93bg0KTmV2ZXIg
Z29ubmEgcnVuIGFyb3VuZCBhbmQgZGVzZXJ0IHlvdQ0KTmV2ZXIgZ29ubmEgbWFrZSB5b3UgY3J5
DQpOZXZlciBnb25uYSBzYXkgZ29vZGJ5ZQ0KTmV2ZXIgZ29ubmEgdGVsbCBhIGxpZSBhbmQgaHVy
dCB5b3U=

@PeterTaylor Excellent point, I'll update it.

Voting to close because "useful" is very vague, especially for something so important to answers' scores.

PHP 8986
<?php
$data = file_get_contents('php://stdin');
printf('$var=gzuncompress(base64_decode("%s"));', base64_encode(gzcompress($data)));

Binary 1417
$var=gzuncompress(base64_decode("eJwBAAT/+9pqBPAhkAkkq/FeLh2nijL7SVLUralcL4J98RoAliJUVmhI1Uy5hf359IXl2IexiDwFEmZhGtqUeSk7i3y1bTzIvHlIOfdN83f2+ewSFSRDxlTsgYc8Rk5c2BFRt7mlMJ0jpacPcz+Uiv74wzQwnReCCWQYPHB5aGqMasNQZt9Ohler+vxs8fjB3AjrFMk9DMqjgIG7gOLeevEE0/Ns3f522UNgRPUOm5iMKLXwQkz8FdE0oXrQrn8WSQW51azZQ1vAQ5yjBs6sLP3SU/gtN53XeuLLM4/0Lr64u+BGq34Ov9O3mhoeSmPKJzIaUYgf5PzOmh6QP4JZmhTRORrtE7ClYDQh1Aj9Q6m/TCkdxVNtQ4OnzbbUeJvmSTbW1MjMup1k7gcfze4XFFyHZ+RRel+a/hHVLScVdaXoGgz7CjtVnmoNU0+RaniBRCssNi/TV+0ALF7r2vGP+v/ohB/5XSBHv2R8z3OZKj7boqepf8tvs5Xly8O1uI0Nbyy9MWyOCdJUIaS54gnNSvuevfUzfPpNNQteiXUkHxAMfnVZUaupvVX9LlqJ1FoK2LJr7WOIZgtQKigyK/aeqwes0S93f/HLR3isC2ZZoRwkGKsmVEYsVSZzpGpiJPCT+sZPNpQtz8gnz/X8B4rYLsCuC58+sdtrJ6h75PH1vYmW8nVo4xVtfkl9ihOTOKa+0irPls2xlpLPRWTaB5RheCbta0/M5WFlMF/96mdoRyrnPrV8HnW++b4/DQ3k4gQIA/9y93JLfF8NCchSgl795wicd6wu6ANcdVO2XsJUE4AoqT5FK0RXoSmAozONofFwo9cla27i+X077mS+Uf8TgC8/FytMsT6jeVoFLQ+FBXMbJrwGejq2xcrHIrneYTR5GZa/U69qFLRb7cfKOnlh/3hztziRcioinagxP0c8J2j3jQ/Q2mdwNiZ/+US/iB31kZQOUPYuaZToOr92TLhoTyV+7X6o7VVu8+Tp0aU2dr6QzFcFlHcoA25o14OsSBblWc10foXaBd3Rm9IgTpDpbLwEjZ5i7PmUoCRWHtN8nYxXvAlRvA6IIuwmvRbWhrznpvDKrI1UtrBw3S2kOgB19MtxxL4Svjt7nQKE87SG/1SC8mgPTVZ8cIiuTAnXwZdAh5UcZldqA2GscWufFNpZRKp/WnXE3af3h/0FYX7t9vnNceKTDAz2cRvRwbTnuaCBRD1GLYes87bQ/5n2tFUTzPmWtTlqWvkqRbFfLKWHN/HPXebfMdooTX9gdLzf7fGN0dIHvIqup/07dhBgUaKe8Vb9NdzjMuVFAO6ohnsSL+MUtjlFvIElG8MbdmvvEOVkAcNS1Oxi0+pg7Gb0Pr7B6ot+DznCPnHYlQQF"));

ASCII 561
$var=gzuncompress(base64_decode("eJztlD1uwzAMhXcDvgM3N0AvEaBA4KUdg46yRVtuZDLQTwzfvpSctHGDbu0QtJuhRz195JO8x8ohEIMPTlGPzkNgsHzCsnjlCAfiCYJBcNGiB0UaPINmqMtiC120FloexyGMSKHyMBkVoK5G2TPQYaAeuFucJo5WUxWgx5BUD53jURxnYDnAQR/nsqjhLfoAkyJSEFDsZ9lrBCKZdohWPMtixyEoGNUBsx5JC3kQurIoi2c8JTtOFv1wOpcc14IVirSueaK14iKBciyeuV2NHl2uXZd9HN66ea14NcsX62bGtZD7kaMHzM4mXnzLYo+VgKZpE6BqzXkmHbs0b8upaZmiA4PKpUE3iILZmjTiJoaspigDS5ZmTikmjkGUmvygESaERlyXSFNOF5eec06UKD4D79W4YE75iiwdHO3ZcyvC0OX+lT+AlN5k9MQp7dzzmCd1wWtE1xkQ8V7zukfmhxc2j9e0m+/XNrctPgJ9WZHS3Q/tvH4Bd/EA/u6v6p/595nfAV47k5c="));

Z 94
Assumed the same character set as given for C++ in the question.
There's not really much wiggle room on how to accomplish this aside from compression and base64 encoding. The only "step up" I can think of would be finagling base128 encoding, but there aren't enough "safe" characters to accomplish this given the variability of extended-ASCII.

is the output in php? then it is not valid source without at least <?

Ruby
Long version:
require 'tempfile'
tf=Tempfile.new('r')
while $stdin.gets{tf.puts $_}
tf.rewind
print "data='"
print IO.read(tf).gsub(/'/,"\\'")
print "'"

Golfed-up version
require 'tempfile'
t=Tempfile.new('r');while gets{t.puts $_};t.rewind;p "data='"+IO.read(t).gsub(/'/,"\\'")+"'"

When I run this on either input, I just get 'data=' followed by the raw binary, which doesn't work in Ruby.

@tecywiz121 you're right, modified to put the binary between "'"

What if the data contains a single quote?

@tecywiz121 I suppose it matters (though none of the test data, as binary, should contain a plaintext single quote), so I added a gsub(/'/,"\\'")


text:
Last-letter-first-letter sort
Given a list/array of names(String) sort them such that each name is followed by a name which starts with the last character of the previous name.
input
[
    Luis
    Hector
    Selena
    Emmanuel
    Amish
]
output:
[
    Emmanuel
    Luis
    Selena
    Amish
    Hector
]

What do we output if it's not possible with the given list? What about if there is more than one possible solution?

Why is this Java-specific?

What's your objective winning criterion? Shortest code, most upvotes, or something else?

Sorry for tagging it as java problem. @Kendall Frey Objective is to get a solution, and may be optimize it further.

@Gareth A solution will always exist for the given input.


text:
Morse code to standard output
This question involves taking input in Morse code as . (period) and - (minus symbol), with spaces to separate the input.  Your task is to convert the code to standard output.  You can assume that the only input contains character symbols found in the International Morse Code alphabet, found here: http://en.wikipedia.org/wiki/Morse_code#Letters.2C_numbers.2C_punctuation.
All output should use lowercase letters. A double space should be interpreted as a word space.
Sample input:
. -..- .- -- .--. .-.. . .-.-.-  ... --- ...

Output:
example. sos

Shortest code after two weeks wins.

You say only 'character symbols' is that characters and symbols?

@Quirliom All the "symbols" in that link are characters. Anything that you can put in a String is a character (well, basically). However, that part of the question is basically saying that every bit of morse will be valid.

@Quirliom Yes, every Morse 'character', such as .- for 'a' and . for 'e' is valid.  No non-Morse characters need be handled.

What about letter space and word space ? One space for the former and two (or more) for the latter ?

Slighly (un)related: http://stackoverflow.com/questions/1352587/code-golf-morse-code

@PaulR Yes, that sounds good.

Mathematica 62
Mathematica allows us to cheat
f=ToLowerCase@StringDrop[WolframAlpha[". .- "<>#,"Result"],2]&

f@"."
f@". -..- .- -- .--. .-.. . .-.-.-"
f@".... .- ...- .  -.-- --- ..-  -- --- --- . -..  - --- -.. .- -.-- ..--.."

e
example.
have you mooed today?

The first two symbols . and .- are necessary to interpret small codes correctly.

This is missing the conversion to lower case.

@PeterTaylor It can be easily modified to  f=ToLowerCase@StringDrop[WolframAlpha[". .- "<>#,"Result"],2]& for lower case.

Doesn't using the Wolfram Alpha api require an application id? If so, shouldn't that add to the character count? Nevertheless very clever solution.

@BjörnLindqvist Just evaluate exactly this command in Mathematica, it forks fine.

Drat, I was hoping to get here before the GolfScripters arrived :-(
Anyhoo...
C: 228 characters:
char n,t,m[9],*c=" etianmsurwdkgohvf l pjbxcyzq  54 3   2& +    16=/   ( 7   8 90    $       ?_    \"  .    @   '  -        ;! )     ,    :";
main(){while(scanf("%s",m)>0){for(t=m[6]=n=0;m[n];n++)t+=t+1+(m[n]&1);putchar(c[t]);}}

I thought I'd add an explanation of how this works.
The input data is parsed according to the tree data in *c, which can be expanded as follows (using · to represent a vacant node):
                     dot <-- (start) --> dash
                e                               t
        i               a               n               m
    s       u       r       w       d       k       g       o
  h   v   f   ·   l   ·   p   j   b   x   c   y   z   q   ·   ·
 5 4 · 3 · · · 2 & · + · · · · 1 6 = / · · · ( · 7 · · · 8 · 9 0
····$·······?_····"··.····@···'··-········;!·)·····,····:·······

Starting at the top of the tree, work your way down while moving to the left for a dot and to the right  for a dash. Then output whatever character you happen to be at when the input string ends (i.e., when a whitespace character is encountered). So for example, three dots and a dash will take you to v via e, i and s. Instead of explicitly checking for dots (ASCII \x2e) and dashes (ASCII \x2d), we only need to check the last bit (m[n]&1), which is 0 for . and 1 for -.
Six rows are enough to encode everything except $, which has 7 dot/dashes: ...-..-, but since the input data is guaranteed to be valid, this can easily be fixed by truncating the input at 6 characters (m[6]=0) and interpreting ...-.. as $ instead. We can also cut away the last 7 bytes from the tree data, since they are all empty and aren't needed if the input is valid.

Nice trick to discard the last character of 6-character codes and shorten the lookup table.

I am up voting as much for the clarity of the discussion as for the quality of the algorithm. Good work.

See if you could shave off a few chars by processing character-by-character instead of reading a whole string in. c could be inlined. Perhaps you could use modulo & an offset to try to squish the higher values together; this is what I do in my solution. Anyway, nice work!

GolfScript (116 113 97 chars)
This includes non-printable characters used in a lookup table, so I'm giving it as xxd output:
0000000: 6e2d 2720 272f 7b60 7b5c 6261 7365 2035
0000010: 3925 2210 a9cd 238d 57aa 8c17 d25c d31b
0000020: 432d 783e 277a 3823 e146 e833 6423 23ac
0000030: e72a 39d5 021c 4e33 3b30 3138 dc51 2044
0000040: 3aa7 d001 df4b 2032 333f 36ae 51c3 223d
0000050: 7d2b 5b35 2d34 5d2f 2b32 3333 257d 256e
0000060: 2b

This decodes to a program equivalent to
n-' '/{`{\base 59%"\x10\xA9\xCD#\x8DW\xAA\x8C\x17\xD2\\\xD3\eC-x>'z8#\xE1F\xE83d##\xAC\xE7*9\xD5\x02\x1CN3;018\xDCQ D:\xA7\xD0\x01\xDFK 23?6\xAEQ\xC3"=}+[5-4]/+233%}%n+

which is essentially
n-' '/{`{\base 59%"MAGIC STRING"=}+[5-4]/+233%}%n+

This uses a (non-minimal) perfect hash based on the core idea of An optimal algorithm for generating minimal perfect hash functions; Czech, Havas and Majewski; 1992. Their basic idea is that you use two hash functions, f1 and f2, together with a lookup table g, and the perfect hash is (g[f1(str)] + g[f2(str)]) % m (where m is the number of strings we wish to distinguish); the clever bit is the way they build g. Consider all of the values f1(str) and f2(str) for strings str of interest as nodes in an undirected graph, and add an edge between f1(str) and f2(str) for each string. They require not only that each edge be distinct, but that the graph be acyclic; then it is just a DFS to assign weights to the nodes (i.e. to populate the lookup table g) such that each edge has the required sum.
Czech et al generate random functions f1 and f2 which are expressed via lookup tables, but that's clearly no good: I searched for a suitable hash using simple base conversions with two distinct bases from -10 to 9. I also relaxed the acyclic requirement. I didn't want to assign the strings to values from 0 to 54, but to the corresponding ASCII codes, so rather than taking (g[f1(str)] + g[f2(str)]) % m I wanted (g[f1(str)] + g[f2(str)]) % N for some N > 'z'. But that allows freedom to try various N and see whether any of them allow a valid lookup table g, regardless of whether there are cycles. Unlike Czech et al I don't care if the search for the perfect hash function is O(n^4).
The graph generated by -4base and 5base mod 59 is:

which is fairly nice apart from the biggest connected component, which has three cycles of length 1. We have to go up to N=233 before we can find a g which is consistent.

Other possible encodings for the lookup table: difference encoding isn't going to help, because there isn't the structure. It might be possible to exploit the non-repetition of values by encoding as a permutation, but either the gaps need to be handled separately (54 output characters => 30 bytes of entropy, plus decoding; the runs need at least 15 bytes if encoded as a straight base conversion; might just be possible to improve on the current 92 bytes total) or we're permuting 138 items (more than 98 bytes of entropy, plus decoding).

Since it's a non-prefix code we can't easily try to palm the hard work off to a zlib implementation.

R, 145 bytes
Translated a dot to a 2, a dash to a 1 and interpreting the number in ternary and taking the mod 89, which gives a unique number we can use in a hash table. The presence of a 13 (111 base-3) means adding 1 because ASCII 13 doesn't work in TIO.
cat(c(letters,0:9,".")[match(strtoi(chartr(".-","12",scan(,"",t=scan(,""))),3)%%89+1,utf8ToInt('DG,)62	5N*EHMAI.%"!4=@'))],sep='')

Try it online!
R, 236 bytes (non-competing)
This is not going to be competitive, but it lets us show off something interesting in R: store the Morse code tree inside a quoted language structure m and retrieve it from the code of dots and dashes very simply using the fact that [[ can be applied recursively to lists. For example m[[c(2,2,3,2)]] retrieves dot, dot, dash, dot or "f".
m=quote(.(e(i(s(h(5,4),v(,3)),u(f,M(,2))),a(r(l,.(.(,.),)),w(p,j(,1)))),t(n(d(b(6),x),k(c,y)),m(g(z(7),q),o(D(8),S(9,0))))))
for(w in scan(,"",t=scan(,"")))
cat(chartr("MDS","-. ","if"(is.symbol(z<-m[[(utf8ToInt(w)==45)+2]]),z,z[[1]])))

Try it online!

C, 169 chars
I couldn't find a better hash function..
(I posted the unminified code but counted it minified; to minify just do :%s/ //g | %j! in vim, then put the space in the string literal back.)
c, v = 1;

main() {
  while (c = getchar(), ~c)
    v = c < 33? putchar(
      "& etianmsurwdkgohvf.l.pjbxcyzq..54.3.;!2).+...,16=/:..(.7.?_8.9o\"...$...@...'..-"[v < 64? (v != 40)*v : v % 51 + 33]
    ), 1 : v * 2 + c % 2;
}

Test run
(morse.in is just the whole alphabet in morse on separate lines):
% clang morse.c && ./a.out </tmp/morse.in
abcdefghijklmnopqrstuvwxyzO123456789.,?'!/()&:;=+-_"$@
% ./a.out <<<'. -..- .- -- .--. .-.. . .-.-.-  ... --- ...'
example. sos

Explanation
This one is fairly straightforward. c < 33 finds a whitespace/separator character (, \n, EOF, ...). c % 2 translates a dot or dash into a bit. The idea is to create a unique number for each character simply by interpreting it as a binary number (after prefixing it with 1 to deal with the variable length) (this interpretation is the v*2 + c%2 part).  I then get a 137-char LUT, which I compacted by hashing the resulting value (v < 64? v : v % 51 + 33, constants found via trial-and-error and by looking at the distribution and try to find a huge gap).  Unfortunately this hash function has a single collision, which is why I have to special-case the 40 → '&' mapping.

Powershell, 193 bytes
$n=1
-join("$args "|% t*y|%{if($_-32){$n=$n*2+($_-ne'.')}else{("  etianmsurwdkgohvf l pjbxcyzq  54 3   2& +~16=/   ( 7   8 90~~~?~ `"  .~@   '  -~~;! )~ ,~:~~~~$"-replace'~','    ')[$n]
$n=1}})

Less Golfed Test script:
$f = {

$n=1
-join(
    "$args "|% t*y|%{
        if($_-32){
            $n=$n*2+($_-ne'.')
        }else{
            ("  etianmsurwdkgohvf l pjbxcyzq  54 3   2& +~16=/   ( 7   8 90~~~?~ `"  .~@   '  -~~;! )~ ,~:~~~~$"-replace'~','    ')[$n]
            $n=1
        }
    }
)

}

@(
    ,("example. sos",". -..- .- -- .--. .-.. . .-.-.-  ... --- ...")
    ,("0123456789abcdefghijklmnopqrstuvwxyz","----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----. .- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..")
    ,("hello world", ".... . .-.. .-.. ---  .-- --- .-. .-.. -..")
) | % {
    $expected,$s = $_
    $result = &$f $s
    "$($result-eq$expected): $result"
}

Output:
True: example. sos
True: 0123456789abcdefghijklmnopqrstuvwxyz
True: hello world

JavaScript (165 bytes, only implementing four planes.)
n=''.replace(/\./g,1).replace(/-/g,0).split(' ')
l='|te|mnai|ogkdwrus|cöqzycxbjpälüfvh'.split('|')
r=''
for(i in n){r+=l[n[i].length][parseInt(n[i],2)]}
alert(r)

The input should be assigned to n, execute the following code to get the output:
n='. -..- .- -- .--. .-.. .'.replace(/\./g,1).replace(/-/g,0).split(' ')
l='|te|mnai|ogkdwrus|cöqzycxbjpälüfvh'.split('|')
r=''
for(i in n) {r+=l[n[i].length][parseInt(n[i],2)]}
alert(r)

Not only does this appear to be an incomplete implementation, but it doesn't even work. Fiddle + Chrome gives error Cannot read property '42' of undefined, and IdeOne also reports an error (although without a useful message).

Try fixing it :)

@PeterTaylor It is stated that it only support four planes, i.e. uptill 4 characters long morse codes, thus it won't accept . -..- .- -- .--. .-.. . .-.-.- as input, as last code is a 6 chars long. In the example script I omit it and go with . -..- .- -- .--. .-.., which alerts(example).

Here is a fiddle with the second block code: http://jsfiddle.net/aularon/AHY4e/1/

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