text:
CSS Color Golf!
You are a web developer, and your boss has decided to update the company's website. He has decided that less color is better, but he wants the site to look the same. You justly decide that he has no idea what he's talking about, but you're going to try anyway, because you're bored. Since the company has thousands of webpages, and each one has its own CSS, you decide to write a script to do the necessary changes. Parsing HTML not required.
All of the pages currently use a string like rgb(255,0,0) for a color. Given the three decimal values representing the RGB values of a CSS color attribute (in that order), return or print the shortest string representation of that color, such that it's usable for CSS like so: color:<your-result-here>;.
Here is a complete table of valid CSS Color Keywords. They are case-insensitive.
Examples:
Note that colors can be defined with 12 or 24 bits. The pattern #ABC is a shorter version of #AABBCC. Chuck Norris is a color.
Your program will only take in 3 integers, not a string (with the exception of the "bonus" mentioned later).
0, 0, 0         ->  #000        (same as #000000, but shorter)
255, 0, 0       ->  red
0, 128, 128     ->  TEAL
139, 0, 0       ->  DarkRed     (OR #8B0000)
72, 61, 139     ->  #483D8B
255, 255, 254   ->  #fffffe
255, 85, 255    ->  #f5f        (same as #ff55ff, but shorter)

Scoring / Rules

Shortest code wins!
Standard loopholes are disallowed, with the exception of built-ins.
-50% bytes (the bonus is rounded down) if you accept any* valid color selector and output the shortest. So DarkSlateBlue would output #483D8B, #F00 outputs red, etc.

*This only includes RGB, hex codes, and names.
Note that some colors have alternate names due to X11 (like Fuchsia and Magenta, or Cyan and Aqua). The alternate names are included in the linked list of CSS Color Keywords according to the W3 standard.

CSS3 is Turing Complete. That'd be worth a bounty.

Edit:

PLEASE RUN YOUR CODE ON THE TEST CASES!

Here's a related question: http://codegolf.stackexchange.com/questions/13132/color-rgb-int-to-hex

This is the minimal set of colour names you need to consider.

Does an answer wishing to score the -50% bonus need to parse hsl(...) too? What about rgba(...) and hsla(...)? :)

According to this link on colors in CSS, White is #000000.  How did you come up with #000?  And if fewer than 6 digits are allowed, why not #0? http://www.w3schools.com/cssref/css_colors.asp, , the CSS

@DavidCarraher See http://stackoverflow.com/q/8318911/791604 for an in-depth explanation. I would suspect many of the answers here are actually not outputting minimal colors going by the flexible implementation available in browsers (but are outputting minimal colors going by the spec given in the question here).

Perl, 212 - 50% = 106 bytes
use aliased Graphics::ColorNames,G;sub c{tie%c,G,CSS;$_=pop;$c={reverse%c}->{$_=sprintf'%02x'x(@0=/(\d+, ?)((?1))(\d+)/)||$c{s/#(.)(.)(.)$|#/\1\1\2\2\3\3/r},@0};s/(.)\1(.)\2(.)\3|/#\1\2\3/;y///c>length$c&&$c||$_}

With newlines added:
use aliased Graphics::ColorNames,G;
sub c{
  tie%c,G,CSS;$_=pop;
  $c={reverse%c}->{
    $_=sprintf'%02x'x(@0=/(\d+, ?)((?1))(\d+)/)||$c{s/#(.)(.)(.)$|#/\1\1\2\2\3\3/r},@0
  };
  s/(.)\1(.)\2(.)\3|/#\1\2\3/;
  y///c>length$c&&$c||$_
}

Test Cases
use feature say;

say c '#f00';
say c '#FF0000';
say c '#112233';
say c '#f0ffff';
say c 'azure';
say c 'DARKSLATEBLUE';
say c 'rgb(255, 127, 80)';
say c 'rgb(255, 255, 254)';
say c 'rgb(255,228,196)';

Output
red
red
#123
azure
azure
#483d8b
coral
#fffffe
bisque

Perl, no bonus, 144 bytes
use aliased Graphics::ColorNames,G;sub c{tie%c,G,CSS;$c={reverse%c}->{$_=sprintf'%02x'x3,@_};s/(.)\1(.)\2(.)\3|/#\1\2\3/;y///c>length$c&&$c||$_}

With newlines added:
use aliased Graphics::ColorNames,G;
sub c{
  tie%c,G,CSS;
  $c={reverse%c}->{
    $_=sprintf'%02x'x3,@_
  };
  s/(.)\1(.)\2(.)\3|/#\1\2\3/;
  y///c>length$c&&$c||$_
}

Graphics::ColorNames isn't a core module, but it's been around since 2001. You may need to install it via:
cpan install Graphics::ColorNames
cpan install Graphics::ColorNames::CSS

The hex representation is preferred if the color name has the same length.

Test Cases
use feature say;

say c 0, 0, 0;
say c 255, 0, 0;
say c 0, 128, 128;
say c 139, 0, 0;
say c 72, 61, 139;
say c 255, 255, 254;
say c 255, 85, 255;

Output
#000
red
teal
#8b0000
#483d8b
#fffffe
#f5f

Any chance you could cut 4 bytes off for the tie?

@mbomb007 6 bytes, in fact.

Do I hear 4 more? This competition is tough.

@mbomb007 raise.

C#6 527 bytes / 2 bonus = 264
EDIT: Woot!  I finally got the bonus answer with a lower score than the basic answer!
I've written just a function.  It requires a using statement (included.)
C# has a nice list of known colours to work with, but it insists on including the Alpha channel.  The known colours also includes all system colours, two of which have names less than 7 characters long, so these needed to be stripped out.
Here's the bonus solution, supporting formats such as:

12, 34, 56
#123
#123456
DarkSlateBlue

Completely golfed:
using System.Drawing;int H(string s,int i,int l)=>Convert.ToInt32(s.Substring(i*l+1,l),16)*(l<2?17:1);string D(string a){int i=17,j=a.Length/3,n;var d=a.Split(',');Color k,c=a[0]<36?Color.FromArgb(H(a,0,j),H(a,1,j),H(a,2,j)):Color.FromName(a);c=c.A>0?c:Color.FromArgb(int.Parse(d[0]),int.Parse(d[1]),int.Parse(d[2]));j=c.R%i+c.G%i+c.B%i<1?3:6;n=c.ToArgb();a="#"+(j<6?c.R/i<<8|c.G/i<<4|c.B/i:n&0xffffff).ToString("x"+j);for(i=26;i++<167;k=Color.FromKnownColor((KnownColor)i),a=n==k.ToArgb()&k.Name.Length<=j?k.Name:a);return a;}

Indentation and new lines for clarity:
using System.Drawing;
int H(string s,int i,int l)=>Convert.ToInt32(s.Substring(i*l+1,l),16)*(l<2?17:1);
string C(string a){
    int i=17,j=a.Length/3,n;
    var d=a.Split(',');
    Color k,c=a[0]<36
        ?Color.FromArgb(H(a,0,j),H(a,1,j),H(a,2,j))
        :Color.FromName(a);
    c=c.A>0?c:Color.FromArgb(int.Parse(d[0]),int.Parse(d[1]),int.Parse(d[2]));
    j=c.R%i+c.G%i+c.B%i<1?3:6;
    n=c.ToArgb();
    a="#"+(j<6?c.R/i<<8|c.G/i<<4|c.B/i:n&0xffffff).ToString("x"+j);
    for(i=26;i++<167;
        k=Color.FromKnownColor((KnownColor)i),
        a=n==k.ToArgb()&k.Name.Length<=j?k.Name:a
    );
    return a;
}

C#, 265 bytes
Here's the basic solution.
using System.Drawing;string C(int r,int g,int b){int i=17,c=r<<16|g<<8|b,j=r%i+g%i+b%i<1?3:6;var o="#"+(j<6?r/i<<8|g/i<<4|b/i:c).ToString("x"+j);for(i=26;i++<167;){var k=Color.FromKnownColor((KnownColor)i);o=c<<8==k.ToArgb()<<8&k.Name.Length<=j?k.Name:o;}return o;}

Indentation and new lines for clarity:
using System.Drawing;

string C(int r,int g,int b){
    int i=17,
        c=r<<16|g<<8|b,
        j=r%i+g%i+b%i<1?3:6;
    var o="#"+(j<6?r/i<<8|g/i<<4|b/i:c).ToString("x"+j);
    for(i=26;i++<167;){
        var k=Color.FromKnownColor((KnownColor)i);
        o=c<<8==k.ToArgb()<<8&k.Name.Length<=j?k.Name:o;
    }
    return o;
}

Mathematica 207 242 500-250=250 bytes
Update:
This works with inputs consisting of rgb triples, color names, or hex numbers.
(12 bit) color-depth output now works fine, thanks to an excellent article on Color Bit Depth Reduction.  The basic idea is that, if an RGB triple {r,g,b}, where r, g, and b are in the range of 0-255, (i.e. hex 00-ff) can be represented without loss as a number in the range of 0-15 (i.e. 0-f), then one may use the 3 digit hex number instead of the 6 digit number.  Turns out that this will occur whenever 17 (i.e 255/15) divides r, g, and b.
Only built-in functions are used. Mathematica has rules for replacing HTML colors names with RGB triples.  For example, one rule is
"Teal"-> RGBColor[0, 128, 128].
When such rules are inverted, rgb values (recalibrated to the range, {0, 255}) can be replaced with color names.
q=ColorData["HTML","ColorRules"];
j=q/.{(c_ -> RGBColor[r_,g_,b_]):> (Floor[255{r,g,b}]-> c)};
k=Reverse/@j;
v@l_:=And@@IntegerQ/@(l/17);
y@l_:=If[v@l,l/17,l];
h@l_:="#"<>(IntegerString[#,16,If[v@l,1,2]]&/@y@l)
o@h_:=Module[{c=(StringLength[h1=StringDrop[h,1]]==6)},FromDigits[#,16]&/@StringPartition[h1,If[c,2,1]]*If[c,1,17]]
u@l_:=ToString[l/.j]
m@s_:=s/.q/.RGBColor[r_,g_,b_]:>Floor[255{r,g,b}]
f@n_:=SortBy[{u@n,h@n},StringLength][[1]]
z@d_:= (If[StringQ@d,If[StringTake[d,1]=="#",e=o@d,e=m@d],e=d];f@e)

Examples
z /@ {{0, 0, 0}, {255, 0, 0}, {0, 128, 128}, {139, 0, 0}, {255, 255,
   255}, {72, 61, 139}, {255, 255, 254}, {255, 85, 255}}

{"#000", "Red", "Teal", "#8b0000", "#fff", "#483d8b", "#fffffe","#f5f"}

z /@ {"Red", "DarkSlateBlue", "Teal", "Black"}

{"Red", "#483c8b", "Teal", "#000"}

z /@ {"#000", "#f00", "#008080", "#8b0000", "#fff", "#483d8b", "#fffffe", "#f5f"}

{"#000", "Red", "Teal", "#8b0000", "#fff", "#483d8b", "#fffffe", \
  "#f5f"}

Commented, Ungolfed Code
(* rules for replacing a color name with a color swatch, e.g. RGBColor{255,17,0}
q=ColorData["HTML","ColorRules"];

(* rules for replacing a list of 3 integers with the respective color name, if one exists.  And the same rules, reversed. *)
rulesListsToColorNames=(q)/.{(c_ -> RGBColor[r_,g_,b_]):> (Floor[255{r,g,b}]-> c)};

rulesColorsToLists=Reverse/@rulesListsToColorNames;

(*tests whether a 24 bit hex color can be represented as a 12 bit color with no loss. reduce can change the 24 bit expression to a 12 bit expression. *)
depthReducible[l_List]:=And@@IntegerQ/@(l/17);
reduce[l_List]:=If[depthReducible@l,l/17,l];

(*RGB list changed to a Hex number *)
fromListToHex[l_List]:="#"<>(IntegerString[#,16,If[depthReducible@l,1,2]]&/@reduce[l])

(* Hex number changed to RGB list. *)
fromHexToList[h_String]:=Module[{c=(StringLength[h1=StringDrop[h,1]]==6)},
FromDigits[#,16]&/@StringPartition[h1,If[c,2,1]]*If[c,1,17]
]

(* More conversions *)
fromListToColorName[l_List]:=ToString[l/.rulesListsToColorNames]
fromColorNameToHex[s_String]:=fromListToHex[s/.rulesColorsToLists]
fromColorNameToList[s_String]:=s/.q/.RGBColor[r_,g_,b_]:>Floor[255{r,g,b}]

(* choses the shortest valid CSS expression of a color *)
f@n_List:=SortBy[{fromListToColorName[n],fromListToHex[n]},StringLength][[1]]

(* converts any input into an RGB list and calls f  *)
returnShortestColor[d_]:=
 (If[StringQ[d],
   If[StringTake[d,1]=="#",
     e=fromHexToList@d,
     e=fromColorNameToList@d],
   e=d];
f@e)

Isn't 255 in base 10 equal to FF in Base 16?  So that should make #FFFFFF, which is longer than White.   I'm finding #000 unusual but will look into the quirks of CSS to be sure.

@DavidCarraher: CSS colors may be specified as 24 bits or 12 bits. #FFF is the same as #FFFFFF (all bits one) which is the same as white. Also, #0 is invalid because it's neither 24 bits nor 12 bits

slebetman, Thanks for the clarification, which confirms @mbomb007's observation.

CoffeeScript, 411 404 388 384 382/2 = 191
UPD: Pretty sure it is final result
Hope, it's okay to use window.document.*. Check rgb function and eval call.
s=(c,rgb=(r,g,b)->(2**24+(r<<16)+(g<<8)+b).toString 16)->d=y=document.body;r=(q=(a)->y.style.color=a;d[b='#'+eval(getComputedStyle(y).color)[1...].replace /(.)\1(.)\2(.)\3/,'$1$2$3']=a;b) c;(d='NavyGreenTealIndigoMaroonPurpleOliveGraySiennaBrownSilverPeruTanOrchidPlumVioletKhakiAzureWheatBeigeSalmonLinenTomatoCoralOrangePinkGoldBisqueSnowIvoryRed'.match /.[a-z]+/g).map(q);d[r]||r

Test results
rgb(   0,   0,   0 ) -> #000
rgb( 255,   0,   0 ) -> Red
rgb(   0, 128, 128 ) -> Teal
rgb( 139,   0,   0 ) -> #8b0000
rgb(  72,  61, 139 ) -> #483d8b
rgb( 255, 255, 254 ) -> #fffffe
rgb( 255,  85, 255 ) -> #f5f
darkslateblue        -> #483d8b
indigo               -> Indigo
#f00                 -> Red

Commented code
s = ( c,
    rgb = ( r, g, b ) ->
        return ( 2 ** 24 + ( r << 16 ) + ( g << 8 ) + b )
        .toString( 16 )
) ->

This will save some bytes.
    d = y = document.body

q function will place input color to document.body.style.color and get compiled color as rgb(...).
Also it will store result as hexColor:inputColor in d.
Notice eval use.
rgb(100,100,100) is a valid JavaScript function call with three number arguments.
rgb function will convert arguments to single 24/12 HEX notation (like #fff, #f0f0f0).
    r = (
        q = ( a ) ->
            y.style.color = a
            b = '#' + eval( getComputedStyle( y ).color )[ 1... ].replace( /(.)\1(.)\2(.)\3/, '$1$2$3' )
            d[ b ] = a
            return b
    )( c )

Split string to array of color names, create lookup object.
    ( d = 'NavyGreenTeal...'.match( /.[a-z]+/g )).map( q )

And return HEX if no shorter variant in d.
    return d[ r ] or r

Stylus, 238 234/2 = 117
More CSS-like solution! Stylus already has great support for color manipulation, so desired function is pretty small and not golfed a lot.
f(c){for n in split(' ''navy green teal indigo maroon purple olive gray sienna brown silver peru tan orchid plum violet khaki azure wheat beige salmon linen tomato coral orange pink gold bisque snow ivory red'){lookup(n)==c?c=s(n):c}}

Test it here
body
  color f(rgb(0, 0, 0))
  color f(rgb(255, 0, 0))
  color f(rgb(0, 128, 128))
  color f(rgb(139, 0, 0))
  color f(rgb(72, 61, 139))
  color f(rgb(255, 255, 254))
  color f(rgb(255, 85, 255))
  color f(darkslateblue)
  color f(indigo)
  color f(#f00)
  color f(rgba(255,0,0,1))
  color f(rgba(255,0,0,0.5))

Welcome to PPCG! That's a really nice solution!

not golfed a lot. You'd better try to golf it some more if you want to win. Someone is beating you by one.

@mbomb007, alright, golfed a bit.

It looks as though you've been beaten. Maybe you can try cramming the colors together without spaces, but padded to five characters, then split every five and trim? Not sure if that would save bytes?

Matlab 617
A lot of preprocessing and hardcoding. The minimal set of colour names you have to consider are these. Too bad Matlab does not have built in color names=/
function s=f(r,g,b);
t=255;
c=[r,g,b];
a=[0 t t;240 t t;245 245 220;t 228 196;0 0 t;165 42 42;t 127 80;0 t t;t 215 0;75 0 130;t t 240;240 230 140;0 t 0;250 240 230;t 165 0;218 112 214;205 133 63;t 192 203;221 160 221;t 0 0;250 128 114;160 82 45;t 250 250;210 180 140;t 99 71;238 130 238;245 222 179;t t t;t t 0];
s=textscan('aqua azure beige bisque blue brown coral cyan gold indigo ivory khaki lime linen orange orchid peru pink plum red salmon sienna snow tan tomato violet wheat white yellow','%s');
i=find(ismember(a,c,'rows'));
k=1;
if i>0;s=s{1}{i};elseif ~any(mod(c,16));k=16;end;d=dec2hex(c/k,2-(k>1))';s=['#',d(:)']

You've left the hardcoded r=0;g=16;b=0; in there, though it's not counted in your score.

Oh, I pasted the wrong version, thanks for letting me know!

Python 3, 857 795 bytes
Having to manually specify all of the accepted colours required did increase the byte count on this one :/
c(a) takes one argument, a, which comes in the form of rgb(#,#,#). From that, the rgb and brackets are removed and the string is then split by commas into an array. c(x,y,z) takes 3 ints, the r, g and b values of the rgb colour to process. We put those together in an array a. We then use Python's built-in hex function which converts a Base 10 number to a Base 16 number on our array and create a hex string (this is done in the for loop). The if statements convert colours like 000000 to 000, and replace the known colours using a dictionary.
Here it is (thanks to @undergroundmonorail for tip about ; in Python):
def c(x,y,z):
  a=[x,y,z];b="";
  for i in a:
    i=hex(i)[2:]
    if len(i)<2:i="0"+i;
    b+=i
  k={"00ffff":"AQUA","f0ffff":"AZURE","f5f5dc":"BEIGE","ffe4c4":"BISQUE","0000ff":"BLUE","a52a2a":"BROWN","ff7f50":"CORAL","ffd700":"GOLD","808080":"GRAY","008000":"GREEN","4b0082":"INDIGO","fffff0":"IVORY","f0e68c":"KHAKI","00ff00":"LIME","faf0e6":"LINEN","800000":"MAROON","000080":"NAVY","808000":"OLIVE","ffa500":"ORANGE","da70d6":"ORCHID","cd853f":"PERU","ffc0cb":"PINK","dda0dd":"PLUM","800080":"PURPLE","ff0000":"RED","fa8072":"SALMON","a0522d":"SIENNA","c0c0c0":"SILVER","fffafa":"SNOW","d2b48c":"TAN","008080":"TEAL","ff6347":"TOMATO","ee82ee":"VIOLET","f5deb3":"WHEAT","ffff00":"YELLOW"}
  if b[:3]==b[3:]:b=b[:3];
  if b in k:b=k[b];
  else:b="#"+b;
  return b

Old Version:
def c(a):
  a=a[4:-1].split(",")
  b=""
  for i in a:
    i=hex(int(i))[2:]
    if len(i)<2:
      i="0"+i
    b+=i
  k = {"00ffff":"AQUA","f0ffff":"AZURE","f5f5dc":"BEIGE","ffe4c4":"BISQUE","0000ff":"BLUE","a52a2a":"BROWN","ff7f50":"CORAL","ffd700":"GOLD","808080":"GRAY","008000":"GREEN","4b0082":"INDIGO","fffff0":"IVORY","f0e68c":"KHAKI","00ff00":"LIME","faf0e6":"LINEN","800000":"MAROON","000080":"NAVY","808000":"OLIVE","ffa500":"ORANGE","da70d6":"ORCHID","cd853f":"PERU","ffc0cb":"PINK","dda0dd":"PLUM","800080":"PURPLE","ff0000":"RED","fa8072":"SALMON","a0522d":"SIENNA","c0c0c0":"SILVER","fffafa":"SNOW","d2b48c":"TAN","008080":"TEAL","ff6347":"TOMATO","ee82ee":"VIOLET","f5deb3":"WHEAT","ffff00":"YELLOW"}
  if b[:3]==b[3:]:
    b=b[:3]
  if b in k:
    b=k[b]
  else:
    b="#"+b
  return "color:"+b+";"

Maybe I'll add the bonus to it, I don't know yet. It could definitly do with 50% bytes off!
-Toastrackenigma

general python golfing tips: many of your newlines can be replaced by ;, saving the indentation. for example: a=a[4:-1].split(",");b="". any if, else, for, while, etc block with only one line can be written as if b in k:b=k[b].finally, you can lose a lot of your whitespace in the middle of lines, e.g. k = { -> k={ and return "color: -> return"color:

also, welcome to PPCG :)

That literal k is huge. As all color codes are in lowercase and all color names are in uppercase, you could just write it as a single string, then parse it with re.findall() (so will also need import re): http://pastebin.com/rQHqgxXS

@undergroundmonorail Thanks for that, should save a lot of space :D

@mbomb007 OK, I wasn't quite sure how you wanted the output or input - got a little confused there :P I did run the code on the test cases to ensure it works properly, do you want me to upload my results?

JavaScript (ES6), 499 611
Edit Added the test cases in the question
Note: I kept just the color names that are shorter than the hex equivalent.
Note 2: this can surely be golfed more...

f=(r,g,b,k='#'+(r%17|g%17|b%17?1<<24|r<<16|g<<8|b:4096|(r*256+g*16+b)/17).toString(16).slice(1))=>
("#d2b48cTAN#f00RED#ff7f50CORAL#f5deb3WHEAT#ff6347TOMATO#ffd700GOLD#008000GREEN#faf0e6LINEN#f5f5dcBEIGE#da70d6ORCHID#4b0082INDIGO#ffc0cbPINK#f0e68cKHAKI#008080TEAL#ee82eeVIOLET#dda0ddPLUM#fa8072SALMON#ffa500ORANGE#a0522dSIENNA#800000MAROON#800080PURPLE#ffe4c4BISQUE#f0ffffAZURE#fffff0IVORY#cd853fPERU#808000OLIVE#c0c0c0SILVER#fffafaSNOW#a52a2aBROWN#000080NAVY#808080GRAY"
.match(k+'([A-Z]+)')||[,k])[1]

// TEST
;[[0,0,0,'#000'],[255,0,0,'red'],[0,128,128,'TEAL'],[139,0,0,'#8B0000'],[72,61,139,'#483D8B'],[255,255,254,'#fffffe'],[255,85,255,'#f5f']]
.forEach(([r,g,b,t])=>(x=f(r,g,b),o+=r+','+g+','+b+' -> '+x+' '+(x.toUpperCase()==t.toUpperCase()?'ok':'error('+t+')')+'\n'),o='')
O.innerHTML=o

function go()
{
  var r,g,b
  [r,g,b] = I.value.match(/\d+/g)
  O.innerHTML=r+','+g+','+b+' -> '+f(r,g,b)+'\n'+O.innerHTML
}
R,G,B: <input id=I><button onclick="go()">--></button>

Less golfed
f=(r,g,b) => (
   k='#'+(
     r%17|g%17|b%17
     ? 1<<24|r<<16|g<<8|b
     : 4096|r/17<<8|g/17<<4|b/17
    ).toString(16).slice(1),
   s = "#d2b48cTAN#f00RED#ff7f50CORAL#f5deb3WHEAT#ff6347TOMATO#ffd700GOLD#008000GREEN#faf0e6LINEN#f5f5dcBEIGE#da70d6ORCHID#4b0082INDIGO#ffc0cbPINK#f0e68cKHAKI#008080TEAL#ee82eeVIOLET#dda0ddPLUM#fa8072SALMON#ffa500ORANGE#a0522dSIENNA#800000MAROON#800080PURPLE#ffe4c4BISQUE#f0ffffAZURE#fffff0IVORY#cd853fPERU#808000OLIVE#c0c0c0SILVER#fffafaSNOW#a52a2aBROWN#000080NAVY#808080GRAY",
   m = s.match(k+'([A-Z]+)'), // names are upper, hex codes are lower
   (m || [,k])[1] // if no match use the code
)

Those underscores… According to my counting, would be shorter without them. Just quote the codes starting with a digit and keep the others unquoted: {f00:"red";"008000":"green"}.

@manatwork nice trick. But a literal object is rarely a good choice for code golf. A simple string is better

Correct. I already made a comment in that sense to our fresh sitemate.

@mbomb007 Test cases added. The snippet won't work in chrome being EcmaScript 6, and Chrome is not fully compliant (quite tired to repeat this again and again). Test in Firefox.

Python 3 + matplotlib, 193 bytes
import matplotlib.colors as M
def f(c):
 H=h=M.rgb2hex([i/255for i in c]).upper()
 if all(v%17<1for v in c):h=h[::2]
 for n,x in M.CSS4_COLORS.items():
  if H==x and len(n)<len(h):h=n
 return h

Input is taken as a tuple or array of integers.
Try it here
Less golfed:
import matplotlib.colors as mcolors

def f(c):
  # Save two copies of the uppercase hex value.
  # Inconvenient, but it takes decimals instead of integers,
  # and it returns lowercase, but the dictionary has uppercase. :'(
  H=h=mcolors.rgb2hex([i/255 for i in c]).upper()

  # Check if all 3 integers are divisible by 17,
  # because that means in hex the digits are the same,
  # similar to how that works for multiples of 11 in base 10,
  # or multiple of N+1 in base N.
  if all(v%17<1 for v in c):
    # Get every other character from the hex string
    h=h[::2]

  # Loop through the dictionary. Way too verbose for me to appreciate.
  for n,x in mcolors.CSS4_COLORS.items():
    # If the name is shorter, use it.
    # H is needed, because "h" is the shortened.
    if H==x and len(n)<len(h):h=n

  return h

CSS4_COLORS contains a dictionary of the color names and hex values. Unfortunately, the dictionary is "backwards" from what I'd like. Also, this could likely be used to create a better score using the bonus, though I don't think it'd win.


text:
Generate the Temple Skyline Sequence
Consider the following process:

Take some non-negative integer N.
e.g. N = 571

Express it in binary with no leading zeroes. (Zero itself is the only exception, becoming 0.)
e.g. 571 = 1000111011 in binary

Break apart consecutive runs of ones and zeroes in this binary representation.
e.g. 1000111011 → 1, 000, 111, 0, 11

Sort the runs from longest to shortest.
e.g. 1, 000, 111, 0, 11 → 000, 111, 11, 1, 0

Overwrite all the digits in each run with alternating 1's and 0's, always starting with 1's.
e.g. 000, 111, 11, 1, 0 → 111, 000, 11, 0, 1

Concatenate the result to get a new binary number.
e.g. 111, 000, 11, 0, 1 → 1110001101 = 909 in decimal

When you plot the values produced by this process you get a pretty neat graph:

And it's hopefully apparent why I'm calling the resulting sequence the Temple Skyline sequence:

Challenge
Write a program or function that takes in a non-negative integer N and prints or returns the corresponding Temple Skyline sequence number. Your input and output should both be in decimal.
e.g. If the input is 571 the output should be 909.
The shortest code in bytes wins.
For reference, here are the terms in the sequence from N = 0 to 20:
0   1
1   1
2   2
3   3
4   6
5   5
6   6
7   7
8   14
9   13
10  10
11  13
12  12
13  13
14  14
15  15
16  30
17  29
18  26
19  25
20  26

Here are the terms from 0 to 1023.

Pyth, 20 19 bytes
ACr.BQ8|is*V_SGH2 1

1 byte saved by Jakube
Test Suite
Uses the fact that after run-length-encoding, the runs are the desired runs in the output.
Lost 3 bytes special casing 0.

CJam, 25 23 22 bytes
ri1e>2be`z($W%a\+ze~2b

Just a bit of run-length encoding. -1 thanks to @MartinBüttner.
Try it online / Test suite.
Explanation
ri        Read n from input as int
1e>       Take max with 1 (special case for n = 0)
2b        Convert n to binary
e`        Run length encode
z         Zip, giving a pair [<counts> <10101.. array>]
($W%      Drop the counts array and sort decending
a\+z      Add it back to the 10101.. array and re-zip
e~        Run length decode
2b        Convert from binary

Pyth - 21 20 bytes
Thanks to @sok for saving me one byte!
is.em%hk2hb_Sr.BQ8 2

Try it here online.

You can use .BQ instead of jQ2, which means you can lose the space between the 8 and the preceding 2.

is*R\s=!Z_ShMr.BQ8 2` is an interesting same-length solution. Mostly posting because I didn't really expect the assign in a map argument to work.

@FryAmTheEggman Replace \swith]`. Saves one byte.

Python 2, 121 bytes 125
121: Thanks to Sp3000 for shaving off 4 bytes!

import re;print int("".join(n*`~i%2`for i,n in enumerate(sorted(map(len,re.split('(1*|0+)',bin(input())[2:])))[::-1])),2)

125

import re;print int("".join("10"[i%2]*n for i,n in enumerate(sorted(map(len,re.split('(1*|0+)',bin(input())[2:])))[::-1])),2)

Nice! I believe you can also do n*\~i%2`forinstead of"10"[i%2]*n for`

Thanks for editing! I had to rush off quickly but wanted to submit because I thought this was a beautiful challenge and a good one for a first submission. I will check out your submission shortly!

I think that you can save some bytes by using sorted(...,key=len) instead of using map(len,... but I don't fully comprehend your program right now so I'm not positive that would benefit you.

Hey @Cole I am mapping len because that is the only information I need to replicate the amount of 1 and 0. I tried your suggestion and it adds 2 bytes, as I will have to use len twice then, but thanks for the suggestion!

JavaScript ES6, 110 bytes 113 116 119 120
Saved 3 bytes thanks to @intrepidcoder
Saved 3 bytes thanks to @NinjaBearMonkey
n=>+('0b'+n.toString(2).split(/(0+)/).sort((b,a)=>a.length-b.length).map((l,i)=>l.replace(/./g,i-1&1)).join``)

Straight forward approach. Don't like the length of the sort function but I can't think of a way to golf it.

I think you can use a + instead of eval.

@intrepidcoder thanks, that saved 3 bytes!

I can't test this, but split(/(0+)/g) should be able to replace match(/(.)\1*/g).

@NinjaBearMonkey thanks, that saved 3 bytes!

Saving one byte:  +(s=0,  ... .map(l=>l.replace(/./g,s^=1))...)

Nice work! Are you sure you need the parentheses in the first regex?

@ETHproductions unfortunately yeah, otherwise split will actually split the 0's themselves if that makes sense

C++, 535 527 Bytes
(thanks zereges for shaving off some bytes.)
Now that we got rid of those bytes the program is now competetive ;)
#include<iostream>
#include<cmath>
int main(){int I,D;std::cin>>I;while(I>int(pow(2,D))){D++;}int L[99];int X=0;int Z=0;int O=0;for(int i=D-1;i>=0;i--){if( int(pow(2,i))&I){if(Z>0){L[X]=Z;Z=0; X++;}O++;}else{if(O>0){L[X] = O;O=0;X++;}Z++;}}if(Z>0){L[X]=Z;Z=0;X++;}if(O>0){L[X]=O;O=0;X++;}int P=0;bool B = true;int W = D-1;for(int j=0;j<X;j++){int K=0;int mX=0;for(int i=0;i<X;i++){if(L[i]>K){K=L[i];mX=i;}}L[mX]=0;if(B){for(int k=0;k<K;k++){P+=int(pow(2,W));W--;}}else{for(int k=0;k<K;k++){W--;}}B^=1;}std::cout<<P;return 0;}

I'm new to golfing, so please give me some tips in the comments.
Things like "you don't need those brackets" or "use printf" are all helpful, but I also appreciate advice on the logic. Thanks in advance!
For ease of reading, I present the ungolfed version:
#include<iostream>
#include<cmath>
int main()
{
int input,digits;

std::cin>>input;
while(input > int(pow(2,digits))){digits++;}

int list[99];
int index=0;
int zCounter=0;
int oCounter=0;

for(int i=digits;i>0;i--)
{
    if( int(pow(2,i-1))&input)
    {
        if(zCounter>0)
        {
            list[index] = zCounter;
            zCounter=0;
            index++;
        }
        oCounter++;
    }
    else
    {
        if(oCounter>0)
        {
            list[index] = oCounter;
            oCounter=0;
            index++;
        }
        zCounter++;
    }
}
if(zCounter>0)
{
        list[index] = zCounter;
        zCounter=0;
        index++;
}
if(oCounter>0)
{
        list[index] = oCounter;
        oCounter=0;
        index++;
}

int output = 0;
bool ones = true;
int power = digits-1;
for(int j=0;j<index;j++)
{
    int max=0;
    int mIndex=0;
    for(int i=0;i<index;i++)
    {
        if(list[i]>max){max=list[i];mIndex=i;}
    }
    list[mIndex]=0;

    if(ones)
    {
        for(int k=0;k<max;k++)
        {
            output+=int(pow(2,power));
            power--;
        }
    }
    else
    {
        for(int k=0;k<max;k++)
        {
            power--;
        }
    }
    ones^=1;

}
std::cout<<output;
return 0;
}

EDIT golfed version brought down a couple bytes, ungolfed version unchanged

You can instead of int a; int b; use int a,b;. Also variables in in global scope are initialized with 0. Also you don't have to use curly brackets when there is only one command to be executed. Also ones=!ones; can be simplified as ones ^= 1;

Saved some bytes thanks

Shift your first for loop by 1, i.e. for(int i=D;i;i--) and use pow(2,i-1) inside the loop.

@LiamNoronha You actually did not save what I recommended :)

I changed it in the golfed version. I didn't touch the ungolfed version. I'll do that in a minute

@LiamNoronha Check this out. There is still a lot of space for improvement. E.g. reusing variables (saves definition), ones can also be int. Maybe macroing int(pow(i)) into P(i). I would recommend you reading the discussion here

You are taking a power of 2, so instead of pow(2, D) you could just write 2<<D. You can save a statement by replacing L[X]=O;X++; by L[X++]=O;. And as mentioned, your initializations may be shortened, e.g. int a,b; instead of int a=0;int b=0; and bool b=1 instead of bool b = true. Golfing turns out to be a lot more than just removing all the whitespace, doesn't it ;)

Yes it does. It's pretty interesting to get into (and frustrating)

Perl 5.10, 121 101
say oct"0b".join'',map{$|=1-$|;$_=~s/./$|/gr}sort{length$b<=>length$a}(sprintf"%b",shift)=~/(0*|1*)/g

I think the sort part can be shorter.
Edit: -20 bytes, thanks to symbabque!

You can get rid of the \n, and the m is not required for regular expression matching. In your substitution, just use . instead of the char group.

No need for the grep part either. The oct is neat though :)

Thank you, I accidentally left those parts from the original code.

Haskell, 132 131 bytes
import Data.List
g 0=[]
g n=mod n 2:g(div n 2)
q=[1]:[0]:q
f=foldl((+).(2*))0.concat.zipWith(<*)q.sortOn((-)0.length).group.g.max 1

Usage example:
> map f [0..20]
[1,1,2,3,6,5,6,7,14,13,10,13,12,13,14,15,30,29,26,25,26]

How it works:
                 max 1         -- fix n=0: f(0) is the same as f(1)
               g               -- turn into binary, i.e. list of 0s and 1s
            group              -- group sequences of equal elements
         sortOn((-)0.length)   -- sort groups on negative length
      zipWith(<*)q             -- map each element in a group to constant 1 or 0 by turns
   concat                      -- flatten all groups into a single list
foldl((+).(2*))0               -- convert back to decimal

J - 30 bytes
Function taking integer on right. Correctly handles 0.
(\:~#2|#\)@(#;.1~1,2~:/\])&.#:

#: - Take the binary representation.
1,2~:/\] - Between each digit, report True if they are different. Prepend a True so that the list has True at the start of each "run".
(#;.1~...) - Using the boolean vector above, take the length of each run.
\:~ - Sort these lengths from longest to shortest.
2|#\ - Take a list of alternating 1 0 1 0 ... as long as the list of lengths.
(...#...) - For each number on the left (sorted lengths), take as many of the corresponding item on the right (alternating 1's and 0's)
&. - Convert this new binary representation back to a number.

Examples:
   (\:~#2|#\)@(#;.1~1,2~:/\])&.#: 571
909
   i.21   NB. zero to twenty
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
   (\:~#2|#\)@(#;.1~1,2~:/\])&.#: every i.21   NB. apply separately to every number
1 1 2 3 6 5 6 7 14 13 10 13 12 13 14 15 30 29 26 25 26

Python 3, 146 136 bytes
import re;print(int(''.join(len(j)*'01'[i%2<1]for i,j in enumerate(sorted(re.findall('1+|0+',bin(int(input()))[2:]),key=len)[::-1])),2))

Rather than map with a lambda, would it be better to do ''.join(... for  ... in ...)?

Mathematica, 83 bytes
Flatten[0#+(d=1-d)&/@SortBy[d=0;Split[#~IntegerDigits~2],-Length@#&]]~FromDigits~2&

This defines an unnamed function.

Ruby, 107 104 102 bytes
(saved 3 bytes thanks to nimi)
Not going to beat the likes of CJam, but I got it pretty small for a sane language.
p gets.to_i.to_s(2).scan(/((.)\2*)/).map{|e|e[i=0].size}.sort.reverse.map{|e|"#{i=1-i}"*e}.join.to_i 2

A few bytes to save: (i+=1)%2 is i=1-i.

@nimi Ah, thank you. I was trying to figure out how to shorten that.

Java 8, 179 176 bytes
(x)->{int g[]=new int[32],h=0,i=highestOneBit(x);g[0]=1;while(i>1)g[((x&i)>0)^((x&(i>>=1))>0)?++h:h]++;sort(g);for(i=32,h=0;g[--i]>0;)while(g[i]-->0)h=h<<1|i%2;return x<1?1:h;}

I used two static imports: java.util.Integer.highestOneBit and java.util.Arrays.sort.
For readability, here's the code ungolfed:
java.util.function.ToIntFunction<Integer> f = (x) -> {
  int g[] = new int[32], h = 0, i = java.util.Integer.highestOneBit(x);
  g[0] = 1;
  while (i > 1) {
    g[((x & i) > 0) ^ ((x & (i >>= 1)) > 0) ? ++h : h]++;
  }
  java.util.Arrays.sort(g);
  for (i = 32, h = 0; g[--i] > 0;) {
    while (g[i]-- > 0) {
      h = h << 1 | i % 2;
    }
  }
  return x < 1 ? 1 : h; // handle zero
};

Husk, 11 bytes
ḋ`Ṙİ¬↔OmLgḋ

Try it online!

Japt, 14 bytes
¤ò¦ ñÊÔËîEvÃ¬Í

Try it
¤ò¦ ñÊÔËîEvÃ¬Í     :Implicit input of integer
¤                  :To binary string
 ò                 :Partition on
  ¦                :Inequality
    ñ              :Sort by
     Ê             :Length
      Ô            :Reverse
       Ë           :Map each D at 0-based index E
        î          :  Fill D with
         Ev        :  Parity of E
           Ã       :End map
            ¬      :Join
             Í     :To decimal

APL (Dyalog Extended), 32 30 bytes
⊥{⍵/(≢⍵)⍴⊤2}⊃¨∨{⍴¨⍵⊂⍨1,2≠/⍵}⊤⎕

Try it online!
-2 bytes for full program.
Explanation
⊥{⍵/(≢⍵)⍴⊤2}⊃¨∨{⍴¨⍵⊂⍨1,2≠/⍵}⊤⎕
                            ⊤⎕ convert input to binary
                       2≠/⍵    inequality of overlapping pairs
                     1,        prepend 1
                  ⍵⊂⍨          partition bits on that
                ⍴¨             get length of each part
              ∨                sort in descending order
            ⊃¨                 unenclose each
          ⊤2                   array [1,0]
    (≢⍵)⍴                      reshape to ⍵'s length
  ⍵/                           filter ⍵ by that(every other element)
⊥                              convert that back to binary

Jelly, 13 bytes
BŒgLÞṚJḂṁ"ƊFḄ

Try it online!
How it works
BŒgLÞṚJḂṁ"ƊFḄ - Main link. Takes n on the left
B             - Convert to binary
 Œg           - Group adjacent equal elements; Call this l
    Þ         - Sort by...
   L          -   length
     Ṛ        - Reverse, to put the longest first
          Ɗ   - Run the previous 3 commands over the sortedt list
      J       - Yield [1, 2, ..., len(l)]
       Ḃ      - Bit;  [1, 0, 1, 0, ..., len(l)%2]
         "    - Zip with l and do the following over each pair
        ṁ     -   Mould 1 or 0 to each element of l
           F  - Flatten
            Ḅ - Convert from binary

source: Stack Exchange

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

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

sort: votes


text:
Create a 'calculator interpreter'
Your task is to create an interpreter for a calculator. It has to parse commands like 5 + 5 and return the answer.
It has to be able to add, subtract, multiply, and divide. The interpreter only needs to accept two numbers (ex. 9 * 5 and 3 + 3)
The interpreter will take input from a console/whatever, not a file.
Eval isn't allowed

Examples:
Input: 5 * 5
Output: 25

Input: 8 / 2
Output: 4

Bonus
If you're really bored you can add these to the interpreter, if you'd like:
Simple mathematical functions like sqrt.
Make the interpreter be able to accept more than two numbers (ex. 55 + 55)

Only cursory check, but duplicate? http://codegolf.stackexchange.com/questions/568/basic-calculator If not, I think you should quantify the bonus.

I'd almost say this is a dupe of this challenge, but at the same time I feel that accepting only two numbers might make a difference. Either way, even if this isn't a dupe, the spec needs a bit more fleshing out: 1) Is eval allowed? 2) Can numbers be more than one digit?

What should 8 / 3 print?

Does the bonus have a byte value/% taken off the byte count?

By the way, we have a Sandbox where you can post challenge ideas to get feedback from communinity before "going live".

This challenge would of gotten much further by disallowing eval. Most languages have build-in support for calculations

@Dennis Thanks for the tip, I'll try it out next time I post something...

@Sp3000 Eval isn't allowed

@Dennis Response to your first comment: It should print 2.6, I guess

@Sp300 They don't have to be more than one digit, but you can add that if you're bored.

Perl, 10 8 chars
I hope this is not cheating ;)
8 chars (7 chars code + 1 for -p): Thanks to Dennis
perl -pe '$_=eval'

10 chars:
say eval<>

Takes input from STDIN and needs perl v5.10 and above.

JavaScript ES6, 10 4 bytes
Anonymous function.
eval

eval is already assignable (e.g., f=eval), so I think you can claim a 4 byte solution.

Couldn't this technically be zero bytes? Just say 'call the function with the name eval to get the answer', the same way you could normally say 'call the function f'.

Pyth, 1 byte
Q

For some reason, multiplication and division don't work in the online interpreter. The Python interpreter behaves as expected.

><>, 14 Bytes
Thanks @Sp3000 for saving 2 bytes
Quick, but kinda cool solution. Probably not an ideal golf, but utilizes an interesting feature of ><>.
<v ip02ii
n<,;

Receives input through the numerical interpretation of ascii characters (i.e. a is 97). It places the second character read (the operator) in the space after <v. Because dividing in ><> uses ,, not /, I make use of the fact that / reflects the pointer to accommodate for that case.
Alternate solution if that's invalid (+4 Bytes):
<v %cip02i%ci
n<,;

For this we just take mod 12 (c pushes 12) of the input since 0 is 48 and there are only 10 characters.
If , could be used in place of /, this would be a lot shorter (something like ii60pi n; or ic%ia0pic% n;)
Golf suggestions gladly welcome -- I'm rather tired right now.

I'm still not sure whether the OP intended to allow eval-like submissions, but in any case the last line can just be n<,;

MATLAB, 4 bytes  (or 0 bytes)
eval s

Pretty simple really. MATLAB will evaluate the string s you pass it, and voila. For example the following operators work:  * / + - ^ sqrt() min() max(). Well pretty much anything that you can think of.
Heck you can even print Hello World! if you want - eval 'disp(''Hello World!'')'.
To be honest given that MATLAB is already a calculator, you can call it 0 if you omit eval and simply type in the string:
>> 8/2
ans =
     4

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


text:
Avoid the steepest descent!
Background
A few months ago, the adventure of your life was just about to start. Now, in this precise moment (yeah, now), after months of suffering and hard work, you and a group of friends are standing on the top of the world. Yes, you are right, you are on the summit of Sagarmāthā.
However, things aren't going as well as you would like to. A dense fog has surrounded you and an incredibly bad-looking storm is coming as fast as it can. You didn't fix any rope on the way up, and your footprints have been covered in snow. If you want to survive (at least for today), you need to get out of there as fast as you can, but you MUST first find a way to know which face of the mountain is the one you should descend.
Luckily, you brought with you your sat phone which you modified before the trip so you are able to program and execute programs in it.
Challenge
You have been able to download to your phone the  map of the mountain in an ASCII-old-fashioned-unreadable-on-the-top-of-the-world way. Your task is to decide which face of the mountain presents the easiest descent so you can increase your chances of surviving. In order to do so, you have the brilliant idea to code a program on your phone that will tell which is the easiest way down. (Disclaimer: These activities have been done by professionals. No programmer was hurt during this narration. Please, do not try this at home.)
Maps are only made of the characters / and \ (plus spaces and newlines).
In any map, the summit of the mountain is always represented by
 /\
 \/

and from each of the sides (1,2,3 or 4) of the summit you will always find a "possible" way down the mountain.
1 /\ 2
3 \/ 4

The routes are always presented in the next way:
                      \
  Steep-> /          /
           /        / <-Flat
            /      \
      Flat-> \    \
              /  \ <-Steep
               /\
               \/

where each new character is either one place to the left/right of its predecessor. The meaning of each character is:

If the slash/backlash is parallel to its summit side -> counts as a 'steep' part.
If the slash/backslash is perpendicular to its summit side -> counts as a 'flat' part.

*For further reference see graphic above.
Note: The sides can have different lengths and the characters which constitute the summit also count as part of their side. In case of a draw, you can choose any of them.
Standard loopholes are disallowed.
Input
A string representing the map of the mountain or a plain text file containing the same info.
Either
C:\....\file.txt

or
                  \
      /          /
       /        /
        /      \
         \    \
          /  \
           /\
           \/
          \  /
         \    \
        \      \
       \        \
      /          /

as a string are valid inputs.
Output
As output, you should produce either a file in plain text or by stdout an ASCII profile representation of the side with the smallest average steepness using _ for flat parts and / for steep parts along with the average steepness of the side (number of "/")/(total chars).
Output example for map above:
       /
   ___/
  /
  AS:0.5

The format is not important as long as you have the profile and average steepness.
Scoring
What? Do you want a better reward than saving your and your friend's lives and being the first programmer who has ever programmed on the top of the world? Okay... this is code golf, so shortest program in bytes wins.
Test cases
Input:
                  \
      /          /
       /        /
        /      \
         \    \
          /  \
           /\
           \/
          \  /
         \    \
        \      \
       \        \
      /          /

Output:
       /
   ___/
  /
  AS=0.5

Input:
                  /
      \          /
       /        /
        \      /
         \    /
          /  /
           /\
           \/
          \  /
         \    \
        \      \
       \        \
      /          /
     /
    /

Output:
______/
AS=0.143 (1/7)

Input:
           /        \
            \      \
             /    /
              /  \
               /\
               \/
              \  /
             \    /
            \      /
           /        \

Output:
        /
       /
      /
    _/
    AS=0.8

Based on the examples, it looks like the profile shows the path in bottom to top direction if you read it from left to right? Seems somewhat unusual, since we're moving top to bottom, but no problem if it's clearly defined this way.

@RetoKoradi you are right. I don't know why I did it this way... You know, at that heigth its hard to keep your thoughts in order...

Should the output also include the number of the slope that is the least steep (1,2,3 or 4)? As it stands, you know one of them is definetly the winner but not which one.

are we to assume there could be an infinite amount of spaces before the shape?

*No programmer was hurt during this narration. * I care. +1

@Vic it is not strictly required to give the number of the winner slope (although if you want you can). For a valid entry the output must at least meet the requirements stated.

@torcado you can assume no infinite spaces will ever be found before a shape so you don't have to take this case into consideration.

I like that you used Sagarmāthā :)

Quite a challenging problem— kudos to you!

JavaScript (ES6), 303
Test running the snippet blow in an EcmaScript compliant browser - surely Firefox, probably Chrome. Using template strings, arrow functions.

// Golfed, no indentenation, all newlines are significant

f=s=>(s=`
${s}
`.split`
`,s.map((r,i)=>~(q=r.search(/\/\\/))&&(y=i,x=q),x=y=0),z=[],[0,2,0,2].map((d,i)=>{t=x+i%2,u=y+i/2|0,b=s[u][t];for(p=[''],n=l=0;(c=s[u][t])>' ';++l,t+=d-1,u+=(i&2)-1)c==b?p.push(p[n++].replace(/./g,' ',w='/')):w='_',p=p.map((r,i)=>(i<n?' ':w)+r);z=z[0]<(p[0]=n/l)?z:p}),z.join`
`)

// Less golfed

U=s=>(
  s=(`\n${s}\n`).split`\n`,
  x = y = 0,
  s.map((r,i)=>~(q=r.search(/\/\\/))&&(y=i,x=q)),
  z=[],
  [0,2,0,2].map((d,i) => {
    t = x+i%2,
    u = y+i/2|0,
    b = s[u][t];
    for(p=[''], n=l=0; (c=s[u][t])>' '; ++l, t += d-1, u +=(i&2)-1)
      c == b
        ? p.push(p[n++].replace(/./g,' ',w='/'))
        : w='_',
      p = p.map((r,i) => (i<n?' ':w)+r);
    z = z[0]<(p[0]=n/l)?z:p
  }),
  z.join`\n`
)

// TEST
// redirect console into the snippet body
console.log=x=>O.innerHTML+=x+'\n'

maps=[ // as javascript string literals, each baskslasch has to be repeated
`                  \\
      /          /
       /        /
        /      \\
         \\    \\
          /  \\
           /\\
           \\/
          \\  /
         \\    \\
        \\      \\
       \\        \\
      /          /`,
`                  /
      \\          /
       /        /
        \\      /
         \\    /
          /  /
           /\\
           \\/
          \\  /
         \\    \\
        \\      \\
       \\        \\
      /          /
     /
    / `,
`           /        \\
            \\      \\
             /    /
              /  \\
               /\\
               \\/
              \\  /
             \\    /
            \\      /
           /        \\`]

maps.forEach(m=>console.log(m + '\n'+ f(m) +'\n'))


text:
King of the Hill - Firefighters
It is a dry summer in the prairie. The four farmers in the area realize that they can corner the market on corn by burning their neighbors crops. But they need a strategy for doing so; that is where you come in.
Your task is to write a bot to tell the farmers what to burn. The goal is to finish the game with the largest area of unburnt land.  The playing field is a 32x32 grid. Each cell may be one of the following:
.  - Ground
@  - A bot
#  - Ash
W  - Wet ground
1,2,3,4,5, or 6  - Fire
Fire grows in intensity by 1 each turn. Once it is 3 or higher, it will set cells next to it (horizontally or vertically) on fire. After fire hits 6, it turns into ash.
On each turn, bots receive as STDIN the following: bot starting x, bot starting y, bot current x position, bot current y position, and the board, separated by newlines. An example:
8
22
6
24
................................
................................
................................
.....................1..........
....................1#1.........
...................1#363........
....................16@1........
.....................31.........
................................
.........1.1....................
........15#62...................
........15@2....................
.........32.....................
................................
................................
................................
................................
................................
................................
................................
................................
................................
....4.1.........................
.....1#3........................
.....@3.........................
.....W..........................
................................
................................
................................
................................
................................
................................

(in this instance you are the bot in the bottom left).
You must output three characters, with an optional newline, representing the following:
Move - one of L, R, U, D, or S (stay)
Action - one of B (burn), P (pour water) or X (do nothing)
Direction - one of L, R, U, D or S - controls which cell you perform the action on
Fire does not affect bots.
Turn order is as follows: All bots move; all bots perform actions; then environmental rules happen.
If you pour water on the ground, it will be wet (W) for one turn. Fire will not spread to wet ground. If you pour water on wet ground, it will continue to be wet. If you pour water on fire, it turns back to regular ground. You cannot do anything to ash.
Rounds are run with 4 bots at a time. The round ends after 50 turns, or when one bot runs out of unburnt ground, whichever comes first. Your score is calculated as the number of ground or wet ground cells in the 9x9 square centered on where your bot started.
Here is an example bot; it picks all three letters randomly and generally ends up burning down its own fields.
RandomBurner:
#!/usr/bin/env python
import random
print random.choice('LRUDS')+random.choice('BPX')+random.choice('LRUDS')

Rules:

No filesystem access outside of your own folder.
You may write to files if you need to store persistent data between turns, but only up to a maximum of 1kb per bot
You may not overwrite anybody else's bot
If you output an invalid move, your bot will sit still. If you output an invalid action, your bot will do nothing.
Please stick to common languages that can be run on a OSX or Linux box.

Controller code can be found here.
Initial results:
Average of 15 rounds:
---------------------
81 Farmer
56 CautiousBot
42 GetOff
41 Visigoth
40 DontBurnMeBro
37 FireFighter
35 Pyro
11 Protector

Update: Added Farmer, CautiousBot, GetOff, FireFighter, and Pyro.

The board doesn't wrap around at the edges, right?

Right. If you try to move past the edge, you just stand still.

I understand Move and Action, but what does Direction do?

@recursive Direction is where you do the action. E.g. if you do SBR, you stay where you are and burn the cell to the right of you.

I don't understand one detail.  What land is mine and what is yours?

Your land is what was inside the 9x9 block area centered on where you started. All bots start the round at least 8 blocks from each other, so there is no overlap.

How do you tell the type of land under the bots?

It's not provided. If you want to record it somehow, that is an option. Sitting on a fire to hide it is a valid strategy.

If your land is a 9 by 9 square, does the bot you control in the example have less land to start with than the others?

No, because it's centered on your bot; four spaces in each direction.

Whoops, thought you meant 9 in each direction. Thanks.

Is a PHP answer acceptable?

Does fire stop propagating at some point? Or the chain reaction of setting fire to adjacent cells goes on forever?

@Andrew, PHP is fine as long as it can be run from the command line.  The chain reaction continues until the round ends (unless stopped by water or ash).

I tried running the controller code but I got some weird output. The bot is outputting UBR (move up, burn right). It goes straight down as expected but the fire doesn't spread to the left until it reaches the bottom. I took a quick look at the code but couldn't see what is causing this. Is there a reason for it?

In the example, shouldn't the current position be (5,24)?

@Andrew Indeed. There was a bug in the controller which I fixed before I ran the last rounds, but forgot to update here - should be fixed now.

@Skyler I'm having a little trouble getting the controller to work, every character is just standing still. Can you clarify how to run it/ what the file structure is? Thank you

Sure, the file structure is firefighters.py and bots/, with all the bots in bots/. Run with python firefighters.py bot1name bot2name bot3name bot4name.

Would an answer written in Felix be OK? It runs well on Linux...

@kirbyfan64sos Should be fine. I'd just need to update Java on my Linux box, because Protector doesn't run on anything below 1.8.

What is the format of the tournament?

I am currently running bots in matches of 4, such that every bot is in a match with every other bot at least three times. The total score for a bot is the average of its score over all rounds it played in.

BTW, your controller code has some bugs in the environmental effects section, specifically in managing the spread of fire. Spreading fire can overwrite more intense fires, and sometimes fires just get stuck at 5. I rewrote some of the controller code in python3 for my personal testing, let me know if you'd like it.

Yes, I would be interested in that.

link. I changed it to run on python3, be compatible with windows, and added builtin tournament if called with no parameters.

Visigoth
Visigoth tries to burn its enemies to the ground. It hopes to do this before anyone else gets to its land.
Run: python visigoth.py
#!/usr/bin/python

''' Charge the enemy and burn them to the ground. '''

import sys

data = sys.stdin.readlines()

startx, starty, x, y = [int(i) for i in data[0:4]]
field = [list(i) for i in data[4:]]

otherbots = []
for i in range(32):
    for j in range(32):
        if field[i][j]=='@': #bot
            if i!=y and j!=x:
                otherbots.append([j,i])

min_bot = otherbots[0]
for bot in otherbots:
    if abs(bot[0]-x)+abs(bot[1]-y) < abs(min_bot[0]-x)+abs(min_bot[1]-y):
        min_bot = bot

dx = min_bot[0]-x
dy = min_bot[1]-y

if abs(dy)>abs(dx):
    if dy>0:
        move = 'U'
    else:
        move = 'D'
else:
    if dx>0:
        move = 'R'
    elif dx<0:
        move = 'L'
    else:
        move = 'S'

if max(abs(x-startx), abs(y-starty))>4:
    if 0<x<31 and 0<y<31:
        dirs = {'U':(-1,0), 'D':(1,0), 'L':(0,-1), 'R':(0,1)}
        for i in dirs:
            if field[dirs[i][0]][dirs[i][1]] in ('.', 'W'):
                action = 'B'+i
                break
        else:
            # No free land nearby, go out in a blaze of glory
            action = 'BS'
    else:
        action = 'BS'
else:
    # Don't set own field on fire
    action = 'XS'

print move+action

This is my first entry, constructive criticism is appreciated!

"Fire does not affect bots"

Visigoth seems to rarely burn anything.

Oh, just noticed I had min where I should have had max. I fixed it.

@CᴏɴᴏʀO'Bʀɪᴇɴ It's not actually trying to burn the enemy bots, just assuming they will stay near their own base. It would be very weak against itself.

Oh, I see. That makes more sense.

Java, Protector
Attempts to surround his field with a fence of ash.
Edit: Improved logic a bit. Probably won't make a difference.
import java.awt.Point;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

/**
 * Created 10/6/15
 *
 * @author TheNumberOne
 */
public class Protecter {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Point start = new Point(in.nextInt(), in.nextInt());
        Point current = new Point(in.nextInt(), in.nextInt());
        in.nextLine();
        String output = "";
        char[][] board = new char[32][];
        for (int i = 0; i < 32; i++){
            board[i] = in.nextLine().toCharArray();
        }
        List<Point> danger = new ArrayList<>();
        List<Point> close = new ArrayList<>();
        List<Point> closeDanger = new ArrayList<>();
        List<Point> fence = new ArrayList<>();
        for (int i = 0; i < 32; i++){
            for (int j = 0; j < 32; j++){
                Point p = new Point(i, j);
                char c = board[j][i];
                if (Math.abs(p.x - start.x) < 10 && Math.abs(p.y - start.y) < 10){
                    if ((c + "").matches("\\d")){
                        danger.add(p);
                    }
                }
                if (distance(current, p) == 1){
                    close.add(p);
                }
                if ((Math.abs(p.x - start.x) == 10 || Math.abs(p.y - start.y) == 10) && !(c + "").matches("#|\\d|@")){
                    fence.add(p);
                }
            }
        }
        closeDanger = new ArrayList<>(danger);
        closeDanger.retainAll(close);
        danger.sort(Comparator.comparingInt(a -> distance(current, a) / (board[a.y][a.x] - '0')));
        if (danger.size() > 0){
            output += moveTo(current, danger.get(0));
        } else {
            fence.sort(Comparator.comparingInt(a -> distance(current, a)));
            if (fence.size() == 0){
                output += "S";
            } else {
                output += moveTo(current, fence.get(0));
            }
        }
        closeDanger.sort(Comparator.comparingInt(a -> board[a.y][a.x] - '0'));
        if (closeDanger.size() > 0){
            output += "P";
            output += moveTo(current, closeDanger.get(0));
        } else {
            if (danger.size() == 0) {
                List<Point> closeFence = new ArrayList<>(fence);
                closeFence.retainAll(close);
                if (closeFence.size() > 0) {
                    output += "B";
                    output += moveTo(current, closeFence.get(0));
                } else {
                    if (!fence.contains(current)){
                        output += "PS";
                    } else {
                        output += "BS";
                    }
                }
            } else {
                if (!fence.contains(current)){
                    output += "PS";
                } else {
                    output += "BS";
                }
            }
        }
        System.out.println(output);
    }

    private static String moveTo(Point from, Point to) {
        if (from.x > to.x){
            return "L";
        }
        if (from.x < to.x){
            return "R";
        }
        if (from.y > to.y){
            return "U";
        }
        if (from.y < to.y){
            return "D";
        }
        return "S";
    }

    private static int distance(Point p1, Point p2){
        return Math.abs(p1.x - p2.x) + Math.abs(p2.y - p1.y);
    }

}

Place in a file named Protector.java.
Compile with: javac Protector.java
Run with: java Protector

First, had to rename to Protecter.java to get it compiled. But, when I run it, it throws a java.lang.ArrayIndexOutOfBoundsException at line 29.

@Skyler fixed it :)

Thanks, I added it to the results. Protector doesn't always manage to put out the fires he starts.

Kind of relevant ;)

@Fatalize That was what I was taught to do if I was caught in a forest/desert fire :)

DontBurnMeBro
Another Python entry. Guaranteed not to be the first to die (I think).
#!/usr/bin/python

print "SPS"

Based on the spec pouring water is P not W.

Pyro, python
Pyro likes fire. Pyro loves fire. Pyro lives in fire. I'm thinking "Pyro from TF2". Pyro likes to burn things. He won't burn his own territory, but he will try to get out of it, using a simple "pathfinding" algorithm.
import sys
import random
inpu          = sys.stdin.readlines()
ox,oy,x,y     = [int(i) for i in inpu[0:4]]
board         = [list(i) for i in inpu[4:]]
adjacentcells = [[[board[y+b][x+c],b,c] for b in range(-1,2)] for c in range(-1,2)]
action        = ""
infield=max(abs(ox-x),abs(oy-y))<=9
# let's find out what Pyro will do!
if not infield: # Pyro won't burn what's in his field.
    for row in adjacentcells:
        for entry in row:
            cell,a,b=entry
            if(a!=b):   # Can't act on these cells.
                if cell==".":   # burn it!!!!!!
                    action = "B"
                    if(a==0):
                        direction = {-1:"L",1:"R"}[b]
                    else:
                        direction = {-1:"D",1:"U"}[a]
            if action: break;
        if action: break;
    # Pyro doesn't care where he goes, so long as
    # Pyro's not in the field of Pyro.
    move = random.choice("LRUDS")
else:   # Thought Pyro hates water, Pyro must protect SOMETHING.
    action    = "P"
    direction = "S"
    # get the direction towards the center
    # Pyro will move away from ox and oy to
    # towards the center, if in the field.
    # Pyro will do this by first going right/left,
    # then going up/down. (This behaviour is
    # removed when he leaves his field.)
    cx = cy = 16
    while max(abs(cx-x),abs(cy-y))<=9:
        cx = random.randint(0,31)
        cy = random.randint(0,31)
    if(cx-x>0): #is to the left of the center
        move = "R"
    elif(cx-x<0): #is to the right of the cenetr
        move = "L"
    elif(cy-y>0): # is above center
        move = "D"
    elif(cy-y<0): # is below center
        move = "U"
    else:   # is at center (something went wrong!)
        move   = "S"
        action = "B"
if not move:
    move = "S"
if not action:
    action = "B"
if not direction:
    direction = "S"
print(move+action+direction)

""" Here, have a face!
MMMMMMMMMMMMMMMMMMMMMMMdyo/:-.````.:+sdMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMNs/....----...``````.omMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMh/``..-://+//:-..````````/mMMMMMMMMMMM
MMMMMMMMMMMMMMMm:````..-:////:--..``````````sMMMMMMMMMM
MMMMMMMMMMMMMMs```````....--....`````````````/NMMMMMMMM
MMMMMMMMMMMMM/````````````````````````````````:NMMMMMMM
MMMMMMMMMMMM/```......``````````````````.......+mMMMMMM
MMMMMMMMMMMo.:::::::::::-````````````.-:::::::::/+yNMMM
MMMMMMMMMNs:-..-------::::.`````````://:-------..-:/hMM
MMMMMMMMm+:..---:::::---:::.```````::::---:::::--.`-/sM
MMMMMMMN+:`.---:::/:/:---:::``````.:::.--:::/:/:--.`:/h
MMMMMMMh:-`---://o+///:---::.`````-::---://oo///:--..:+
MMMMMMMs:..--:/+/sss+//:-.::.`````-::.-://+osyo//:-.-::
MMMMMMMs:----///+sosso/:--::``````.::.-://+oosso+:-.::/
MMMMMMMd:::-:/++/osyso+/--::```````::-://+/osyso+/--::s
MMMMMMMMs:/::::+ooos+o+/:::.```````.::::/+ooos/o+/:/:+N
MMMMMMMMMs://:+osooo+o+/::.``.....``.:/:/osoos+o+//:+mM
MMMMMMMMMM--:/++ysyoo+/:-...........`.-:/+ssso++/:-yNMM
MMMMMMMMMMs``.-:://::-..`.....---....``..--::::-.`.MMMM
MNNMddhyys+-.```````````...--:::::-...````````````+MMMM
////.-:///:-..``````````.:///++o/o+/:/.```````````yMMMM
---.`.-:::--..`````````..+//+ooo+++///.```````````mMMMM
/.--``..--...``````````..--:/+oo+/:--..``````````.MMMMM
s --.```...````````````...--/+++++/-...````````.`/MMMMM
d .--```````````````````...-::::::-...````````.-/+MMMMM
M.`--`  ````````````````....------....````````.-/.dMMMM
M+ .-.  `````````````````.:::::::::::.`````````.-sMMMMM
Mm``--`  ``````````````-://///////////:-````````/MMMMMM
MM: --.  ````````````.://::--......-::///-``````yMMMMMM
MMd`.-.  ``````````.:/::-..-:::::::.``-::::.````NMMMMMM
MMM+.--`  `````````:::-.-::-.......-::-`--::```+MMMMMMM
MMMN---`  ````````.--..:-.```````````..-`.--.``dMMMMMMM
MMMMd--.` `````..`.-.`-````````````````.-`...`/MMMMMMMM
MMMMMNh+ss/oydNMd``.`.`````````````````````.`.NMMMMMMMM
MMMMMMMMMMMMMMMMMd.``.```````````````````````dMMMMMMMMM
MMMMMMMMMMMMMMMMMMm:```````````````````````-dMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMy.```````````````````.oNMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMNs-```````````````:sNMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMmy+:-.````.:+ymMMMMMMMMMMMMMMMM
"""

Not enough ambiguity as to the Pyro's gender in your description and comments.

@Cole Oh darn. I forgot about that quirk. I'll edit in some ambiguity, for sure ;)

Doesn't run, because there is nothing after the else statement in line 21.

Now breaks at line 5 ('data' is not defined)

@Skyler Fixed again. I'm so sorry. I did this without my python interpreter.

Line 6: name 'a' is not defined

@Skyler I fixed it, looked over the code. There should be no more errors.

Let us continue this discussion in chat.

GetOff, Python
GetOff just wants to keep his land for himself, and he's not afraid to chase those damn bots all over his land, squirting them with his water gun until they leave. While its property is not being violated, it makes tries its best to make sure his land doesn't get burned.
#!/usr/bin/env python

import sys

fire = ['1','2','3','4','5','6']

move = ''
ad = ''

data = sys.stdin.readlines()

startx, starty, x, y = [int(i) for i in data[0:4]]
board = [list(i) for i in data[4:]]

top = starty-4
bottom = starty+5
right = startx+5
left = startx-4

bots = []
for i in range(32):
    for j in range(32):
        if board[i][j]=='@':
            if i != y and j != x:
                bots.append([j,i])

fires = []
for i in range(32):
    for j in range(32):
        if board[i][j] in fire: #fire
            fires.append([j,i])

for bot in bots:
    if left < bot[0] < right and top < bot[1] < bottom: # if there's a bot in the field
        if bot[0] > x:
            move = 'R'
        elif bot[0] < x:
            move = 'L'
        elif bot[1] > y:
            move = 'D'
        elif bot[1] < y:
            move = 'U'
        else:
            move = 'S'
    else:
        nearest_fire = []
        for f in fires:
            if left < f[0] < right and top < f[1] < bottom:
                if nearest_fire == []:
                    nearest_fire = f
                elif (f[0]-x)+(f[1]-y) < (nearest_fire[0]-x)+(nearest_fire[1]-y):
                    nearest_fire = f
        if nearest_fire == []:
            move = 'S'
        else:
            if nearest_fire[0] > x:
                move = 'R'
            elif nearest_fire[0] < x:
                move = 'L'
            elif nearest_fire[1] > y:
                move = 'D'
            elif nearest_fire[1] < y:
                move = 'U'
            else:
                move = 'S'

if board[x-1][y] in fire: # position immediately to the left
    ad = 'L'
elif board[x+1][y] in fire: # position immediately to the right
    ad = 'R'
elif board[x][y-1] in fire: # position immediately up
    ad = 'U'
elif board[x][y+1] in fire: # position immediately down
    ad = 'D'
else:
    ad = 'S'

print(move+'P'+ad)

Does the a < b < c syntax work in Python? I thought that evaluates to (a < b) < c, which is either 1 < c or 0 < c. Correct me if I am wrong. (Found in first conditional of bot loop.)

It's always worked for me, but I'm not sure if it does in every version of python...

@CᴏɴᴏʀO'Bʀɪᴇɴ believe it does, 1<3>2 evaluates to True on my machine (if it were to group them it would return false: 1>2 and 1<1 are the possibilities).

@Cole Thanks. I was in JavaScript-thinking mode. Just tried it out on repl.it. More reasons why Python is beautiful.

Farmer, Java
The farmer only cares about his crops. He constantly watches his field for possible fires or invaders.
import java.awt.Point;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

public class Farmer {

    public static void main(String[] args) {
        //row == y
        //col == x
        Scanner in = new Scanner(System.in);
        Point start = new Point(in.nextInt(), in.nextInt());
        Point current = new Point(in.nextInt(), in.nextInt());
        in.nextLine();
        char[][] board = new char[32][];
        for (int row = 0; row < 32; row++){
            board[row] = in.nextLine().toCharArray();
        }
        final List<Point> firesInField = new ArrayList<>();
        final List<Point> enemiesInField = new ArrayList<>();
        for (int row = 0; row < 32; row++) {
            for (int col = 0; col < 32; col++) {
                Point p = new Point(col, row);
                if (!isInField(start, p))
                    continue;
                char c = board[row][col];
                if (isFire(c)) {
                    firesInField.add(p);
                } else if (c == '@' && col != current.x && row != current.y) {
                    enemiesInField.add(p);
                }
            }
        }
        List<Point> destinations = firesInField.size() > 0 ? firesInField : enemiesInField;

        if (destinations.size() > 0) {
            //take short paths to eliminate more fires
            destinations.sort(Comparator
                    .comparingInt((Point p) -> distance(p, current))
                    .thenComparingInt(p -> -1 * (board[p.y][p.x] - '0')));
            Point dest = destinations.get(0);
            print(moveTo(current, dest), "P", moveTo(current, dest));
        }

        //TODO start fires if an enemy has more intact ground

        //walk back to center
        print(moveTo(current, start), "P", moveTo(current, start));
    }

    private static void print(String move, String action, String actionMove) {
        System.out.println(move + action + actionMove);
        System.exit(0);
    }

    private static boolean isInField(Point centerOfField, Point toTest) {
        //add one extra, to prevent fires that are very near
        return distance(centerOfField, toTest) <= 10 && Math.abs(centerOfField.x - toTest.x) <= 5 && Math.abs(centerOfField.y - toTest.y) <= 5;
    }

    private static boolean isFire(char c) {
        return c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6';
    }

    private static String moveTo(Point from, Point to) {
        if (from.x > to.x){
            from.x--;
            return "L";
        }
        if (from.x < to.x){
            from.x++;
            return "R";
        }
        if (from.y > to.y){
            from.y--;
            return "U";
        }
        if (from.y < to.y){
            from.y++;
            return "D";
        }
        return "S";
    }

    private static int distance(Point p1, Point p2){
        return Math.abs(p1.x - p2.x) + Math.abs(p2.y - p1.y);
    }
}

Small improvement, in  isFire you could use Character.isDigit instead.

FireFighter, Java
Fights all fires.
import java.awt.Point;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

/**
 * Created 10/7/15
 *
 * @author TheNumberOne
 */
public class FireFighter {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Point start = new Point(in.nextInt(), in.nextInt());
        Point current = new Point(in.nextInt(), in.nextInt());
        in.nextLine();
        String output = "";
        char[][] board = new char[32][];
        for (int i = 0; i < 32; i++) {
            board[i] = in.nextLine().toCharArray();
        }

        List<Point> danger = new ArrayList<>();
        List<Point> close = new ArrayList<>();
        List<Point> closeDanger;
        for (int i = 0; i < 32; i++){
            for (int j = 0; j < 32; j++){
                Point p = new Point(i, j);
                char c = board[j][i];
                if ((c + "").matches("\\d")){
                    danger.add(p);
                }
                if (distance(current, p) == 1){
                    close.add(p);
                }
            }
        }
        closeDanger = new ArrayList<>(danger);
        closeDanger.retainAll(close);

        Comparator<Point> comparator = Comparator.comparingInt((Point a) -> board[a.y][a.x]).reversed();

        danger.sort(comparator);
        danger.sort(Comparator.comparingInt(a -> distance(start, a)));
        if (danger.size() > 0){
            output += moveTo(current, danger.get(0));
        } else {
            output += moveTo(current, start);
        }
        closeDanger.sort(comparator);
        if (closeDanger.size() > 0){
            output += "P" + moveTo(current, closeDanger.get(0));
        } else {
            output += "PS";
        }
        System.out.println(output);
    }

    private static String moveTo(Point from, Point to) {
        if (from.x > to.x){
            return "L";
        }
        if (from.x < to.x){
            return "R";
        }
        if (from.y > to.y){
            return "U";
        }
        if (from.y < to.y){
            return "D";
        }
        return "S";
    }

    private static int distance(Point p1, Point p2){
        return Math.abs(p1.x - p2.x) + Math.abs(p2.y - p1.y);
    }

}

Keeper, Python 2
import sys

Out = ["S", "P", "S"]

StX = int(sys.stdin.readline()) - 1
StY = int(sys.stdin.readline()) - 1
NowX = int(sys.stdin.readline()) - 1
NowY = int(sys.stdin.readline()) - 1
Map = []
for i in range(32):
    Map.append(sys.stdin.readline())

Pos = [NowX, NowY]
Area = [[StX, StY]]
for x in range(StX-4, StX+4):
    for y in range(StY-4, StY+4):
        Area.append([x, y])

Fires = []
for y in range(32):
    for x in range(32):
        if Map[y][x] in "123456":
            Fires.append([x, y])

Danger = []
for Tile in Area:
    if Map[Tile[1]][Tile[0]] in "123456":
        Danger.append(Tile)

Distance = {}
i = -1
for Fire in Danger:
    i += 1
    Distance[(Pos[0] - Fire[0], Pos[1] - Fire[1])] = i

i = min(Distance)
Closest = Danger[Distance[i]]

if Closest[0] > Pos[0]:
    Out[0] = Out[2] = "R"
    Pos[0] += 1
if Closest[0] < Pos[0]:
    Out[0] = Out[2] = "L"
    Pos[0] -= 1
if Closest[0] == Pos[0]:
    if Closest[1] > Pos[1]:
        Out[0] = Out[2] = "D"
        Pos[1] += 1
    if Closest[1] < Pos[1]:
        Out[0] = Out[2] = "U"
        Pos[1] -= 1

if Closest[0] + 1 == Pos[0] and Closest[1] == Pos[1]:
    Out[2] = "L"
if Closest[0] - 1 == Pos[0] and Closest[1] == Pos[1]:
    Out[2] = "R"
if Closest[1] + 1 == Pos[1] and Closest[0] == Pos[0]:
    Out[2] = "U"
if Closest[1] - 1 == Pos[1] and Closest[0] == Pos[0]:
    Out[2] = "D"
if Closest[0] == Pos[0] and Closest[1] == Pos[1]:
    Out[2] = "S"

print "".join(Out)

Could be simplified, but I'm tired.
The Keeper tries to keep its field from harm. If a fire appears, it hurries over to it and puts it out as fast as it can.
I may add accommodation for incoming fires as well.

Line 36: ValueError: min() arg is an empty sequence - it throws errors if nothing is on fire yet.

@Skyler I'll fix in a bit, sorry.

Just an idea; shouldn't 4/5/6s be prioritised over 1/2/3s, or am I being dumb.

CautiousBot, Node.js (ES5)
This bot goes out and tries to set fire to other bots' land. It even sits on top of the fire for 3 ticks to hide it! However, one can never be too cautious, so it always makes sure it is close enough to put out any fires on its own land.
Notes:

Uses a state file called state.json stored in its working directory, used to store information about other bots' initial positions and to determine how long to hide a started fire. This must be deleted once the round is over (eg, when some bot has won). Otherwise the bot will be confused on the next round. (Let me know if this breaks rules.)
Requires the split module.

#!/usr/bin/env node

// imports
var fs       = require("fs");
var splitmod = require("split");

// variables
var startX, startY, currentX, currentY, board = [], state = {};
var DEBUG = false;

// utility functions
function debug(){
    if(DEBUG) console.log.apply(console, arguments);
}

// calculates manhattan distance which is also the number of turns it will take to get somewhere
function manhattan(x1, y1, x2, y2){
    return Math.abs(x2 - x1) + Math.abs(y2 - y1);
}

// calculates chebyshev distance (mostly used for determining if a bot is within someone's plot)
function chebyshev(x1, y1, x2, y2){
    return Math.max(Math.abs(x2 - x1), Math.abs(y2 - y1));
}

// gets the board character at x, y
function get(x, y){
    return board[y][x];
}

function readState(){
    try {
        state = JSON.parse(fs.readFileSync('state.json').toString());
        debug("Opened state file");
    } catch(e){
        // it must be the first turn
        createState();
    }
}

function writeState(){
    fs.writeFileSync('state.json', JSON.stringify(state));
    debug("Wrote state file");
}

// finds out where all the other bots are
function getBotPositions(){
    var positions = [];
    for(var x = 0; x < 32; x++){
        for(var y = 0; y < 32; y++){
            if(get(x, y) == '@' && x != currentX && y != currentY){
                positions.push({x: x, y: y});
            }
        }
    }
    return positions;
}

function createState(){
    debug("Creating state");
    // take a loot at where other bots are to record their land locations
    var botLands = getBotPositions();
    state['botLands'] = botLands;

    state['turn'] = 0; // which turn is it?
    state['lastFireTurn'] = -999; // which turn was the last one where this bot set a fire?
}

// finds whether a plot of land (defined by its center) has fire on it
function isLandBurning(x, y){
    for(var dx = -4; dx < 5; dx++){
        for(var dy = -4; dy < 5; dy++){
            if(get(x + dx, y + dy).match(/[1-6]/) != null) return true;
        }
    }
    return false;
}

// finds the fire with the highest number (and therefore the one to put out first)
function findFire(x, y){
    var highestNum = 0;
    var fire = {x: x, y: y};
    for(var dx = -4; dx < 5; dx++){
        for(var dy = -4; dy < 5; dy++){
            if(get(x + dx, y + dy).match(/[1-6]/) != null){
                var num = parseInt(get(x + dx, y + dy));
                if(num > highestNum){
                    highestNum = num;
                    fire = {x: x + dx, y: y + dy};
                }
            }
        }
    }
    return fire;
}

// figures out where to go to get somewhere
function getDirection(x1, y1, x2, y2){
    var direction = 'S';
    var cycx = Math.abs(y2 - y1) / Math.abs(x2 - x1);

    if(cycx < 1){
        if(x2 > x1) direction = 'R';
        if(x2 < x1) direction = 'L';
    } else {
        if(y2 > y1) direction = 'D';
        if(y2 < y1) direction = 'U';
    }

    debug("Getting direction", x1, y1, x2, y2, "result", direction);

    return direction;
}

// read input
var dataCycle = 0;
process.stdin.pipe(splitmod()).on('data', function(line){
    switch(dataCycle){
    case 0:
        startX = parseInt(line);
        break;
    case 1:
        startY = parseInt(line);
        break;
    case 2:
        currentX = parseInt(line);
        break;
    case 3:
        currentY = parseInt(line);
        break;
    default:
        board.push(line);
    }

    dataCycle++;
}).on('end', function(){
    // main bot code
    readState();
    state['turn']++;
    debug("It is turn", state['turn']);

    // get bot positions
    var botPositions = getBotPositions();

    var action = {type:'X', direction:'S'};
    var move   = 'S';

    var isMyLandBurning = isLandBurning(startX, startY);
    if(isMyLandBurning){ // hurry over there ASAP!
        debug("Bot land is burning!");
        var pos = findFire(startX, startY);
        debug("Fire found at", pos);
        move = getDirection(currentX, currentY, pos.x, pos.y);
        // simulate the move and figure out if/where to dump the water
        var newX = currentX + (move == 'R') - (move == 'L');
        var newY = currentY + (move == 'D') - (move == 'U');
        if(chebyshev(newX, newY, pos.x, pos.y) < 5){
            // on its own land, start dropping water like a madman
            debug("Dropping water");
            action.type = 'P';

            // if it can put out the target fire, then do that
            if(manhattan(newX, newY, pos.x, pos.y) == 1) action.direction = getDirection(newX, newY, pos.x, pos.y);
            // it's not in range of the target fire, so use the time to put out other fires
            // if it's moving on top of a fire, put that out
            else if(get(newX, newY).match(/[1-6]/) != null) action.direction = 'S';
            // if there's a fire around it then put that out
            else if(get(newX + 1, newY).match(/[1-6]/) != null) action.direction = 'R';
            else if(get(newX - 1, newY).match(/[1-6]/) != null) action.direction = 'L';
            else if(get(newX, newY + 1).match(/[1-6]/) != null) action.direction = 'D';
            else if(get(newX, newY - 1).match(/[1-6]/) != null) action.direction = 'U';
            else action.direction = 'S';
        }
    } else {
        // are there any bots that could start a fire when this bot is 6+ tiles away?
        var headBack = false;
        for(var i = 0; i < botPositions.length; i++){
            var otherBot = botPositions[i];
            var dist = manhattan(otherBot.x, otherBot.y, startX, startY) - 4;
            var myDist = manhattan(currentX, currentY, startX, startY);
            if(dist + 6 < myDist){
                headBack = true;
                break;
            }
        }
        if(headBack){ // they're probably up to no good
            debug("Bots are dangerously close, heading back");
            move = getDirection(currentX, currentY, startX, startY);
        } else if(state['turn'] - state['lastFireTurn'] < 3) { // no bots near own plot, time to consider other options
            debug("Hiding fire");
            // sneakily hide the fire if one was set :)
        } else { // last option is to go find land to burn
            debug("Finding land to burn");
            var closestX = 999, closestY = 999;
            for(var i = 0; i < state.botLands.length; i++){
                var otherLand = state.botLands[i];
                if(!isLandBurning(otherLand.x, otherLand.y) && chebyshev(currentX, currentY, otherLand.x, otherLand.y) > 4){ // find someone to burn
                    // use [-3, 3] here because on the first turn, the bots could have moved before this bot had a chance to see them
                    // meaning that the [-3, 3] region is the only one that is guaranteed to be on their land
                    for(var dx = -3; dx < 4; dx++){
                        for(var dy = -3; dy < 4; dy++){
                            var type = get(otherLand.x + dx, otherLand.y + dy);
                            var distThere = manhattan(currentX, currentY, otherLand.x + dx, otherLand.y + dy);
                            var distShortest = manhattan(currentX, currentY, closestX, closestY);
                            // find normal land, or wet land that will dry by the time the bot gets to it
                            if((type == '.' || type == '@' || (type == 'W' && distThere > 1)) && distThere < distShortest){
                                closestX = otherLand.x + dx;
                                closestY = otherLand.y + dy;
                            }
                        }
                    }
                }
            }
            if(closestX != 999 && closestY != 999){ // land found; go there
                debug("Target acquired", closestX, closestY);
                debug("Burning land");
                move = getDirection(currentX, currentY, closestX, closestY);
                if(move == 'S'){ // is it on the land? If so, then burn it
                    action.type = 'B';
                    action.direction = 'S';
                    state['lastFireTurn'] = state['turn']; // record when the fire was set
                }
            } else { // everyone else's land already has a fire
                debug("Default action");
                // default to heading back; one can never be too safe!
                move = getDirection(currentX, currentY, startX, startY);
            }
        }
    }

    // save the state file
    writeState();
    // output the action
    console.log(move + action.type + action.direction);
});

It throws an error at line 340: Error: Cannot find module 'split'. I am using Node.js v0.10.30.

cd botdir npm install split for some reason node doesn't like it installed globally for me but you could try that too


text:
Self-validating quine
Quines have been around forever.  It's a fun challenge: write a program that, when executed, generates its own source code as output.  But how do you know it's actually producing its own source code?  Generally, you have to look at it and compare it, but with quines generally being composed of tricky and intricate code, this is not always easy.
Comparing two strings, though, is something a computer does very well, so why not make the program validate itself?  Your task is to create a program that:

produces its own source code as output
compares its output to its own source code
raises some sort of error, appropriate to the language used, if the output does not match

If the output does match, it's acceptable to terminate without further output
it can be hard-coded to know where to look to find its own source code for purposes of comparison.  Using this knowledge to actually produce the output in the first place, however, is cheating.

Popularity contest; whoever gets the most upvotes wins.  No standard loopholes, etc, you know the drill.
Enjoy!

I find this challenge confusing. If I understand correctly, I should write a source S for a program that produces output O such that O == S, and if O != S, then an error should be raised. But since O == S, I know that the output matches and no error should be raised, so the program doesn't need to check anything.

@Zgarb: But how do you know that O == S if you don't compare it?

Because that's a necessary condition for being a valid answer. So if my answer is valid, I don't need to check the output.

@Zgarb: You are missing the point, which is that that is part of the challenge.  Making a boring quine that does nothing but produce its own source is easy; making one that actually does something (somewhat) useful as well, while still turning out to be a quine... that's an entirely different animal.

@MasonWheeler You can create a quine in any language which is able to execute any code - also known as dynamic quine (or quine template). It's not difficult. || On a different note, you might want to include an example of what you expect in your task.

How do we validate the validation? That's the real question.