text:
Alternating sort
Given a list of pairwise distinct integers, sort it in alternating order: The second number is larger than the first, the third is smaller than the second, the fourth is larger than the third etc. (This order is not unique.) E.g., 5 7 3 4 2 9 1 would be valid output.
Extra points (since this is code golf, subtract from the number of characters):

15 for not using any built-in sort functionality.
15 if your code does not reorder inputs that are already ordered this way.
10 if the output order is random, i.e., multiple runs with the same input yield different correct outputs.

Do we write a stand-alone program, reading from stdin and writing to stdout, or rather a function, accepting a sequence as an argument and returning the modified sequence? Or may we choose either?

Wait, the last two bonuses are incompatible!

@JanDvorak: Not neccessarily: as my program demonstrates, you can return valid sequences unmodified, and still obtain random sequences otherwise. So multiple runs with the same sequence yield different outputs – at least for most input sequences.

What about lists that have no "alternating solution"?--e.g.{2,1,9,9,9,9,9,9,9}.

Although the task as specified isn't exactly a duplicate of The Strange Unsorting Machine for Nefarious Purposes, many of the answers there are applicable so it doesn't add much to the site.

@JanDvorak Yes, they are. I considered having the third bonus formulated the way MvG interpreted it, but decided against it, for easier rules.

@MvG Either function or filter is fine by me.

@David Good point, I excluded that case by restricting the input.

@Peter I hadn't seen that one, you are right, they are somewhat similar. I believe they are different enough not to close as duplicate, though – in particular with the “keep as is” bonus included.

What does it mean for a list of integers to be "pairwise distinct"? Does it mean that the numbers are unique (appearing at most once, as in "a set of pairwise relatively prime numbers"), or does it say that the same number never appears twice consecutively?

@FireFly It means that each number occurs only once.

Golfscript, 21-30 = -9
~(\{.2$>0!:0^{\}*}/]`

Bonuses: does not use built-in sort constructs (-15); does not modify a sorted array (-15)
Since, in general, it's not possible to sort an array of integers as defined, this assumes that either all integers are distinct, or "larger" and "smaller" actually mean "or equal".
Explanation:
Algorithm taken from Stack Overflow:
What is the most efficient way to sort a number list into alternating low-high-low sequences?

~(\ evals the input, which should yield an array, pops the first element and swaps it before the array.
{...}/]` iterates the block over the array, collecting the results on the stack so that they can be reused immediately, then collects them into an array and stringifies the array so that  it's displayed in a sensible format.

The block:

.2$> duplicates top two elements of the stack (in reverse order) and compares them, yielding 0 or 1.
0!:0 pushes an negates a zero, then overwrites zero with its negated version. This, the variable 0 alternates between the values 0 and 1. This is used to define the comparison sense. It's nice to have a variable initialised to the logical zero, and 0 just happens to be a variable and initialised to the value of 0.
^{\}* XORS the sense with the comparison result, then swaps the top two elements if the result is true.

Example:
;"[3 8 1 6 5 4 7 2 9]"
~(\{.2$>0!:0^{\}*}/]`
#[3 8 1 6 4 7 2 9 5]

I wish I had seen the SO question. That really makes this whole question uninteresting.

Mathematica 24 19 18 = 58 - 40
u = {1, 4, 9, 2, 7, 5, 3, 8, 6}

u//.s:{x___,y_,z_,___}/;y>z⊻OddQ@Tr[1^{x}]:>RandomSample@s

{4, 5, 3, 8, 2, 7, 1, 9, 6}

It doesn't reorder ordered list.
For a list with an even number of elements one can save 2 characters:
n=0;u//.s:{x___,y_,z_,___}/;OddQ@n++⊻y>z:>RandomSample@s

You can write even test as 2\[Divides] instead of OddQ@ which is 3 characters shorter, replacing > with < to restore order.

Also Length@_x works too, a bit clearer with same length.

Mathematica 81-15-15-10=41
f[t_] := t //. {l___, x_, y_, z_, r___} /; x > y > z || x < y < z :>
   f@RandomSample[s = {l, x, z, y, r}] /; s != t

Examples
f@{1, 2, 3, 4, 5, 6, 7, 8}
> {1, 4, 3, 6, 5, 7, 2, 8}

f@{1, 2, 3, 4, 5, 6, 7, 8}
> {8, 3, 5, 2, 7, 4, 6, 1}

f@{8, 3, 5, 2, 7, 4, 6, 1}
> {8, 3, 5, 2, 7, 4, 6, 1}

Japt, 19-40 = -21 bytes
äÎäÎ×©Uªá fÈäÎäÎ×Ãö

Try it
äÎäÎ×©Uªá fÈäÎäÎ×Ãö     :Implicit input of array U
ä                       :Consecutive pairs
 Î                      :  Signs of differences
  äÎ                    :As above
    ×                   :Reduce by multiplication
     ©U                 :Logical AND with U
       ª                :Logical OR with
        á               :  Permutations of U
          f             :  Filter by
           È            :  Passing each through the following function
            äÎäÎ×       :    As above
                 Ã      :  End filter
                  ö     :  Random element

w/o Bonuses, 9 bytes
á æÈäÎäÎ×

Try it
á æÈäÎäÎ×     :Implicit input of array
á             :Permutations
  æ           :First element to return true when
   È          :Passed through the following function
    äÎäÎ×     :  As above

This is my first ever code golfing attempt. Not sure how happy I am with it (there must be a better way to get list of each character in stdin than raw_input() and a list comprehension) but for a first try I think I'm proud.
Python 2.7 (117 = 117 chars - 0 bonuses)
def f(l):
 o=[]
 l.sort()
 while len(l):o.append(l.pop(0));l=l[::-1]
 return o
print f(map(int,raw_input().split()))

Welcome to Programming Puzzles & Code Golf Stack Exchange! "Given a list of integers, sort it in alternating order:" - you seem to be sorting the characters of the input instead.

Use built in map() to take input. You can use it this way map(int,raw_input().split()) This will return a list of integers.

I only recently discovered how useful map is. Thanks for the help!

Ruby 1.9+ (20 = 35 characters - 15 bonus)
Ah, the good ol' minmax!
f=->a{a[1]&&(m=a.minmax)+f[a-m]||a}

Sample run:
irb(main):004:0> f[[1,2,3,4,5,6,7]]
=> [1, 7, 2, 6, 3, 5, 4]

Ruby 1.9+ (43 = 83 characters - 40 bonus)
A solution that satisfies all the bonuses: Shuffles the argument array until it's alternatingly (?) sorted. To check the array, it is zipped toghether with a shifted copy of itself and an alternating array of < and  > symbols, forming something like [[1, :<, 2], [2, :>, 3], [3, :<, 4], [4, :>, 5], ... ]
f=->a{a.shuffle!until a.zip([:<,:>].cycle,a[1..-1]).all?{|x,o,y|!y||x.send(o,y)};a}

C (57 = 97 characters - 40 bonus)
i,t,j;f(a[],n){for(;++i<n;)if(a[i^i&1]>a[i^!i&1])for(i=n;--i;)t=a[j=rand()%n],a[j]=a[i],a[i]=t;}

Bogosort with alternating compares shuffling with Fisher-Yates. The shuffle loop uses the same index as the comparison loop so when the shuffle is done the comparison loop is automatically reset. The indexes in the array we compare have their lowest bit flipped based on the index we compare, it works without parentheses thanks to nice operator precedence and associativity.
Assumes that rand is actually random or at least seeded properly.

Python (75 = 115 characters - 40 bonus)
The same strategy as the second entry in my Ruby answer, except it loops on while instead of until and the condition is negated (from "all correct" to "any uncorrect").
from random import*
def f(a):
 while any(eval(`x`+o+`y`)for x,y,o in zip(a,a[1:],"><"*len(a))):shuffle(a)
 return a

JavaScript (Node.js), 75-40=35 bytes
f=x=>x.some((c,i)=>c>x[i-1]^i%2)?f(x,x.splice(Math.random()*2,0,x.pop())):x

Try it online!

Python 3 (119 = 159 chars - 40 bonuses)
def o(x):
 a,s=x[0],1
 for b in x[1:]:
  if(b-a)*s<0:return 1
  s,a=-s,b
import random
s=list(map(int,input().split()))
while o(s):random.shuffle(s)
print(*s)

Python 3 (may be 2 also)
def f(a):
 for i in range(len(a)-1):
  if (a[i+1]-a[i])*(-1)**i<0:
   a[i:i+2]=a[i+1],a[i]
 return a

100 characters (100)
Do not used builting sorting (-15)
Do not moved already alternating values (-15)
O(n) time complexity (-0)
Total score = 100 - 15 - 15 - 0 = 70

Vyxal, 18 - 40 = -22 bytes
Ṗ'¯±:k+$•⁼;:?c[_|℅

Try it Online!
This is why bonuses are a bad idea

JavaScript, 87
Fairly straightforward approach: sort given array in ascending order, then swap every two elements starting with the second one ([a[i],a[i+1]]=[a[i+1],a[i]]).
According to author, function is OK, so here's a function (87 characters):
function s(a){a.sort();for(i=1;i<a.length-1;[a[i],a[i+1]]=[a[i+1],a[i]],i+=2);return a}

Version with I/O (94 characters, you are supposed to type array like this: 3,7,9,2,1,4,5):
a=(prompt().split(",")).sort();for(i=1;i<a.length-1;[a[i],a[i+1]]=[a[i+1],a[i]],i+=2);alert(a)


text:
Lua: Render a chess board in smallest code
I'm creating a simple challenge here as a first test of the community's reactions. Please let me know if this challenge is the kind of thing you guys like or what I can improve... :)
The task is this: Render a chess board in Lua in smallest code possible.
Here is an example solution: http://tinybrain.de/145
As you can see, there is definitely room for getting smaller than 657 bytes (# of bytes are printed on the page). All the information you need for coding should be on the page or, hopefully, on tinybrain.de. Mailed questions totally welcome too. Lua API overview: http://tinybrain.de:8080/tb/debug.php?cmd=144
I am not demanding your chess board to have the exact same colors or even the same size. It should look like a chess board, that's all.
You need to register on TinyBrain.de to submit and test code. (Sorry, hope that is OK... It's free and I'm not a data peddler, so no harm there... :)
Edit: For testing your code locally (without any registration or Internet connection), you can download the TinyBrain runtime (magic.jar). Here is the link: http://tinybrain.de:8080/magic.jar

Does it have to be rendered as an image? Your question doesn't specify that.

Yes, that was the original idea... What's the alternative? Render it as ASCII? Well, why not. We can collect those solutions too. :) In that case, just use print() statement(s)!

Could you bring in the examples from tinybrain.de and make the source code for magic.jar available (I am a bit hesitant to run unkown binaries on my machine that I've downloaded from the internet).

Closing as unclear because tinybrain.de is now a dead link.

For a fancy ASCII art solution:
print("/"..("-"):rep(32).."\\")for y=0,15 do print("|"..("....    "):rep(5):sub(1+(y-y%2)*2%8):sub(1,32).."|")end print("\\"..("-"):rep(32).."/")

At 145 characters.
For a small ASCII art solution:
for i=1,8 do print(("# "):rep(9):sub(i,i+7))end

At 47 characters.

Great job :) Is it the shortest ASCII version? Using "rep" is pretty smart!

(Typo in the second solution gives a ninth row.)

@Stefan I'm unsure if it's the shortest solution, but it's probably close.

@breadbox fixed.

Starting with col6y's "small ASCII" solution (47):
for i=1,8 do print(("# "):rep(9):sub(i,i+7))end

sometimes brute force is better (43):
for i=1,4 do print("# # # # \n # # # #")end

:)

You don't really need the trailing space after the newline, and Lua has sugar for calling functions with a string literal: print"# # # #\n # # # #".  Though, you could save yet more chars anyway by using string.rep instead: print(("# # # #\n # # # #\n"):rep(4)) clocks in at 37.

Nice. Wish I'd noticed that.

38
Combining 14921's and col6y's ideas:
print(("# # # # \n # # # #\n"):rep(4))

83 characters
This snippet takes advantage of the description's offer to omit one of the dimensions, and to use a single integer to represent the pixel color.
w=256
p={}
for i=0,65535 do p[i+1]=5595493-((i-i%32)/32+(i-i%8192)/8192)%2*26214 end

(The character count doesn't include the newline on line 2, which I've included solely for legibility.)
The logic is pretty straightforward. The expression (i-i%32)/32 is equivalent to math.floor(i/32) -- in other words, integer division. Written in C's bitwise operators (which Lua lacks), the logic would look like this:
p[i] = (((i >> 5) ^ (i >> 13)) & 1) ? dark : light

This solution should produce identical output as the example given in the description.
You can shave off several characters by changing the colors to pure black and white, assuming -1 can be used to represent the white color:
w=256
p={}
for i=0,65535 do p[i+1]=((i-i%32)/32+(i-i%8192)/8192)%2-1 end

If I also change the size to be 64x64 (which the description permits), I can bring it down to 65 characters:
w=64
p={}
for i=0,4095 do p[i+1]=((i-i%8)/8+(i-i%512)/512)%2-1 end

However, the description doesn't seem to have any objective limits as to the chessboard's appearance. (Rookie mistake.) Let's go ahead and use the color 0x000000 for the white squares, and 0x000001 for the dark squares. And let's have the chessboard squares be 1x1. I can then bring it down to 48 characters:
w=8
p={}
for i=0,63 do p[i+1]=(i+(i-i%8)/8)%2 end

Or, if we forgo graphics entirely and stick to ASCII, we can use this 54-character solution and still be legible:
for i=1,8 do print(('* * * * *'):sub(1+i%2,8+i%2))end

Oh! I see we have someone with some good knowledge of Lua. Really nice. It's a very good job I'd say.

I do see an opportunity for improvement. 2 bytes can probably be saved both on the graphics version and on the text version. With the text version, I'm sure it's possible, my idea for graphics version would have to be tested.

Oh, and another thing: -1 works as white in the pixel array. A white that is good as invisible is REALLY stretching it a bit... ^^

@StefanReich -1 for white you say? I'll change that at once.

27-29 letters :-þ
supersmall diagonal but not ascii ..
print(("♦♦♦♦♦♦♦♦\n"):rep(5));

3D version 35 letters :)
print(("◄►◄►◄►◄►◄►◄►◄►\n"):rep(8));

extra nice version :)
print(("▇   ▇   ▇   ▇\n  ▇   ▇   ▇   ▇\n"):rep(4));

source: Stack Exchange

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

sort: votes


text:
Create self-extractor script (relaxed rules)
This is the target language-relaxed version of Generate a self-extractor application
Create a program in any language, that takes an arbitrary binary input, and generates a valid program (also in any language), which when compiled and run (or interpreted) will print this binary input.
So you could do this:
$ cat file.dat | python program.py > gen.rb
$ ruby gen.rb > file.dat.new
$ diff file.dat file.dat.new
$ echo $?
0

The scoring depends on the byte count of the original code (O), and the square of the byte count of the generated codes for the following inputs:

A: The whole lyrics of Never gonna give you up
B: The uncompressed grayscale 32x32 BMP version of Lena Söderberg
C: The original source code (the generator, O)
D: The generated source code for the A input

Score is O + max(A, O)^2 + max(B, O)^2 + max(C, O)^2 + max(D, O)^2.
Score explained:

The values for the generated variants are squared to encourage optimizing the size of the generated code (and the size of the original code is reflected in C as well).
Also to encourage minimizing the length of the generator code (as opposed to the generated code), if the generated code is smaller than the generator, then the size of the generator will be used instead.

Lowest score wins.
Clarification of the rules:

You can use the standard libraries of the chosen language(s), except for libraries that are designed (or can be used directly) for compression and/or decompression (like zlib, bz2, etc.). Using other kinds of libraries, like base64 are fine, but they have to be part of the standard library of the chosen language(s).
The generated code has to be able to print the original data without any external help, like network connections or pipes, etc. (e.g. if you move the gen.exe to another, isolated computer it should be able to generate the output there as well). You also have to assume that the generated code (if you are using an interpreted target language) will be run the following way: $ langint script.scr > output where langint is the interpreter of your chosen language.
The code generator should also work for any other input (generates code that regenerates the original input), but compression performance for them is not measured in the score (this means that optimizing the generator only for the test inputs are okay). However if there is (or anyone finds) at least one input with a maximum size of 65535 for which the code generator does not work, then the score of the submission is infinite.
The input files are supplied in base64 to make sure everyone will run the app on the same inputs. Please note that the lyrics have windows style line endings. Base64 decoding of the input is not part of the challenge, it can be done separately (eg the file.dat on the example is already the base64 decoded file).

File inputs in base 64:
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=

Lena
Qk02CAAAAAAAADYEAAAoAAAAIAAAACAAAAABAAgAAAAAAAAEAAB1CgAAdQoAAAABAAAAAAAAAAAA
AAEBAQACAgIAAwMDAAQEBAAFBQUABgYGAAcHBwAICAgACQkJAAoKCgALCwsADAwMAA0NDQAODg4A
Dw8PABAQEAAREREAEhISABMTEwAUFBQAFRUVABYWFgAXFxcAGBgYABkZGQAaGhoAGxsbABwcHAAd
HR0AHh4eAB8fHwAgICAAISEhACIiIgAjIyMAJCQkACUlJQAmJiYAJycnACgoKAApKSkAKioqACsr
KwAsLCwALS0tAC4uLgAvLy8AMDAwADExMQAyMjIAMzMzADQ0NAA1NTUANjY2ADc3NwA4ODgAOTk5
ADo6OgA7OzsAPDw8AD09PQA+Pj4APz8/AEBAQABBQUEAQkJCAENDQwBEREQARUVFAEZGRgBHR0cA
SEhIAElJSQBKSkoAS0tLAExMTABNTU0ATk5OAE9PTwBQUFAAUVFRAFJSUgBTU1MAVFRUAFVVVQBW
VlYAV1dXAFhYWABZWVkAWlpaAFtbWwBcXFwAXV1dAF5eXgBfX18AYGBgAGFhYQBiYmIAY2NjAGRk
ZABlZWUAZmZmAGdnZwBoaGgAaWlpAGpqagBra2sAbGxsAG1tbQBubm4Ab29vAHBwcABxcXEAcnJy
AHNzcwB0dHQAdXV1AHZ2dgB3d3cAeHh4AHl5eQB6enoAe3t7AHx8fAB9fX0Afn5+AH9/fwCAgIAA
gYGBAIKCggCDg4MAhISEAIWFhQCGhoYAh4eHAIiIiACJiYkAioqKAIuLiwCMjIwAjY2NAI6OjgCP
j48AkJCQAJGRkQCSkpIAk5OTAJSUlACVlZUAlpaWAJeXlwCYmJgAmZmZAJqamgCbm5sAnJycAJ2d
nQCenp4An5+fAKCgoAChoaEAoqKiAKOjowCkpKQApaWlAKampgCnp6cAqKioAKmpqQCqqqoAq6ur
AKysrACtra0Arq6uAK+vrwCwsLAAsbGxALKysgCzs7MAtLS0ALW1tQC2trYAt7e3ALi4uAC5ubkA
urq6ALu7uwC8vLwAvb29AL6+vgC/v78AwMDAAMHBwQDCwsIAw8PDAMTExADFxcUAxsbGAMfHxwDI
yMgAycnJAMrKygDLy8sAzMzMAM3NzQDOzs4Az8/PANDQ0ADR0dEA0tLSANPT0wDU1NQA1dXVANbW
1gDX19cA2NjYANnZ2QDa2toA29vbANzc3ADd3d0A3t7eAN/f3wDg4OAA4eHhAOLi4gDj4+MA5OTk
AOXl5QDm5uYA5+fnAOjo6ADp6ekA6urqAOvr6wDs7OwA7e3tAO7u7gDv7+8A8PDwAPHx8QDy8vIA
8/PzAPT09AD19fUA9vb2APf39wD4+PgA+fn5APr6+gD7+/sA/Pz8AP39/QD+/v4A////AEmnoKA4
OUVOT0tDSHCAhIiNkpOUnrDNtmJ3dWBUZFk/aJSbp0MwOkU9W0IpUGSCi4+QjJKiu9ieXliNaExV
ZUVZiZerTS45ND1jSyhDY2qNj4uNmazH2H9SS5i1WFZhTlB8l6tMMTk1QVtcOzRkaYSOiZKgt8/K
foCJj8eRWWBbXHaZqkcwRDM8a3RSOkxneYuMmKi/26B8lYeO2bNjZWJycpqsTi5CO0twc0ozPVVz
i5Cer8fcZG6WjIKt0nBhZn5TmqxaNUhNV3ZqPzU7RXKJjaLEzok/c5SEcXbQnktZOU+kpWI9QWBu
dU06MjU9ZIGUpJlbOk9whX1+e8bXi0UuY6qhXEk/aXJ4PTU0OkJjh5qmYShASW+dmZaFvdzWujZe
raRoVUNpYJV1MDZCYoOKfo2HPDhDaaGalYi02tXWQF6soWZdQlJgbJJRLkp6i4uIm6hlNEFjmZiT
i6rT0tVKV6igYV9MXV09U3xHRXyNmpeHqI09PmSGnJWOoczQ0klKpZ1lalRhQjdWWH5AeJWll3ur
oVU9YGahmJGRvszQT1GooF94WlNGPFw3e3tzobKjh7ejZERcSJqalYugxsheW6uhX29zWUlTWCo/
pI+IkZ+GsotURl81ip2Zlo2ftWBkqp1ZX3OTU0pMNi9rwGxMbYGyZz5GWy5woZqbmZCMY2uqm1hk
aoFyY0U5Nz2Rs4l2oMG5cUlRMVScop+ZlY5ka6qaWWVrdYZ/UjY3P0+bs6mvxtuHUUQ2OouhnJmZ
mWdtqZlVYWZwp317WD1FOkqYuKy+xmZwQjEvZp+ko6CcZ3OqllZhYX2zf36AZEQ7RVmku7i4doeP
QipGmaehnZtjdqyVVmJcmKl5f4SIdVhpUFCkxMPFpoiCPy58pZ+bml5yq5VXYl6YoHWCh46Ukpea
lp6yv8fPw590JlKcoJ2dYHCqlFhjYJOKan2Mk6Crrq61uLK2wsrQxbE2L3mjn5xhb6aQVmRli3hs
eYKYq7GyucG/yMemnr3W1U4pQ5WhnFlqpIxUYmh+e218goeluL3DycvZoo+BSKvQRjAuYZ6hV2yk
jFdjanZ5b3eFiIquw8nM1r1nlYczd5tZLTM0eKNpaKeLV2RpdXpzc3uIjqe8ydbJamSZgmKTko89
LTBCg5Rupo1VY2p0e313foaUr77GtH9ncJWNjJKPlI08LzE9pY+ijlplbXl+gIKCjZ6wsp18eXRy
jpeYk42S1nUpMy2ipaSMX2dsen6AgYKBgoWBfX+Ad3WTnp2bkLm7dVgwMZ2hp41haG17gYKDg4N/
f4ODgIB3dZyinpigzIJ2glsun5yokmJqbnyDhIWFhoSDhYOBgnSCnp2bmMKob3t9gWU=

Yay! A new challenge :)

Max(D,O)? Did you mean Min(D,O)? Otherwise we'll be given the score of the uncompressed file unless we manage to make it even larger.

@JanDvorak No... say I have a 25 char generator (O). And D is what O generated given A. So if A was 100 and O made it 50 (50 = D), Max(D,O) = 50

PHP - 141.047.262 45.922.273 13.895.520 13.779.516
My code applies a handcrafted huffmann encoding to the input, see below for an uncompressed and commented version.

O: 1145
A: 1901 (42 bytes smaller)
B: 2180 (78 bytes larger)
C: 1223 (78 bytes larger)
D: 1979

Demo:
[timwolla@~/workspace/php]cat lena.txt |php huffmann.php |php|md5sum && md5sum lena.txt
ebcc2e2a501121b37dcbac3e438be58b  -
ebcc2e2a501121b37dcbac3e438be58b  lena.txt
[timwolla@~/workspace/php]cat rick.txt |php huffmann.php |php|md5sum && md5sum rick.txt
549d9635795ef37857e0b3dc02e52e53  -
549d9635795ef37857e0b3dc02e52e53  rick.txt

Minified version:
<?php
$q=file_get_contents('php://stdin');$_='str_split';$i=$_($q);$t=[];$c=array_count_values($i);foreach($c as$k=>$v)$t[]=['c'=>$v,'v'=>$k];do{usort($t,function($a,$b){return$a['c']-$b['c'];});$a=array_shift($t);$b=array_shift($t);$t[]=['c'=>$a['c']+$b['c'],'l'=>$a,'r'=>$b];}while(count($t)>1);$r=[];function t($t,&$r,$j=''){if(isset($t['v']))$r[$t['v']]=$j;else{t($t['l'],$r,$j.'1');t($t['r'],$r,$j.'0');}}t($t[0],$r);uksort($r,function($a,$b){return$a<$b;});$z=$_(array_reduce($i,function($a,$b)use($r){return $a.$r[$b];},""),8);$z[]=str_pad(array_pop($z),8,0);$s="";for($i=0;$i<256;$i++)$s.=isset($r[chr($i)])?$r[chr($i)].';':';';$w='<?php
$_=<<<\'EOT\'
'.array_reduce($z,function($a,$b){return $a.chr(bindec($b));},"").'
EOT;
$s=explode(";","'.$s.'");$r=[];foreach($s as$k=>$v)$v?$r[chr($k)]=$v:1;$o=implode("",array_map(function($a){return str_pad(decbin(ord($a)),8,0,0);},'.$_.'($_)));for(;$l=strlen($o);){for($i=1;$i<$l;$i++){$p=substr($o,0,$i);if(($k=array_search($p,$r,true))!==false){echo$k;$o=substr($o,$i);continue 2;}}die;}';
do{$x=md5(mt_rand());}while(strpos($q,$x));
$q="<?=<<<'x$x'
$q
x$x;
";echo strlen($w)<strlen($q)?$w:$q;

Uncompressed and commented version:
(Note that it will surely spit out the unencoded version, because of the comment)
<?php
$q=file_get_contents('php://stdin'); // read input
$_='str_split'; // shorter name (saves some bytes in the end)
$i=$_($q); // convert input into array of chars
$c=$t=[];
$c=array_count_values($i); // calculate frequency table
foreach($c as$k=>$v){
    // build bottom of huffmann tree
    $t[]=[
        'c'=>$v, // count
        'v'=>$k // value (= the character)
    ];
}
do{
    usort($t,function($a,$b){return$a['c']-$b['c'];}); // sort elements of the tree-to-be
    $a=array_shift($t); // lowest count
    $b=array_shift($t); // 2nd lowest count

    // and merge them
    $t[]=[
        'c'=>$a['c']+$b['c'], // cumulated cost of this part of the tree
        'l'=>$a, // left
        'r'=>$b // right
    ];
}
while(count($t)>1);
$r=[];
// recursive tree traverser to build the bits of the encoding
function t($t,&$r,$j='') {
    if(isset($t['v'])) {
        // abort once we found a value
        $r[$t['v']]=$j;
    }
    else {
        // going left = 1
        t($t['l'],$r,$j.'1');
        // going right = 0
        t($t['r'],$r,$j.'0');
    }
}
t($t[0],$r);
// sort the bit-mapping by ascii value of the key
uksort($r,function($a,$b){return$a<$b;});

// encode the input by concatenating the bits and split the result into chunks of 8 bits
$z=$_(array_reduce($i,function($a,$b)use($r){return $a.$r[$b];},""),8);
// ensure the last part is 8 bit long
$z[]=str_pad(array_pop($z),8,0);

// encode the mapping into a semicolon separated string, unmapped characters are empty (that's why I sorted the mapping above)
$s="";
for($i=0;$i<256;$i++) {
    $s.=isset($r[chr($i)])?$r[chr($i)].';':';';
}

// build the decoder
$w='<?php
$_=<<<\'EOT\'
'.array_reduce($z,function($a,$b){return $a.chr(bindec($b));},"" /* // convert the 8-bit chunks into characters */).'
EOT;

// split the encoded map at the semicolons
$s=explode(";","'.$s.'");
$r=[];
foreach($s as$k=>$v) {
    $v?$r[chr($k)]=$v:1; // if there are some bits save them into the map
}
// convert the encoded characters back into a long string of 0 and 1
$o=implode("",array_map(function($a){return str_pad(decbin(ord($a)),8,0,0);},'.$_.'($_)));

for(;$l=strlen($o);){
    // search the whole string for an character in the map
    for($i=1;$i<$l;$i++){
        $p=substr($o,0,$i);
        if(($k=array_search($p,$r,true))!==false){
            // character found, spit it out
            echo$k;
            // and remove the bits
            $o=substr($o,$i);
            continue 2;
        }
    }
    // nothing found, we are finished, the remaining characters are a result of the padding to multiples of 8
    die;
}';
// search a NOWDOC delimiter that does not occur in the input
do{
    $x=md5(mt_rand());
}
while(strpos($q,$x));

// build a program that simply spits out the input unchanged
$q="<?=<<<'x$x'
$q
x$x;
";

// check which one is shorter :-)
echo strlen($w)<strlen($q)?$w:$q;

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


text:
Produce a palindrome from this text

Copy and paste or curl this text:
http://lorem-ipsum.me/api/text
Using any language make the text palindromic.
You may remove letters.
You may rearrange letters.
The goal is to make the text palindromic by the sequence of the letters and spaces. The end result might not contain words. It will be merely a sequence of letters and spaces.
Capital letters are considered the same as lowercase letters.
You may use each letter only once, or you may remove the letter.
You may also use each space only once. Or you may remove the space.
The result should be the longest palindrome you can programmatically create from the text.
While you could technically print just the letters AaA or something similar to it, that is not what I am looking for.
Your palindrome creator should work with any text.
A palindrome, by definition, is a word, phrase, number, or other sequence of symbols that reads the same backward as forward.  A sequence of symbols that reads the same backward as forward is the acceptable palindromic definition I am looking for in this CodeGolf example.
Scoring will be Length of palindrome / Length of code. The winner is the one with the highest score.

Text:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, possimus voluptatem do ut vel deserunt laborum. cupidatat libero minim at a aute minus cupiditate excepturi reiciendis blanditiis, atque vero. dolorem dolores dolore corrupti aute recusandae repellat recusandae modi deleniti libero nostrud aute delectus quidem alias odio nostrum pariatur. placeat minus similique a aliquip facere ullamco officiis eligendi ad at magnam commodi maxime.

Adipisicing modi enim similique maxime ex nisi sed eu suscipit earum corrupti assumenda perferendis cumque maiores qui praesentium nobis. Sed voluptas consequatur voluptates rerum facilis qui dolor commodi minim provident, magnam facere, tenetur. Aliqua voluptatibus delectus illum dolorem excepturi aliquip duis odio. Excepturi similique hic iusto eu consectetur laboriosam quidem esse eiusmod, anim. Eu consequatur magnam tempor vel.

Nobis incididunt eius cum distinctio magnam velit facilis libero ullam, tenetur distinctio eius eveniet. Anim possimus expedita fugiat facilis vel consequatur in temporibus laboriosam at molestiae velit cupidatat. Vel consequatur voluptate cum sint dolores ullamco quas omnis quibusdam id officiis tenetur voluptas, tempore tenetur aliquam debitis. Nostrud, do in numquam magnam quia voluptate incidunt accusamus distinctio officia molestiae fuga. Nam corporis ex quos recusandae sed.

Ullamco incidunt cupidatat eos voluptate delectus nostrud nisi irure quod quis alias. Fuga quam autem mollit ex dolores quod non tempor mollitia quas labore sapiente a anim deserunt expedita minus. Ex pariatur accusamus alias deleniti quo, quia similique voluptas. In voluptatibus esse perferendis commodo aute repellendus accusamus laboriosam deserunt aute possimus laboriosam.

Labore hic tempora, ad iusto hic aliqua ducimus. Distinctio omnis tempore incididunt ut sed mollit, quidem, aute sunt eius eveniet, vel distinctio cupiditate eius atque. Fuga asperiores tenetur enim, provident similique aliqua nostrum ad dolorum, molestiae, repudiandae ad sunt. Consequatur ullamco a nisi aliqua non omnis officia.

Labore sapiente obcaecati libero quas eos incididunt. Saepe quas voluptas mollitia consectetur dolores dolores officiis id, quo, laboriosam reprehenderit alias. Voluptates cumque dignissimos, cumque dolor. Incididunt minima consectetur harum et.

What if the text isn't symmetric? For example, the text of this comment in this question can't be palindromed as it has more than one letter that occurs an odd number of times, hence it can be flipped without duplicating a letter.

Can you give an example input and output here?

@LegoStormtroopr I believe that's what he means by "you may remove letters". My interpretation is: every character in that file is going into a bag, and you pull characters from the bag to create a palindrome?

How will this be scored? Length of palindrome / Length of code?

Please explain why you're emphasising you in "the longest palindrome you can programmatically create".

@Johnston, since you have tagged this as [tag:code-golf] then are you prepared to award the win to the shortest code, even if the palindrome it generates is extremely suboptimal?

I would suggest tightening up Rule 10 a bit.  "Or something similar" is vague and you're already seeing submissions that are extremely short, generating extremely short palindromes.

@JoshCaswell The Mathmatica answer below is a good example.

@Bob "...into a bag..." Exactly. Except that you may also discard letters you pick from the bag.

@Bob: "How will this be scored?" Yes that is perfect. Length of palindrome / Length of code.

@DarrenStone The scoring should fix that, no? Length of palindrome / Length of code.

I'm still a bit confused. Is the winner the one with the highest score, or the lowest? Code golf is usually lowest score wins, but this scoring mechanism encourages very long programs which create extremely short palindromes - and that seems contrary to the intent of this challenge.

@Iszi Highest score. Largest palindrome and shortest program. It encourages short programs with long palindromes.

How does a score of NaN sort?

Why is this on hold and what do you mean NaN score? NaN will be 0. Lowest score. How would you come to NaN?  Also what else is unclear?

You still haven't answered my question, so that's still unclear for a start.

@PeterTaylor: The objective is to find the longest palindrome with the least amount of code. I was attempting to point out that there is 1 palindrome that is longest by definition, but I will accept all palindromes, however the scoring will make smaller palindromes equate to less points. Emphasis on the word you was unnecessary and possibly confusing . I have unbolded the word "you".

The spec still seems a bit confusing. Particularly: "A palindrome is a word, phrase, number, or other sequence of symbols." (not at all minding the fact that it's an incomplete definition to begin with) is self-contradictory when paired with several other portions of the challenge which specify that we're only dealing with letters and spaces. Which is it? Do we need to count for non-letter/space characters or not - and if so, which ones?

In any case, the specification that the palindrome can be any combination of the characters in the given text input, without any regards to having the output make any sort of sense at all, makes this relatively trivial. Simply count the occurrence of each character, rounded down to the nearest even number, then output a string that has half of those occurrences sorted ascending followed by half of them descending. If you want to get a bonus point on length, take one of the odd characters and put it in the middle (though this may make your code long enough to nullify that bonus).

@Johnston Looks like it's already done. I figured someone else had probably gotten ahead of me on that - just hadn't bothered to look yet.

With this latest edit, your definition of a palindrome still remains incomplete. In fact, by explicitly stating that this incomplete definition is the one to be used for this challenge, one might simply echo the text as-is and be done because it is "a sequence of symbols".

Per general StackExchange quality guidelines, shouldn't the Lorem Ipsum text be included in the question so that the question remains valid if the link goes dead?

Mathematica 146 92 chars (score 2130/92 = 23.15)
Shorter Version (92 chars)
This palindrome has the characters grouped,
""<>{s=({#[[1]],Length@#~Quotient~2}&/@ Gather@Characters@t)
/.{c_,n_}:>c~Table~{n},Reverse@s}

Longer Version (146 chars)
This will return a maximum length, randomized palindrome from t.
Because capital letters are equivalent to lowercase letters, I converted all capitals to lower case.  (This can be changed if necessary.)
f@t_ := "" <> Join[s = RandomSample[ Flatten[({#[[1]], Quotient[Length[#], 2]} & /@
     Gather[Characters@ToLowerCase@t]) /. {c_, n_} :> ConstantArray[c, n]]], Reverse@s]

Example:
When t is the suggested, Lorem ipsum, text.  (Ignore line returns; all line returns were generated via the SE editor.)

"ti,iopexri  rpiuu opaat tismimetnesa lvuot oiaiu oaaittcoar nc
muapua elhpibemu utin ia f  ihide sdourgeeic e  oaasa.marsae dstircd
ci ndn   rs t egoaiq.aeatntreusng xi a lumalnoiieqqeq cc otiueasniieu
nrpupdlmnai o cdsm t gt.iccmittli i t tu.rust.li maui bea gqiceeo
pncu eonttecvtutqun eaaariusoquppsedlqu scrddmt esiafidurs  hitlpna
nlamltire ivmumbabi nbuderup td x uuualsoq.eiib li olel ru aeelau
idbc lrop iil ssur anda o scnmsr ,m uri,teo
esmiaveuomrt ldqqaid ihi snsr   spueeoevcre oe
msirulaleaisormm.oicolarsstteo td aatncn ieqrsuam boid te utcf eccp
siacu m etnqutlacniiereltiulqemltaqx a
qtdlxmliibileoheesimittlusqemooamuiippeaiilcgudsatfsiemamsc irn
rsgoi, ie
nmteiaiiptraned alsomsui noru ic,mditi ic ouud oadmv iudinrfuludet
eeiidueel nndaemcrepnioe sials unetuamconn,i
ubpo eiu ei dsn equi,ue ostmp udiatqu dalmau nueeiit ln e mioancteop
ntiiao ts noeefubtefrit ldeop earnmsm oas
d.catirotulvliodiellmesurotiomsmduia.nauenb iuiroimduriohs.lrndsaroc
t inidrssq apeuionnlaa eqdroounosmotidr arxr o taouarut  ussce uamae
is.dcadaimuoaprad iifl  i  lmml  i  lfii darpaoumiadacd.si eamau
ecssu  turauoat o rxra rditomsonuoordqe aalnnoiuepa qssrdini t
corasdnrl.shoirudmioriui bneuan.aiudmsmoitorusemlleidoilvlutoritac.d
sao msmnrae poedl tirfetbufeeon st oaiitn poetcnaoim e nl tiieeun
uamlad uqtaidu pmtso eu,iuqe nsd ie uie opbu
i,nnocmautenu slais eoinpercmeadnn leeudiiee tedulufrnidui vmdao duuo
ci itidm,ci uron iusmosla denartpiiaietmn
ei ,iogsr nri
csmameisftasdugcliiaeppiiumaoomeqsulttimiseehoelibiilmxldtq a
xqatlmeqluitlereiincaltuqnte m ucais pcce fctu et diob mausrqei
ncntaa dt oettssralocio.mmrosiaelalurism eo ercveoeeups   rsns ihi
diaqqdl trmouevaimse
oet,iru m, rsmncs o adna russ lii porl cbdi  ualeea ur lelo il
biie.qoslauuu x dt puredubn ibabmumvi eritlmaln anpltih  srudifaise
tmddrcs uqldesppuqosuiraaae nuqtutvcettnoe ucnp oeeciqg aeb iuam
il.tsur.ut t i ilttimcci.tg t msdc o ianmldpuprn  ueiinsaeuito cc
qeqqeiionlamul a ix gnsuertntaea.qiaoge t sr   ndn ic dcritsd
easram.asaao  e cieegruods edihi  f ai nitu umebiphle aupaum cn
raocttiaao uiaio touvl asentemimsit taapo uuipr  irxepoi,it"

It is possible that Chron and Lego Stormtroopr have more efficient solutions than mine.

Python, 1/4
A single character is a palindrome, so...
s[0]

presuming the target text is stored in s.

Rule 10 says this is not what he wants.  Also, did you mean s[0]?  s[1] will not work if s has less than 2 characters, while s[0] works as long as s is not empty.

I thought my solution sufficiently different from AaA.  No idea why I used s[1] initially.

Ruby, 78 chars
Reads from standard input.
s=gets.downcase.chars.group_by{|c|c}.map{|k,v|k*(v.size/2)}*''
$><<s+s.reverse

For example, passing the text from @LegoStormtrooper's first comment on the question:
What if the text isn't symmetric? For example, the text of this comment in this question can't be palindromed as it has more than one letter that occurs an odd number of times, hence it can be flipped without duplicating a letter.

The program will return this:
whhhhhaaaaaattttttttttttt                    iiiiiiiffeeeeeeeeeeexssssnnnnnn'mmmmrrrrccccooooopplll,uubddddddbuu,lllppoooooccccrrrrmmmm'nnnnnnssssxeeeeeeeeeeeffiiiiiii                    tttttttttttttaaaaaahhhhhw

If you don't want the punctuation at all (on re-reading the question it sounds like you only want letters and spaces) this will work (87 chars):
s=gets.downcase.scan(/[a-z ]/).group_by{|c|c}.map{|k,v|k*(v.size/2)}*''
$><<s+s.reverse

Which returns:
whhhhhaaaaaattttttttttttt                    iiiiiiiffeeeeeeeeeeexssssnnnnnnmmmmrrrrccccoooooppllluubddddddbuulllppoooooccccrrrrmmmmnnnnnnssssxeeeeeeeeeeeffiiiiiii                    tttttttttttttaaaaaahhhhhw

Python 2.7 - 82
Takes an input, converts it all to lower case,
makes an array with half (rounded down) of each character,
then prints that out concatenated to itself in reverse.
Worst case scenario, it outputs an empty string if every character is unique.
L=raw_input().lower()
o=[x*(L.count(x)/2)for x in set(L)]
print''.join(o+o[::-1])

Python, 107
s="""Lorem ipsum dolor sit amet, consectetur adipisicing elit, hic a sunt odio eius culpa labore. vero vero possimus irure quidem est saepe ut do quis excepturi incididunt. magna eveniet nisi enim quidem distinctio.

Ullam saepe officiis consequatur, provident soluta blanditiis sunt possimus minima impedit corporis voluptatibus occaecat distinctio mollitia, commodo et. Facilis autem cum dolor dignissimos magna modi nisi labore animi incididunt numquam quam voluptatem optio tempor provident fugiat ullam. Consequat tempora numquam minim tempore eius perferendis ullamco labore corporis officiis. Saepe deserunt a asperiores rerum quis excepteur odio voluptatibus ducimus itaque.

Qui nam provident corrupti sunt velit est laboris. Delectus tempora possimus quas cillum exercitation debitis cupidatat omnis voluptatibus. A dignissimos saepe repellat nostrum quaerat rerum molestias, alias dolorum provident fuga repellat sed, esse cum illum culpa animi. Placeat atque necessitatibus nostrud saepe maxime cupiditate, impedit elit iure hic.

Excepturi id numquam odio aliquam maiores, expedita eveniet. Repellendus eos voluptates quaerat excepteur sunt velit consectetur vel eius ad voluptatem corporis cillum tempore incidunt molestiae. Atque tempora, duis vero, tempore et sint nostrud molestiae laboris eligendi maxime nam reprehenderit.

Fugiat anim commodo sed incidunt, et aut, labore corrupti velit incididunt quaerat. Aliquam saepe minima sunt minima eos, nobis, eu delectus itaque optio consequatur voluptatibus delectus ex sapiente deserunt dolor. Optio doloribus officiis ducimus dolores.

Voluptas commodo cupidatat molestiae tempora quia consequatur. Repellendus ea rerum exercitationem, odio voluptatem ullam perferendis ea animi deleniti deleniti quaerat magnam repellat voluptates. Obcaecati aut exercitation dolore nisi eos."""

import itertools
t=''.join(''.join(list(g[1])[1::2]) for g in itertools.groupby(sorted(s)))
print t+t[::-1]

itertools.groupby(sorted(s)) groups identical characters. list(g[1])[1::2] takes each group and cuts it in half, rounding down for odd-length groups. It then joins the lists together and prints the resulting string concatenated with its reverse. Could be improved in a number of ways, as already demonstrated by others.

authors: Huá dé ní 華得尼


text:
Minimum perimeter of an area
Just a simple code golf function for fun, intentionally left open with few rules to see what creativity comes up.
Input: An integer representing the area of a rectangle.
Output: Two integers representing the side lengths of the rectangle that have the least perimeter for the area.  (In any order.)
Test cases:
25 => 5, 5
53 => 53, 1
4294967295 => 65537, 65535

For the sake of completeness here the corresponding OEIS numbers:  http://oeis.org/A033676 and  http://oeis.org/A033677

GolfScript (21 chars)
:^,{)^\%!},.,2/=)^1$/

This takes the input as a number on the stack and leaves the result as two numbers on the stack.
For fair comparison with Howard's solution, taking input on stdin and giving output on stdout separated by newline is 23 chars:
~:^,{)^\%!},.,2/=)n^2$/

It works because this problem is trivial: it's just looking for the pair of factors closest to sqrt(area).
Online demo for a square; online demo for a non-square.

I knew that my first try-and-post solution wouldn't last very long.

Runs out of memory on the last test case, otherwise seems to be working :)

Mathematica 34 26
Besides the explicit search there is a nice convergent series:

n = 27

{i=√n//.i_:>n/⌈n/⌊i⌋⌉,n/i}

{3, 9}

Three previous approaches with 34 characters:
{#,n/#}&@FixedPoint[n/⌈n/⌊#⌋⌉&,√n]

For[i=√n,i>(i=n/⌈n/⌊i⌋⌉),];{i,n/i}

f@i_:=f[f@i=n/⌈n/⌊i⌋⌉]
{i=f@√n,n/i}

ClearAll[f]

Visualization:
p = FixedPointList[n/⌈n/⌊#⌋⌉ &, Sqrt[n]];

Plot[n/x, {x, 0, 11}, GridLines -> {Range@n, Range@n},
 AspectRatio -> Automatic, PlotRange -> {{0, 10.2}, {0, 7.2}},
 Epilog -> {Red, Thickness[0.005],
   Arrow[Transpose[{{n/p, ⌈p⌉}, {n/p, ⌊p⌋}, {⌈n/⌊p⌋⌉, ⌊p⌋}}, {2, 3, 1}]],
  PointSize[0.02], Black, Point[{n/p[[-1]], p[[-1]]}]}]

(this is not a function, but a snippet evaluating to the answer. Invalid according to newer consensus, can somebody fix it? ...)

Python 2 (63 62)
n=input()
print[(i,n/i)for i in range(1,n)if i*i>=n/i*i==n][0]

This produces all pairs of integers (i, n/i) that could be the sides of the rectangle, starting from the first one greater or equal to the square root of n. It prints the first one.

You may save a single char if you take the reverse list, i.e. i*i>=n and then the first element [0].

Is it just me or does it blow up on the last test case? :)

@JoachimIsaksson Yes, because it goes through all the numbers from 1 to n, it scales very poorly. I actually had a much more elegant solution first that used a generator instead of a list comprehension, so it didn't generate unused elements, but it needed a few extra characters...

Follow-up on Levin's answer.
It fails on areas that are prime.
I.e. > python peri.py
401
Traceback (most recent call last): File "peri.py", line 2, in ? print[(i,n/i)for i in range(1,n)if ii>=n/ii==n][0]
IndexError: list index out of range Fix it by using n+1 inside the range. n=input()
print[(i,n/i)for i in range(1,n+1)if ii>=n/ii==n][0] > python peri.py
401
(401, 1) Cheers,
Gert

Golfscript (46 43 40)
~1{..*2$>!}{1$1$%!{.@@}*)}while;1$/p p];

No way to beat the math oriented languages at this challenge I suspect :)
Somewhat "long winded", it would be shorter to work with arrays, sadly they get a bit large with the last test case.
Basically what it does is similar to the Python solution, it loops from 1..sqrt(n), testing for an even multiplier, then just displaying the last value found.

You may replace {X}{}if with {X}* in this case.

@Howard Thanks, updated, although I see you soundly beat me with your solution :)

GolfScript, 30 characters
~:t,{[.t\/].~*t=1$~>!&\@if}*n*

Does a test on all numbers as many other solutions.

@JoachimIsaksson For me it works fine, have a look here.

Hm, I think my ruby install was severely broken, 32 bit ruby gets it right (but fails with out of memory on the last test case)

C# (178)
int[] R(int n){var a=Enumerable.Range(1,n);var b=a.SelectMany(x=>a.SelectMany(y=>a.Select(_=>new{x,y}))).Where(f=>f.x*f.y== n).OrderBy(f=>f.x+f.y).First();return new[]{b.x,b.y};}

Pretty
int[] R(int n)
{
    var a = Enumerable.Range(1, n);
    var b = a.SelectMany(x => a.SelectMany(y => a.Select(_ => new { x, y }))).Where(f => f.x * f.y == n).OrderBy(f => f.x + f.y).First();
    return new[] { b.x, b.y };
}

Java 8, 73 72 bytes
Saved one byte due to @ThomasKwa!
n->{for(int i=(int)Math.sqrt(n);;i--)if(n%i<1)return new int[]{n/i,i};};

Lambda function, test with:
public class Rectangle {
    interface Test {
        int[] run(int v);
    }
    public static void main (String[] args){
        Test test = n->{for(int i=(int)Math.sqrt(n);;i--)if(n%i<1)return new int[]{n/i,i};};

        int[] testCases = {1, 4, 8, 15, 47, 5040, 40320, 25, 53};
        for (int i : testCases) {
            int[] result = test.run(i);
            System.out.println(i + ": " + result[0] + ", " + result[1]);
        }
    }
}

Finds the greatest divisor less than or equal to the square root of the area. Returns an int[].

@ThomasKwa I knew there was a way to do it with < or >, I just couldn't figure it out. Thanks!

C, 54 bytes
f(x,y){for(y=sqrt(x);x%y;y--);printf("%d, %d",y,x/y);}

Just some general silliness.
Test if you like:
int main() {
    printf("Enter a number\n");
    int a;
    scanf("%d", &a);
    f(a);
    printf("\n");
    return 0;
}

C# 4.0: 79 characters
long[] P(long a){long r=0,s=0;while(++s<a/s)if(a%s==0)r=s;return new[]{r,a/r};}

If it weren't for the last test case, I could save 3 characters naming long to int.
In pretty format:
long[] Perimeter(long area)
{
    long result = 0;
    long side = 0;
    while (++side < area / side)
    {
        if (area % side == 0)
            result = side;
    }
    return new long[] { result, area / result };
}

C, 71 bytes
Nothing fancy, find the pair of integers (a, b) closest to sqrt(n) such that a*b==n:
f;x;L(n,a,b)int*a,*b;{for(f=0,x=sqrt(n);x;--x)n%x||f++?:(*a=x,*b=n/x);}

If the function is allowed to work only on first invocation, then we can shrink it to 67 bytes:
f;x;L(n,a,b)int*a,*b;{for(x=sqrt(n);x;--x)n%x||f++?:(*a=x,*b=n/x);}

Test main:
#include <stdio.h>

int main() {
  int testdata[] = {1, 4, 8, 15, 47, 5040, 40320};
  int x,y;
  for (int i = 0; i < 7; ++i) {
     L(testdata[i], &x, &y);
     printf("%5d >  %dx%d\n", testdata[i], x, y);
  }
}

The code was originally written for another golf, which is a duplicate of this.

Jelly, 8 bytes
÷Ɱ½ĖḞƑƇṪ

Try it online!
Use a bunch of new quicks. (ƇⱮƑ)

Jelly, 9 bytes
ọⱮ½TṪð,÷@

Try it online!
A port of my other answer.

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


text:
Shortest unmatchable regular expression
Your mission is to write the shortest valid regular expression that no string can match, empty string included.
Submissions must have this form ("literal notation"):
/pattern/optional-flags

Shortest regexp wins. The regexp size is counted in characters. (including slashes and flags)
Please explain how your regexp works (if it's not trivial)
Thanks, and have fun!

This inspired a question from me. I'm going to wait a few days though. Don't want 2 regex questions active at the same time

"Valid" according to which implementation? I've just found an amusing one that Perl is okay with (and that is valid according to the only RE grammar I can find, but that grep and Python's re module refuse.

Yes, which dialect(s) of regex? There are many many different ones.

But what about Presidents' names?  http://xkcd.com/1313/

@CarlWitthoft You need to be a program to participate in that contest: http://codegolf.stackexchange.com/q/17718/2180

@boothby  I might be an AI :-)

Which syntax? Perl or POSIX?

6 chars
Following on the answers of primo and Peter Taylor, and a hint from man perlre:
/(?!)/
This perl-compatible regex matches an empty string which is not followed by another empty string.

+1 - This is probably the shortest answer which is widely portable (along with /x\by/, but if I ever actually had to use a regex like this - for whatever reason - then this answer is also the clearest one)

@m.buettner: Thanks.  primo's /(*FAIL)/ is probably clearer, though.  (And actually man perlre gave it away by mentioning that mine actually expands to his internally.)

/(*FAIL)/ is not as portable though. And even in Perl, I think it's a more obscure feature than a negative lookahead.

@m.buettner: Oh, I assumed both were Perl-specific.

You get lookarounds in almost all of the popular (Perl-inspired) flavours today, whereas I've never seen these control verbs anywhere but in Perl.

In fact, Perl documentation (and -Mre=debug) says that (?!) is optimized into (*FAIL) by Perl regex optimizer (OPFAIL according to -Mre=debug). Also, I don't think I saw (*FAIL) outside of Perl 5 (and Perl 6, where it's called <!>).

8 chars
/(?=a)b/

We require a string containing a character which is both a and b, which is obviously impossible.

/(?!x)x/ looks even more impossible ;-)

@PeterTaylor where?

@Lohoris, where what?

@PeterTaylor where did he put those absurd rules you talk about, I couldn't find them.

guys, sorry for the counting i chose, i thought it would be simpler to include slashes because of the optional flags that could come after them.

5 chars
Unlike everybody who abuses $ and ^... this actually works in Perl:
/V\A/

\A matches the beginning of the string.

It works with ^ too.

Nice picket fence :)

6 chars
/x\by/

Based on Sven Hohenstein's answer.

8 characters
/\w\b\w/

A word boundary (\b) surrounded by 'word' characters (\w - one of [_a-zA-Z0-9]). It is unmatchable since one of the characters preceding or following a word boundary must be a non-'word' character.
By the way: this is similar to the unmatchable expression
/\W\b\W/

where \W means non-'word' character.

This is 8 characters according to the rules of the competition, because the wrapping slashes / count. See OP's entry, for example. It's a great entry, though!

It also might be a winner (or tied with Peter Taylor's entry), given the implementation-dependent problems with some of the shorter entries!

Very elegant! I thought there must be something like this!

9 chars
I'm not sure but /[^\S\s]/ should be unmatchable since it means not any character, but at least one of them.

You don't need the +.

/[^\S\s]/ = 9 chars

4 chars
/$a/

searches a "a" after the end of the string.
or
/a^/

searches a before the beginning of the string.

Isn't it only two chars? I would only count $a = 2 chars.

Why post the question if you know that there's a two-char solution?

I didn't know, I found it afterwards.

@Howard: That matches an empty string: http://jsfiddle.net/RjLxJ/

Why do I always find these problems after an unbeatable solution is provided :(

-1: Putting ^ and $ in "illegal" positions just causes them to be treated as ordinary characters.  Your first example matches the literal $a in sed and probably other programs.

@Ben Jackson, that's not true for POSIX EREs. Try echo 'a^b' | grep 'a^b' vs. echo 'a^b' | grep -E 'a^b'. Check out 9.4.9 ERE Expression Anchoring

@BenJackson that's not true for ^ in PERL! perl -e'print "a^"=~/a^/ prints nothing.

Similarily to the other answers with this theme, this is wrong because ^ and $ are only special at the beginning and end, respectively, of the pattern; outside that, they are regular characters.

5 characters
/$.^/
/$^/ will match an empty string, whereas requiring a character in between will not.

This unfortunately matches "$a^" (or anything in place of the 'a') in Perl (and maybe sed). Still a nice one, though!

@JoshCaswell: I guess perl might interpret $. as the current line number variable. Which might be empty, in which case this will be /^/.

A character 'between' just means a one-character string.

@jwg notice the swapped ^ and $

I tried the pattern '$^' with grep, but unfortunately it matched the string '$^'.  Smartass grep.

Similarily to the other answers with this theme, this is wrong because ^ and $ are only special at the beginning and end, respectively, of the pattern; outside that, they are regular characters.

4 characters
(ECMAScript flavour only)
/[]/

In other flavours this is not a valid character class (the ] would be considered a character in the class, so the expression isn't valid, because the class is never closed), but the ECMAScript standard accepts empty character classes. Since it is a class it has to match a character (so empty strings don't match), but since not a single character is included no actual character will match either.

Wouldn't this match an empty string even though you says it has to match a character? Or do you think this is illegal: /[]{0}/. (Ps. though my own answer partially looks like yours, I actually read yours after writing mine.)

@nl-x paste this into your browser's console: /[]/.test(""). it returns false. a character class can never match an empty string, even if it doesn't contain characters (I imagine they are implemented like "IF the next character in the string is one of those listed, match; ELSE fail"). /[]{0}/ is legal (in ECMAScript) and does match the empty string... however, I'm not sure how that is relevant to my answer.

Fails in Ruby 2.0

@Nakilon of course it does. Ruby doesn't implement the ECMAScript flavour.

6 characters
/\b\B/

This matches a word boundary (\b) that isn't a word boundary (\B), which is obviously impossible.

doesn't this one search for a word-boundary followed by a non-word-boundary?

@grexter89 Yes, but they can't have any characters in between. i.e. The boundary and the non-boundary have to occupy the same space.

I like this one. Good catch.

6 chars
/b++b/

Possessive quantifier looks for as many b's as possible, then 1 more. 6 chars but points for symmetry?

Huh... I just learned a new feature. Apparently, my regex skills are badly out of date. Thanks, and +1.

6 characters
/(\1)/

Not a winner, but I thought it was fun. grep and Python both barf on this one, but Perl seems okay with it.
Seems to be very implementation-dependent (which is hardly surprising, given its weirdness). Bob reports below that it matches anything in JavaScript's regex engine.

.NET's regex engine seems to accept it.

And it always matches (an empty string) no matter what input on JS

Maybe a bit of cheating, but…
\0

… is unmatchable in POSIX regex in virtually all, if not all, implementations. BASIC RE and EXTENDED RE, even.
And POSIX RE does not need those pesky slashes and flags PCRE has.

+1 Good!! Unfortunatelly, sole 0 doesn't work in PERL. "0"=~0 is true...

sole \0 ITYM? Yes, most perlre(1) and PCRE implementations do not use C strings but size-bounded buffers, in whom this trick will not work, but most POSIX RE implementations work on C strings.

6 bytes
/(*F)/

An abbreviation for (*FAIL), supported by perl-compatable regex engines. Thanks to @HamZa for pointing this out.
9 bytes
/(*FAIL)/

Should work with any regex engine that supports verbs at all. I'm not convinced this really needs to be golfed any further.

How does this work?

@boothby (*FAIL) is a verb that always fails.

@primo you might just use /(*F)/ :)

4 char:
/.^/

Works with GNU grep 2.5.1 and egrep.

/.^/ = 4 chars.

Why do you need the //? those are not required everywhere ;-)

The wrapping slashes / count, see the original question ("including slashes and flags") and the OP's entry.

right! I miss read  :(

No, for the same reason as the one below: Actually, “^” is only special if at the beginning of the pattern. Any “^” after anything else does not need to be escaped, so this answer is wrong.

Perl 6 (5 characters)
/<!>/

Sorta rule abuse (because Perl 6 regexes are different, and incompatible with stardard regexes by design), but I don't care. <!> rule informs Perl 6 that the regex doesn't match.

5 chars
/^.^/

Matches string that begin with any single character before string begin.

Also matches the string ".^"

@boothby: in which language does matches? in Python doesn't. re.findall(r'^.^', '.^', re.DEBUG)

+1 for using the manga operator (see http://stackoverflow.com/questions/3618340/what-does-the-caret-operator-do)

@boothby ^ and . are metacharacters not literal, that need to be escaped

It's broken in Perl.  This question really should have set some ground rules about language.

Actually, “^” is only special if at the beginning of the string. Any “^” after anything else does not need to be escaped, so this answer is wrong.

4 chars with slashes 2 without
In the TXR language's regex engine, an empty character class [] matches no character, and therefore no string. It behaves this way because the character class requires a character match, and when it is empty it specifies that no character can satisfy it.
Another way is to invert the "set of all strings including empty" regex /.*/ using the complement operator: /~.*/. The complement of that set contains no strings at all, and so cannot match anything.
This is all documented in the man page:
   nomatch
          The  nomatch  regular  expression  represents  the empty set: it
          matches no strings at all, not even the empty string.  There  is
          no  dedicated  syntax  to  directly express nomatch in the regex
          language.  However, the empty character class []  is  equivalent
          to nomatch, and may be considered to be a notation for it. Other
          representations of nomatch are possible: for instance, the regex
          ~.* which is the complement of the regex that denotes the set of
          all possible strings, and thus denotes the empty set. A  nomatch
          has  uses;  for instance, it can be used to temporarily "comment
          out" regular expressions. The regex ([]abc|xyz) is equivalent to
          (xyz), since the []abc branch cannot match anything. Using [] to
          "block" a subexpression allows you to leave it  in  place,  then
          enable it later by removing the "block".

The slashes are not part of the regex syntax per se; they are just punctuation which delimits regexes in the S-expression notation. Witness:
# match line of input with x variable, and then parse that as a regex
#
$ txr -c '@x
@(do (print (regex-parse x)) (put-char #\newline))' -
ab.*c                               <- input from tty: no slashes.
(compound #\a #\b (0+ wild) #\c)    <- output: AST of regex

thanks for your answer and sorry again for the slash-counting. I thought it would be easier to include them if people used flags.

4 chars
/$./

Needs any character after the string ends

Similarily to the other two ones, $ is only special at the end of the pattern.

This is a 5 char regex.
/[]+/

It matches an empty group 1 or more times.
EDIT:
Removed my answer for other flavours:
/.{-1}/

Anything that is not a number inside {} will match the text.
This one will match ".{-1}"

Note that this only works in the ECMAScript flavour. In most (all?) others it is not a valid expression.

Isn't it invalid?

@Wasi not in ECMAScript-conforming flavours

6 chars
(or 4, depending on how you look at it)
/{,0}/

Fails in Ruby 2.0

In which regex implementations does this not give an error?

I only tested it using PHP's preg_match.

5 characters
Hope this doesnt sound stupid: /[]+/

Nope. Not a valid regex.

@RyanCarlson It is valid and legal... At least in Ecmascript.

/$^/

A thing that ends before it has begun...

Matches the empty string (in some RE implementations, anyways).

Your implementation is broken :)

Better let Guido know.

More importantly, as Ben Jackson pointed out, in Perl, where it doesn't match "", it does match a string containing those two literal characters: "$^".

+1 I just wanted to post the same! @Josh, it does work in PERL, and it doesn't match empty string! Ben's comment is broken, I replied to it.

I didn't say it matched the empty string, @Tomas, I said it matched the string "$^": perl -le 'print "Sure enough" if("$^" =~ /$^/)'

@Josh Caswell, you are sure enough but also mistaken enough :-) $^ is a variable that expands to STDOUT_TOP. Your string must be escaped: perl -le 'print "Mistaken enough" if("\$^" =~ /\$^/)', as well as Simons solution must be: /\$^/ or q{$^}.

It doesn't matter what it expands to or what its value is, @Tomas. The contest is to make a regex that matches nothing. If there's any match at all, the pattern doesn't qualify.

Simon, your regex matches a string STDOUT_TOP. Funny enough :-) PS: you haven't tried this one? :-)

Same problem as the other three answers: ^ is only special at the beginning of the pattern, and $ is only special at the end of the pattern, so this does, in fact, match the literal string $^.


text:
Output and sourcecode lineup
General constraints:

Your program should not take any input.
Your program should output words, 1 word/line.
Only capital letters (A-Z) in the output.
A word must be atleast 2 letters in length.
A word can never be a palindrome. That is forbidden.

Rules for word-manipulations, one or more of these operations in any individual order for each new line:

Change one or more letter(-s) in the word 1 char distance (example: A->B, F->E) from the previous word. 'A' can not be 'Z' and 'Z' can not be 'A'.
Insert the letter "A" at any position.
Remove any letter at any position.

Output validation:
Your program must output the following words: OUTPUT, YOUR, SOURCECODE, TODAY atleast (but not limited to) once each, in any order.
Sourcecode validation:
The first and the last letter of all output words should also be part of your sourcecode in the same order as scopes: first and last letter for the first word has the highest scope, example pseudo-code:
<any or no code><first letter, first word>
<any or no code><first letter, second word>
<any or no code><,...              ...,><any or no code>
<last letter, second word><any or no code>
<last letter, first word><any or no code>

For any word # where the actual word number is a fibonacci-number, the first and last letters must be lower-case in the sourcecode.
For any word # where the actual word number is not a fibonacci-number, the first and last letters must be upper-case in the sourcecode.

There is no restriction of the actual letters in the sourcecode, they can be inside strings or part of a command or anything, it is only the order that counts.
Example valid output (only the words YOUR and TODAY in the example):
YOUR
XOUAS
WOAAT
VOBAU
UOCAV
TODAW
TODAX
TODAY

Example valid sourcecode for the above output:
Since words 1, 2, 3, 5 and 8 in the example output is "fibonacci words", their first and last letter-representation in the sourcecode is lower case, leaving us with this constraint on the sourcecode:
yxwVuTTtyXWvUtsr

There could be any code around or between the letters in the sourcecode as long as the representation is there somewhere in that order.
This is code-golf, smallest sourcecode size in counted bytes wins. Competition ends: 2014-02-31.

This is super complicated. I'd be interested if anyone comes up with a sensible solution.

A working solution is easy, just figure out a valid sequence of words to output and put a string of the sourcecode constraint into the sourcecode. Golfing it migth be complicated though ;)

What does "in any individual order" mean?

You can apply the 3 operations on the word in any individual order. Example the "A" can be added and turned into "B" in the same "line"

What is a "word number"? As in, "For any word # where the actual word number is a fibonacci-number…"

A "word number" is the line number where the word is output, starting with number 1 = first line

Oh! End date: 2014-02-31 is impossible, it should be 2014-03-01 instead ;P

Golfscript, 211 210
stuVwXYoOOOOoOOOOOOOoOOOOOOOUTTTTYXWVUTSRQPONmLKJIHGFeDCBB
{.2$<@@>{)}%+}:b;
'ROURCeCodeS'{95&}%
'()[]+\+); '7*';"OUSB" "A"+-3b "A"+'+'-3b '13*+'-2b '6*+';"UTOBUU" ;"TOCAV" ;"TODAW" '+'))[]++ '2*+
' '/{~n 1$}%-4<(@

Newlines added only for clarity, and can be removed. The last bits of the letter string are the name of the function and inside 'ROURCeCodeS'.
Test online
Output:
SOURCECODE
TOURCECOD
UOURCECO
VOURCEC
WOURCE
XOURC
YOUR
OUSB
OUTCB
OUTDCB
OUTEDC
OUTFED
OUTGFE
OUTHGF
OUTIHG
OUTJIH
OUTKJI
OUTLKJ
OUTMLK
OUTNML
OUTONM
OUTPON
OUTPPO
OUTPQP
OUTPRQ
OUTPSR
OUTPTS
OUTPUT
UTOBUU
TOCAV
TODAW
TODAX
TODAY

Java, 1091 1039 bytes
Probably not very good, but I'll give it a try. (Formatting worse will give less Bytes, but for now, let's leave it)
edit 1: used names for Vars to make comment shorter.
public class t {
public static void main(String[] V){
    StringBuilder w = new StringBuilder("SOURCECODE");
    X(w);
    for(int Y=0; Y<6; Y++){
        w.deleteCharAt(4);
        w.setCharAt(0,(char)(w.charAt(0)+1));
        X(w);
    }
    w.deleteCharAt(0);
    for(int o=0;o<2;o++){
        w.setCharAt(2,(char)(w.charAt(2)+1));
        w.append('A');
        w.append('A');
        X(w);}
    for(int O=0;O<20;O++){
        if (O<15) w.setCharAt(3,(char)(w.charAt(3)+1));
        w.setCharAt(4,(char)(w.charAt(4)+1));
        if (O<19) w.setCharAt(5,(char)(w.charAt(5)+1));
        X(w);}
    w.deleteCharAt(6);
    X(w);//o
    for(int O=0;O<6;O++){
        if (O<5) w.setCharAt(0,(char)(w.charAt(0)+1));
        w.setCharAt(1,(char)(w.charAt(1)-1));
        X(w);}
    for(int O=1;O<4;O++){
    w.deleteCharAt(2);//o
    if (O<3) w.insert(4, 'A');
    X(w);}
    for(int O=0;O<5;O++){
        if (O<3) w.setCharAt(2,(char)(w.charAt(2)+1));
        w.setCharAt(4,(char)(w.charAt(4)+1));
        X(w);}
    //OOOOPQRsTTTTTTTTTT
    //yxwVuTTtTTTTtTTAAAAAaAAAAAAAAAAAAaAAREEEEEEE
}
static void X(StringBuilder b){System.out.println(b.toString());}}

outputs:
SOURCECODE
TOURECODE
UOURCODE
VOURODE
WOURDE
XOURE
YOUR
OUSAA
OUTAAAA
OUTBBBA
OUTCCCA
OUTDDDA
OUTEEEA
OUTFFFA
OUTGGGA
OUTHHHA
OUTIIIA
OUTJJJA
OUTKKKA
OUTLLLA
OUTMMMA
OUTNNNA
OUTOOOA
OUTPPPA
OUTPQQA
OUTPRRA
OUTPSSA
OUTPTTA
OUTPUTA
OUTPUT
PTTPUT
QSTPUT
RRTPUT
SQTPUT
TPTPUT
TOTPUT
TOPUAT
TOUAAT
TOAAT
TOBAU
TOCAV
TODAW
TODAX
TODAY

Mathematica 226 221 217
A little bit longer than GolfScript:
yxwV;
u:O_~T~OO_:=T[Print@FromCharacterCode@Select[O,#>64&]TSRQp;O+Sign[OO-O],u=OO]
"YOUR"
oOOOOOOOOOPQRsSSSEEDcBA(TT=ToCharacterCode)@"XOA@@S"~T~TT@"TODA@Y"~T~TT@"OUTPUT"t;
TT@"PTUQA?=T>@"~T~TT@"SOURCECODE"uVWXYyXWvUtsr;

Output:
YOUR
XOAS
WOBAT
VOCAU
UODAV
TODAW
TODAX
TODAY
TODAY
SPEBAX
RQFCBW
QRGDCV
PSHEDU
OTIFET
OUJGFT
OUKHGT
OULIHT
OUMJIT
OUNKJT
OUOLKT
OUPMLT
OUQNMT
OURONT
OUSPOT
OUTPPT
OUTPQT
OUTPRT
OUTPST
OUTPTT
OUTPUT
PTUQAT
QSURBSA
RRURCARB
SQURCBQAC
SPURCCAPBD
SOURCDBOCE
SOURCECODE

ClearAll[T] is necessary after usage.

Windows Batch File, 557
::yxwVuTTtSRQPoOOOOOOOoOOOOOOOOPQRSsSSSS
::EDCBaATTTTTTTTTTTtTTTTTTTtUVXXyXWvUtsr
echo YOUR
echo XOUAS
echo WOAAT
echo VOBAU
echo UOCAV
echo TODAW
echo TODAX
echo TODAY
echo SPEBAX
echo RQFCBX
echo QRGDCV
echo PSHEDU
echo OTIFET
echo OUJGFT
echo OUKHGT
echo OULIHT
echo OUMJIT
echo OUNKJT
echo OUOLKT
echo OUPMLT
echo OUQNMT
echo OURONT
echo OUSPOT
echo OUTPPT
echo OUTPQT
echo OUTPRT
echo OUTPST
echo OUTPTT
echo OUTPUT
echo PTUQAUT
echo QSURBAUT
echo RRURCBAUT
echo SQURCCBTA
echo SPURCDCSBA
echo SOURCECRCB
echo SOURCECQDC
echo SOURCECPDD
echo SOURCECODE

With similar code on Unix you could save a bunch of characters with tr , "\n"<<<'YOUR,XOUAS,...,SOURCECODE'|cat.

@WChargin Windows does it the long way.

GTB, 403
]yxwVuTTtSRQPoOOOOOOOoOOOOOOOOPQRSsSSSS\EDCBaATTTTTTTTTTTtTTTTTTTtUVXXyXWvUtsr[~"YOUR~"XOUAS~"WOAAT~"VOBAU~"UOCAV~"TODAW~"TODAX~"TODAY~"SPEBAX~"RQFCBX~"QRGDCV~"PSHEDU~"OTIFET~"OUJGFT~"OUKHGT~"OULIHT~"OUMJIT~"OUNKJT~"OUOLKT~"OUPMLT~"OUQNMT~"OURONT~"OUSPOT~"OUTPPT~"OUTPQT~"OUTPRT~"OUTPST~"OUTPTT~"OUTPUT~"PTUQAUT~"QSURBAUT~"RRURCBAUT~"SQURCCBTA~"SPURCDCSBA~"SOURCECRCB~"SOURCECQDC~"SOURCECPDD~"SOURCECODE

[C/C++] 1239 chars
Concept solution.
main() {
    // yxwVuTTtSRQPoOOOOOOOoOOOOOOOOPQRSsSSSS
    // EDCBaATTTTTTTTTTTtTTTTTTTtUVXXyXWvUtsr

    printf("YOUR\n");
    printf("XOUAS\n");
    printf("WOAAT\n");
    printf("VOBAU\n");
    printf("UOCAV\n");
    printf("TODAW\n");
    printf("TODAX\n");
    printf("TODAY\n");
    printf("SPEBAX\n");
    printf("RQFCBX\n");
    printf("QRGDCV\n");
    printf("PSHEDU\n");
    printf("OTIFET\n");
    printf("OUJGFT\n");
    printf("OUKHGT\n");
    printf("OULIHT\n");
    printf("OUMJIT\n");
    printf("OUNKJT\n");
    printf("OUOLKT\n");
    printf("OUPMLT\n");
    printf("OUQNMT\n");
    printf("OURONT\n");
    printf("OUSPOT\n");
    printf("OUTPPT\n");
    printf("OUTPQT\n");
    printf("OUTPRT\n");
    printf("OUTPST\n");
    printf("OUTPTT\n");
    printf("OUTPUT\n");
    printf("PTUQAUT\n");
    printf("QSURBAUT\n");
    printf("RRURCBAUT\n");
    printf("SQURCCBTA\n");
    printf("SPURCDCSBA\n");
    printf("SOURCECRCB\n");
    printf("SOURCECQDC\n");
    printf("SOURCECPDD\n");
    printf("SOURCECODE\n");
}

PHP: 321316 bytes
I can't take much credit for this; all I did was compress and base64 encode the word sequence in Timtech's answer.
<?php //yxwVuTTtSRQPoOOOOOOOoOOOOOOOOPQRSsSSSSEDCBaATTTTTTTTTTTtTTTTTTTtUVXXyXWvUtsr
echo gzinflate(base64_decode("Nc5JDsAgCEDRPbdStHMLInS4/0UqNd3wvokJPGQCN1mocFEICifFYGCE4QSlFK5v3t98oHKO7SFlwHhDkTHhCVynnAxI5yErkC3j4KzT6Gzz5OzL7Bzr4tC2OrxvTjl2R+hwKpOjzJ3SkU7taMcUWK2EZqkm0UPEBL+qpRVGDe3uVglrbNkWYcb25c+S8E9O6U9K+QU="));?>

Edit: Moving the comment to the end allows a few characters to be shaved off:
<?php echo gzinflate(base64_decode("Nc5JDsAgCEDRPbdStHMLInS4/0UqNd3wvokJPGQCN1mocFEICifFYGCE4QSlFK5v3t98oHKO7SFlwHhDkTHhCVynnAxI5yErkC3j4KzT6Gzz5OzL7Bzr4tC2OrxvTjl2R+hwKpOjzJ3SkU7taMcUWK2EZqkm0UPEBL+qpRVGDe3uVglrbNkWYcb25c+S8E9O6U9K+QU="));//TTtSRQPoOOOOOOOoOOOOOOOOPQRSsSSSSEDCBaATTTTTTTTTTTtTTTTTTTtUVXXyXWvUtsr
?>

Thanks for giving credit... I know it's not likely to win anything :)


text:
Shortest C \ C++ function to generate -1, 0 ,1
Let a function receive two integers i and j between 0 and 3, it should return the value in position (i,j) in the following 2D array:
1, 0, -1, 0
1, 0, -1, 0
0, 1, 0, -1
0, -1, 0, 1

Shortest code in any variant of C / C++ wins.

Why limit this to C/C++?

probably because the author realizes it is 3-4 chars in golfscript, and wants to make the competition more fair

@Kendall Frey - Actually the true code golf contests are possible only when they target single language (or family of languages). Because there is no point to compete when someone is running on foot, someone is swimming, and others use helicopter.

@mniip - I do not think this is 3 or 4 characters. I think it is about best C/C++ solution minus length of return keyword ;)

@SergeyS Even if I agreed, the rest of the site does not. Language-specific questions are discouraged here.

By the way, do you had in mind some truth-table approach when proposing the question?

How is this unclear?

32
f(i,j){return~-(j+2-i*i/3&3)%2;}

A winner by three chars :)

f(i,j){return-~-(i*i/3^j)%2;} is 29. I found it by running an exhaustive(ish) search. I can't post it because the question is closed, so I'll put it here.

40
f(i,j){return~-(2434352710>>8*i+2*j&3);}

A hackish 35 solution (xxd dump):
0000000: 6628 692c 6a29 7b72 6574 7572 6e7e 2d28  f(i,j){return~-(
0000010: 695b 2246 4619 9122 5d3e 3e32 2a6a 2633  i["FF.."]>>2*j&3
0000020: 293b 7d                                  );}

If proper octal escapes are used, it's the same 40 characters:
f(i,j){return~-(i["FF\31\221"]>>2*j&3);}

You can save 8 bytes by writing f(int i,int j) as f(i,j) (the arguments are int by default)

I see, i actually tried removing those ints, but somehow failed

C99, 34
f(i,j){return(i<3?1-j+i/2:j-2)%2;}

Also works in C89. And function text is 34 chars

I marked it C99 since C99 actually specifies the behavior of '%', whereas prior versions left it implementation-defined. And yeah, I was counting the newline. I'll fix that.

C, 29
I know this one seems kinda unfair but does it actually work for anyone? ^_^
f(i,j){j=("&&4+"[i]>>j)%3-1;}

Welcome to the site! You should add your byte count to the post as this is a code golf question. Also, you may want to add a link to an interpreter so that others can test your solution, such as Try It Online!

38
f(i,j){return(i/2+j+1)*(1-(i-j&2))%2;}

37
f(i,j){return(i/2+j+1)*-~-(i-j&2)%2;}

You can save 2 chars if you change (1-(i-j&2)) to ~-(j&2-i)

Tried your suggestion and it gives wrong results.(i-j&2) is actually ((i-j)&2) so your trick changes the logic here. or am i missing something?

oh, I kind of overlooked that, still can save 1 by replacing with -~-(i-j&2)

@mniip oh yes now it works, thx

C++, 70, 45, 44
f(i,j){return(j/2&i^~i&~j>>1)*~-(j-i&2)%2;}

The Karnaugh map approach, mixed with a bit of fsw's solution.
If A is (j>>1) and D is (i&1), the function should return "-~-(j-i&2)%2" (fsw's solution) multiplied by the Karnaugh map ~A~D + AD.
I feel there is a better solution for this using the Karnaugh map, but it's too late to think of it. Maybe tomorrow :)
Thanks for the comments, shaved off many chars.

you don't need most of the parentheses here: ((~(j>>1)&~(i&1)^j>>1&(i&1))&1)  also you can move the &1 into inside the left side of ^ : (~(j>>1)&~(i&1)&1^j>>1&(i&1))

C#
int f(int i,int j){return "2101210112101012"[i*4+j]-49;}

4 spaces will make that code highlighted...

You can save one character by removing the space after return. But it's arguable whether C# can be considered a variant of C/C++, despite the name. It's derived from C, but so is Java.

48
f(a,b){return 10308>>4*a+b&1?-1:43605>>4*a+b&1;}

C, 45
f(i,j){i=i+(j>1)*(7-2*j)&3;return i&1?0:1-i;}

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


text:
Manipulate destiny, fake random numbers: Be Dirty Harry
bool doYouFeelLuckyPunk, actuallyIsLucky;
doYouFeelLuckyPunk = Harry.catchyPhrase();
actuallyIsLucky = Bandit.rollDice();
if(doYouFeelLuckyPunk) {
    Bandit.grabGun();
    if(!actuallyIsLucky)
        Harry.useMagnum()
    else {
        Harry.tisButAScratch()
    }
else
    Bandit.surrender();

We all know how this plays out and we like it that way.
The task:
Write functions

bool Harry.catchyPhrase()
bool Bandit.rollDice()

Design them so the situation ends either in Harry.uswMagnum() or Bandit.surrender(), at random.
Challenge and key criterion: Obfuscate the fact that bandit cannot win, fake and manipulate the "randomness" in your functions. The less obvious the better of course.
Explain your manipulation in a non-spoilering way (white text etc.)
Language: Doesn't matter
Forbidden moves: none

I'm afraid this doesn't qualify as a [tag:code-trolling], but it's an interesting challenge nevertheless.

@JanDvorak yeah, I just re-read the description of CT and removed the tag.

So the challenge essentially equates to producing two booleans such that: both being true is impossible, while making it look like both can be true?

@Cruncher Indeed. Make it look like there was an equal (or at least existing) chance for any of the 4 possible outcomes, but true-true mustn't occur.

I'm voting to close this question as off-topic because this is a [tag:underhanded] question which are now considered off-topic.

How about this? Solution at the very bottom, encoded in base64. Language is C.
#include <stdio.h>
int lfsr = 0xACE1u;
/*Toy LFSR implementation stolen from wikipedia.*/
int random_bit(){
    /* taps: 16 14 13 11; feedback polynomial: x^16 + x^14 + x^13 + x^11 + 1 */
    int bit  = ((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 5) )&1 ;
    lfsr =  (lfsr >> 1) | (bit << 15);
    return ((lfsr >> 14)&(lfsr >> 15))^bit;
}
int surrendered=0,scratched=0,shot =0;

void harry_tis_but_a_scratch(){scratched++;}
int harry_catchy_phrase(){return random_bit();}
void bandit_surrender(){surrendered++;}
void harry_use_magnum(){shot++;}
int bandit_roll_dice() {return random_bit();}
void bandit_grab_gun() {}

int main()
{
    int random_number=0;
    /*Test bench random bit*/
    for(int y=1;y<51;++y){
        for(int x=0;x<8*sizeof(int);++x)random_number= (random_number<<1)|random_bit();
        printf("%-15d%c",random_number,y%5?' ':'\n');
    }
    printf("\nLooks pretty random\n\n");
    /*Play the game*/
    for(int x=0;100000 >=++ x;){
        int doYouFeelLuckyPunk = harry_catchy_phrase();
        int actuallyIsLucky = bandit_roll_dice();
        if(doYouFeelLuckyPunk) {
            bandit_grab_gun();
            if(!actuallyIsLucky) harry_use_magnum();
            else harry_tis_but_a_scratch();
        }else bandit_surrender();
    }
    printf("Shot: %d Surrendered: %d  Scratched: %d\n",shot,surrendered,scratched);
    return 0;
}
/*
                               Example Output
   1414529544,  -2071427967,     89395234,    690094340,    704663586,
     41977888,  -1572861663,   1107591810,    143171844,    546578948,
  -1542942712,  -1600056768,  -1571682240,     84415044,  -2138746864,
    705971264,    302123561,    168036485,    553717833,    545294674,
     71909648,  -1994096044,   1426227848,   1218611781,    138707496,
     16810505,    553783616,  -1861155808,  -1803283192,   1111626024,

Looks pretty random

Shot: 24941 Surrendered: 75059  Scratched: 0

                                  SOLUTION

IFRoZSB3YXkgdGhpcyB3b3JrcyBpcyBxdWl0ZSBzaW1wbGUsIHRoZSBMRlNSIGlzIHJlYWwgYW5k
IGRvZXMgaW4gZmFjdCBnZW5lcmF0ZQ0KIGdvb2QgcHNldWRvLXJhbmRvbSBudW1iZXJzLkFuZCBp
dCBpcyBpbmZhY3QgYW4gZXhhY3QgaW1wbGVtZW50YXRpb24gb2YgdGhlIG9uZQ0KIGZyb20gd2lr
aXBlZGlhLCBleGNlcHQgZm9yIG9uZSBhZGRpdGlvbjoNCiANCiBUaGUgb3V0cHV0IGJpdCBpcyB4
b3InZCB3aXRoICgobGZzcj4+MTQpJihsZnNyPj4xNSkpDQogDQogTm9ybWFsbHkgdGhpcyBzaG91
bGRuJ3QgYmUgYSBwcm9ibGVtLCBhcyB0aGUgcmVzdWx0IG9mIGEgcmFuZG9tIGJpdCB4b3InZCB3
aXRoDQogYW55IGZ1bmN0aW9uIGJlc2lkZXMgaXRzZWxmIGlzIHNlbGYgaXMgc3RpbGwgYSByYW5k
b20gYml0Lg0KIA0KIEhvd2V2ZXIsICgobGZzcj4+MTQpJihsZnNyPj4xNSkpIGlzIG5vdCBhIG5v
cm1hbCBmdW5jdGlvbi4gRHVlIHRvIHRoZSBMRlNSIGFsc28NCiBiZWluZyBhIHNoaWZ0IHJlZ2lz
dGVyIHRoZSBvdXRwdXQgb2YgdGhlIHJhbmRvbSBiaXQgZnVuY3Rpb24gaXMgYWN0dWFsbHkgdGhp
czoNCiANCiByZXR1cm4gKGxhc3RfYml0JmJpdCleYml0Ow0KIA0KIFNvLCBpZiB0aGUgbGFzdCBi
aXQgd2FzIGEgMSB0aGUgYml0IHJldHVybmVkIGlzIGd1YXJhbnRlZWQgdG8gYmUgMC4NCiANCiBT
byBpdCBpcyBpbXBvc3NpYmxlIHRvIGdldCB0byB0aGUgJ3RpcyBidXQgYSBzY3JhdGNoJyBmdW5j
dGlvbiwgYXMNCiBpdCBpcyBpbXBvc3NpYmxlIGZvciBib3RoIGRvWW91RmVlbEx1Y2t5UHVuayBh
bmQgYWN0dWFsbHlJc0x1Y2t5IHRvIGJlIHRydWUu

*/


text:
Build a deterministic Go AI
Here's an interesting problem I thought of the other day, which involves bits of code competing against other bits of code not just in a property that the code has, but by playing a game against those other bits of code.
Your task is to build a program that takes the current state of a Go board, and determines what move to make or to pass.
Your program will accept the following as input:

19 lines, each with 19 characters, representing the pieces currently on the Go board. A character of 0 represents an empty square, 1 is black, and 2 is white.
Two numbers representing the number of prisoner pieces each player has (black, then white).
One number representing whose turn it is to move (black or white). As above, 1 is black, and 2 is white.

and output one of the following:

A pair of coordinates a b representing the coordinates at which to move. 1 1 is the top-left square, and the first and second numbers represent moving down and to the right respectively.
The string pass, which represents a move to pass.

For example, the program may receive the following input:
0000000000000000000
0000000000000000000
0000000000000000000
0001000000000002000
0000000000000000000
0000000000000000000
0001210000000000000
0000100000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0002000000000001000
0000000000000000000
0000000000000000000
0000000000000000000
0 0 1

which represents a game where only a few moves have been played.
Then the program might output 6 5, which means "put a black stone on the point 6th from the top and 5th from the left". This would capture the white stone at 7 5. The state of the board would then change to:
0000000000000000000
0000000000000000000
0000000000000000000
0001000000000002000
0000000000000000000
0000100000000000000
0001010000000000000
0000100000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0000000000000000000
0002000000000001000
0000000000000000000
0000000000000000000
0000000000000000000
1 0 2

(Note that although a white stone was captured, it counts as a prisoner for black.)
Your code must additionally satisfy the following properties:

If your program is given the same input state, it must always produce the same output. This is the determinism of the Go AI. It must not have a random component.
Your program must not take more than approximately 60 seconds to determine what move to make. This rule will not be strictly applied due to variations in computing power, but it must make a move in a reasonable amount of time.
Your program's source code must not exceed a total of 1 megabyte (1,048,576 bytes).
Your program must always make legal moves. Your program cannot make a move where a stone already exists, and cannot place a piece that would result in a group of its own stones being captured. (One exception to the rules for the purposes of this challenge is that a program is allowed to create a position that was originally there - because it is only given the current position of a board, it cannot be expected to store which moves had been made before.)

Your submission will then play in an all-play-all tournament against all the other submissions, in a game of Go where the state of the board begins as empty, and each program takes turns being fed the position of the board and making a move.
Each pair of submissions will play two rounds - one round with each player being black. Because the AIs in this problem are completely deterministic, two of the same AIs playing together will always result in exactly the same game being played.
Conditions for a win are as such:

If your program plays to the end of the game, the Chinese scoring rules of Go will be used to determine the winner. No komi will be applied.
If your program plays to the point that an earlier state is reached, thus causing an infinite loop, the two programs will be declared to have tied.

Your submission will be scored by how many points it scores against other submissions. A win is worth 1 point, and a tie is worth half a point. The submission with the most points is the overall winner.

This is a king-of-the-hill challenge, in which anybody can post a new entry at any time, and the standings will be re-evaluated periodically when this happens.

Note that pseudorandom processes are fair game, as long as they're still completely deterministic.

Ok, waiting for all other submissions and then write my own in order to beat them - should be possible since the solutions are deterministic.

@Howard I guess the winner will be the last person to tweak their random seed before the code freeze.

@shiona The catch there is that Go still has a bunch of strategy involved, unlike a game like Rock Paper Scissors. A completely randomized solution will still lose to an advanced algorithm, no matter how the seed is changed.

Sounds like you need a [king-of-the-hill] tag for this.

Oh. I kind of assumed that was what my [code-tournament] tag was for.

No point creating a new tag when there's one already in use.

I didn't know the [king-of-the-hill] tag existed, which is the only reason I created the [code-tournament] one.

The board representation is insufficient: how would the program recognise ko?

It seems playing in ko such that the previous position is repeated is allowed but leads to immediate draw (since it causes a loop). Interesting...

@JoeZ. I know, I've played some. It was an attempt of a retort towards Howards comment.

Looks like that your problem is too dificult and nobody would work hard enough to produce a worthful answer (it is really a lot of work). It is a nice problem, but go is way too hard to work with.

Yeah, that's true. I find myself struggling to even make a legal move function.

Why not use a smaller board? 9x9 is common enough for beginner players. It cuts the search space down dramatically, but it's not so small that it's been "beaten" yet by analysis (I think the largest that's been fully solved is 5x6).

How does input work? stdin or command line arguments?

This problem needs a "driver" that will run 2 solutions against each other and determine the result

Do you really expect someone to develop a program able to play go? This has been tried for 40 years or so and the best attempts can be easily beaten by any moderately experienced player.

Well I think we could invite Google to this challenge.

Here is my entry to get this challenge off the ground. Python code:
print "pass"

According to your rules always playing "pass" is a valid (albeit bad) strategy.

Your code will always lose against anyone that makes any play against it. Still, nice base-case answer.

@JoeZ. And from the looks of it he won with it :P

Java : Pick a spot, any spot
Simply chooses spots on the board to test for validity. It uses the PRNG, but with a set seed so that's it's deterministic. It uses different chunks of the PRNG cycle depending on how many turns have passed.
For each candidate position, it checks to see that it's a valid move (but not that it's a smart move). If it isn't, it moves on to the next candidate. If it cannot find a valid move after 1000 tries, it passes.
import java.util.Random;
import java.util.Scanner;

public class GoNaive {

    int[][] board;
    boolean[] checked;
    int me;

    public static void main(String[] args) {
        new GoNaive().run();
    }

    void run(){
        int turns = init();
        Random rand = new Random(seed);

        for(int i=0;i<turns*tries;i++)
            rand.nextInt(size*size);

        for(int i=0;i<tries;i++){
            int pos = rand.nextInt(size*size);
            for(int c=0;c<size*size;c++)
                checked[c]=false;
            if(board[pos%size][pos/size] == 0)
                if(hasLiberties(pos, me)){
                    System.out.print((pos%size+1) + " " + (pos/size+1));
                    System.exit(0);
                }
        }
        System.out.print("pass");
    }

    boolean hasLiberties(int pos, int color){
        if(checked[pos])
            return false;
        checked[pos] = true;

        int x = pos%size, y=pos/size, n;

        if(x>0){
            n = board[x-1][y];
            if(n==0 || (n==me && hasLiberties(y*size+x-1, color)))
                return true;
        }
        if(size-x>1){
            n = board[x+1][y];
            if(n==0 || (n==me && hasLiberties(y*size+x+1, color)))
                return true;
        }
        if(y>0){
            n = board[x][y-1];
            if(n==0 || (n==me && hasLiberties((y-1)*size+x, color)))
                return true;
        }
        if(size-y>1){
            n = board[x][y+1];
            if(n==0 || (n==me && hasLiberties((y+1)*size+x, color)))
                return true;
        }
        return false;
    }

    int init(){
        int turns = 0;
        board = new int[size][size];
        checked = new boolean[size*size];
        turns = 0;
        Scanner s = new Scanner(System.in);
        String line;
        for(int i=0;i<size;i++){
            line = s.nextLine();
            for(int j=0;j<size;j++){
                board[j][i] = line.charAt(j)-48;
                if(board[j][i] > 0)
                    turns++;
            }
        }
        String[] tokens = s.nextLine().split(" ");
        turns += Integer.valueOf(tokens[0]);
        turns += Integer.valueOf(tokens[1]);
        me = Integer.valueOf(tokens[2]);
        s.close();
        return turns;
    }

    final static int size = 19;
    final static int seed = 0xdeadface;
    final static int tries = 1000;
}

Some Scala:
package go;

class Go {
  def main(args : Array[String]) {
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    System.out.printLn("1 1")
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    readLine()
    System.out.printLn("pass")
  }
}

From reading Wikipedia, I think this will beat the current solution.

In fact, it will win by 361 points in both cases.

Actually, I'll have to take that back, it doesn't follow spec. The AI is supposed to be stateless. It's only actually supposed to print one thing given the state of the board, and you've made it print two (1 1 and pass).

@JoeZ. Fixed it. Wouldn't have compiled anyway.

That will always print 1 1, actually, since the program is always run anew every time the board changes.

Java
public class Go {
  public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    for (int i = 0; i < 361;) {
      char c = s.nextChar();
      if (c != '\n') {
        if (c == '0') {
          System.out.println((i % 19 + 1) + " " + (i / 19 + 1));
          System.exit(0);
        }
        i++;
      }
    }
  }
}

Chooses the first empty space. Wins against any of the AIs as of time of posting.

This doesn't guarantee a legal move. If the first available space has no liberties, it can't be played. For instance, if this AI played itself: After the first row of alternating pieces, 1 1 would be captured by white (now empty) and could not be played by black on the next turn.


text:
Create a programs that counts the 0's in numbers from 0 to a billion
This will be my very first post on stackexchange so bear with me.
Create a program that counts from 0 to 1,000,000,000.
Now the trick is to not print all these characters but to only print how many zeroes are in that number. And keep track of the total amount of zeroes you've encountered. For example
10

Will output;
1
2

because 10 has 1 zero in it. The two represents how many 0's you've seen in total, in this case the only zero you have encountered previously is 0 itself so you've seen a total of 2 zeroes.
The highest score will be given to the shortest code (no surprise here).
I hope that this is not too easy and that I've posted enough information, given the fact that I'm completely new here I'm not entirely sure about this.

You should have posted it in the sandbox if you weren't sure about that question. Remove your code-challenge tag, and that should be ok.

This is similar to Count the zeros, differing only in two things: 1. shortest code rather than fastest - but given the length of some of the answers there this is a significant difference; 2. lack of parameter. It's generally a bad idea to hard-code the parameters in the question, because the shortest answer will usually be one which prints the solution without doing any real work.

It's not clear from your question if you want the number of zeroes for a single entry (and all zeroes up to that point), or for all numbers in a given range. Could you please clarify?

The program counts to 1000,000,000 and with every number it has to calculate the number of zeroes in the current number and add them to the total amount of zeroes that is has seen. Then it moves on the the next number hand repeats this process until it reaches a billion. The final output should be 9, 788888899.

Hi Sofa.  Since you were asking for feedback, here's mine:  1) don't tell golfers how to write their algorithms (that removes some of the joy of coding, doesn't it?), and 2) heed @PeterTaylor's advice and parameterize the question with n to prevent a submission of something like this:  puts 9, 788888899.

Python (brute force, 80 chars)
def r(n):
    l=[str(i).count('0') for i in xrange(n+1)]
    return l[-1],sum(l)

Just to asure, i got the task right, it evaluates to:
r(10)
>>> (1, 2)
r(1000000000)
>>> (9, 788888899)

You can make it even shorter by using i instead of str(i). I can't type the needed code, since it uses the char, that declares code on StackExchange. You have to surround i with ``

@user14325 You mean \i`? (This is how I typed that: "You mean `\i\\`?`")

similar def s(n):  print \n`.count('0'), sum(`i`.count('0') for i in xrange(n+1))` cuts to 67 chars

that is what i meant. Or even shorter: replace xrange by range. This makes the function slower  but fast code is not the target here.

@user14325 thanks, didn't know that one with \i`! However, using rangeI would consider cheating, as it won't work forr(1000000000)`.

(Oracle) SQL, 146 144 chars / 122 chars
SELECT*FROM(SELECT l,SUM(REGEXP_COUNT(l,'0'))d FROM(SELECT LEVEL-1l FROM dual CONNECT BY LEVEL<=&a+1)GROUP BY ROLLUP(l))WHERE &a=l OR l IS NULL;

Expanded:
SELECT *
FROM (
   SELECT
      l,
      SUM(REGEXP_COUNT(l, '0')) d
   FROM (
      SELECT LEVEL - 1 l
      FROM dual
      CONNECT BY LEVEL <= &a + 1
   )
   GROUP BY ROLLUP(l)
)
WHERE &a = l
   OR l IS NULL;

Edit: no need to name the column, and * doesn't need spaces around it.

Okay, so we need it for all numbers from 0 to n. Let me put on my thinking cap... Try
SELECT c,SUM(c)OVER(ORDER BY l)FROM(SELECT l,REGEXP_COUNT(l,'0')c FROM(SELECT LEVEL-1l FROM dual CONNECT BY LEVEL<=&a+1));

Expanded:
SELECT
   c,
   SUM(c) OVER(ORDER BY l)
FROM (
   SELECT
      l,
      REGEXP_COUNT(l, '0') c
   FROM (
      SELECT LEVEL - 1 l
      FROM dual
      CONNECT BY LEVEL <= &a + 1
   )
);

C, 90 bytes
r;i;j;main(t){for(;i<=10e8;j=++i){for(r=0;j;j/=10)j%10||r++;t+=r;}printf("%d\n%d\n",r,t);}

ungolfed:
r;i;j;main(t) {
    for (;i<=10e8;j=++i) {
        for (r=0;j;j/=10)
            j%10||r++;
        t+=r;
    }
    printf("%d\n%d\n",r,t);
}

you can save some characters by changing ?0: to || and by moving j=i from inner loop's init into outer's loop increment (j=i++)

Why is this the accepted answer? The Python solution is shorter, and in general there is no accepted answer in questions like these, just scores in different languages.

@mniip, cool thanks! Made the changes that you suggested.

GolfScript 34 32
0 10.(?,{`{48=},,}%{(.p@+.p\.}do

Explanation:
The initial 0 will be the counter for the number of 0s seen thus far.  A billion is 10^9, and 10.(? generates a billion by taking 10, copying it, decrementing, and then exponentiating.  The , then generates an array of all numbers for 0 to a billion - 1.  If we need to include one billion, add a ) before the ,.
The next block takes a number, converts it to a string by doing ''+, then filtering down to the characters that equals '0' (ASCII value 48) by doing {48=}, and then counting the length of the array by doing ,.  Map this block across all the numbers in our array with %.
The next block expects two elements on the stack: the total 0s seen, and then the array of 0-counts for each integer not yet printed.  Each time the block is executed it pops the first element of the array with (, copies and then prints it with .p, moves the total counter to the front with @, adds the current number, and then rearranges the stack to be in the right order.  The do will run this block until the array is empty.

int ''+ is just `int ``, saving two.

@PeterTaylor Good catch!

APL (30)
Brute-forced. There is no lazy evaluation, so it generates the whole list from 0 to 1e9 at once. So you need at least a 7GB workspace, or it will just say WS FULL.
In case you don't have a huge server to use, the program can be proven to work by lowering 1e9 to a saner amount.
(⊃⌽Z),+/¯1↓Z←{'0'+.=⍕⍵}¨0,⍳1e9

Explanation:

0,⍳1e9: the list from 0 up to and including 1e9
Z←{'0'+.=⍕⍵}¨: count the zeroes in each number, and store the list in Z.
+/¯1↓Z: the sum of all but the last item in Z (the total amount of zeroes encountered)
⊃⌽Z: the last item in Z (the amount of zeroes in 1e9).

C# - 223 chars:
using System.Linq;class P{static void Main() { G(10); } static void G(int i){System.Console.Write("{0},{1}",i.ToString().Count(l => l == '0'),Enumerable.Range(0, i + 1).SelectMany(b => b.ToString()).Count(l => l == '0'));}}

Expanded:
using System.Linq;
class P
{
    static void Main() { G(10); }
    static void G(int i)
    {
        System.Console.Write("{0},{1}",
            i.ToString().Count(l => l == '0'),
            Enumerable.Range(0, i + 1).SelectMany(b => b.ToString()).Count(l => l == '0'));
    }
}

Python 81 chars
def x(y):
    o=0
    for i in xrange(y+1):
        o+=`i`.count('0')
    print `y`.count('0'),o

I can't vote up yet, so I wanted to say that I really like this one.

fix indentation, also get rid of extra white-spaces.

@Alkis, please fix it... it's not working.

Fixed it! Sorry

J (33)
Warning: uses an ungodly amount of memory.
({:,+/@}:)(+/@('0'=":))"0 i.1e9+1

Explanation:

i.1e9+1: generate a list of numbers from 0 up to and including 1e9.
(+/@('0'=":))"0: for each number ("0), convert it to a string (#:), and see how many zeroes there are ('0'=).
({:,+/@}:): display the last item in the list ({:), followed by the sum of all but the last item in the list (+/@}:)

I'm confused here.  I hear tell that god is omniscient -- so a large amount of memory ought be godly.  Are you warning us that this is memory efficient?