text:
Calculate a pi-based sequence with a pi-based frequence
Introduction
Pi is
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089...

Let's treat each digit as an instruction as to how to get to the next digit.

The first digit is 3.
Counting three digits after the first digit, we arrive at 1.
One digit after this 1 is a 5.
Five digits after that is 3.
Three digits later is 9.

The digits included in this sequence are in bold: 3.1415926535897932384626433...
If a digit is 0, the next digit is 10 later.
Challenge
Given a positive integer n less than 1000, find out how many of the first n digits of pi, including the initial 3, are in the sequence.
Furthermore, your code's characters must have a "pi-based frequency". Choose any character; your program must use exactly three of that character. Choose another character, use exactly one of it. Choose another character, use it four times. You may continue for as long as you wish, but each character chosen must be different.
For example, the following snippet complies with the frequency rules (but produces the wrong output):
print "r\"rriiiittttnttttppppp"
# Uses 3 quotation marks, 1 space, 4 r's, 1 \, 5 i's, 9 t's, 2 n's, and 6 p's.

For the purposes of "pi-based frequency", treat the digit 0 as 10.
You may write a function or a full program. You may not use any built-in constants, trigonometry functions, or complex number functions to find pi.
Shortest code in characters wins. The tiebreaker is the most votes.
Examples
Input  Output
-------------
 1      1
 2      1
 3      1
 4      2
 5      3
 28     8
 77     17
 123    28
 328    73
 625    122
 999    189

Hardcore level - over 9000!

The source limitations makes the max length of the program to be 521 characters (counting just he printable ASCII range)

I know. Just saying.

Mathematica, 253 bytes
f=(For[i=0;j=1,j<=#,j+=Mod[RealDigits[9801/Sqrt@8/Sum[(4j)!(1103+26390j)/(j!)^4/396^(4j),{j,0,125}],10,999][[1,j]]-1,10]+1;++i];"99iiiitS===oooo8862^^^^^^\uusRRRRRRqqqqqqqqMMMMmlllllllgggggggFFFeeeeeeeeDDDDDDaaaaa55555555<<{{\{{{{{{}}}}}}}}--@@@@@@";i)&

Ungolfed:
f = (
   For[i = 0; j = 1, j <= #,
    j += Mod[
       RealDigits[
          9801/Sqrt@8/
           Sum[(4 j)! (1103 + 26390 j)/(j!)^4/396^(4 j), {j, 0, 125}],
           10, 999][[1, j]] - 1, 10] + 1; ++i];
   "99iiiitS===oooo8862^^^^^^uusRRRRRRqqqqqqqqMMMMmlllllllgggggggFFFeeeeeeeeDDDDDDaaaaa55555555<<{{{{{{{{}}}}}}}}--@@@@@@";
   i
   ) &

Usage is f[999].
A whopping 122 bytes are used to pad the code with a useless string to get the right character frequencies. I'll try to improve that tomorrow.
The character frequencies should match the digits of pi in this order:
3#/&(,![)4+9j0it"S=;]ro862^usRqM1mlgFfeDda5<{}-@

I confirmed that there is some correct order with the following snippet:
Sort[Last /@
   Tally[Characters@
     "f=(For[i=0;j=1,j<=#,j+=Mod[RealDigits[9801/Sqrt@8/Sum[(4j)!(\
1103+26390j)/(j!)^4/396^(4j),{j,0,125}],10,999][[1,j]]-1,10]+1;++i];\"\
99iiiitS===oooo8862^^^^^^\
uusRRRRRRqqqqqqqqMMMMmlllllllgggggggFFFeeeeeeeeDDDDDDaaaaa55555555<<{{\
{{{{{{}}}}}}}}--@@@@@@\";i)&"]] ==
 Sort[RealDigits[Pi, 10, 48][[1]] /. 0 -> 10]

I'm computing pi with Ramanujan's series. It converges to 1000 digits in 125 terms. Due to golfing reasons, I recompute the 999 necessary digits for every single digit of the subsequence, but it still completes within a second for n = 999 on my machine.

C++, 550 428
#include<iostream>
long a[3505],b,c=3505,d,e,f=10000,g,h,i,j,k,l,x,z;int main(){int P[1000];int M[4];for(;(b=c-=14)>0;){for(;--b>0;){d*=b;if(h==0)d+=2000*f;else d+=a[b]*f;g=b+b-1;a[b]=d%g;d/=g;}h=e+d/f;i=h;for(j=0;j<4;j++){M[j]=i%10;i/=10;}for(j=3;j>=0;j--){P[z]=M[j];z++;};d=e=d%f;}std::cin>>k;j=0;while(j<k){x=P[j];(x==0)?x=10:x;j+=x;l++;}std::cout<<l;}//{{{:+-2220000%,ddhhhhiiiiiiijjnorrt, # # # ,MQQQRRRSSSSSSSSTTTTTTTTT:}}}

I'm not 100% confident that my code has a π-based frequence. I will check tomorrow. If it works, there is a direct correspondance between the frequencies of the following characters and the 60 first digits of π.
  zdj(mxakcb)1[*uPes>0M34t;l]g+=n%wo-,hQ{}Rr<f/Si :sT#2
  3.141592653589793238462643383279502884197169399375105820974944

The craziest part is the computation of π. It is done thanks to an implementation of a fascinating spigot algorithm:

Edit: you can generate n digits of π with this 288 characters-long program: :)

#include<iostream>
#include<vector>
using namespace std;long b,c,d,e,f=10000,g,h,l;int main(){cout<<"? ";cin>>l;cout<<": ";l=(l/4+1)*14;c=l;vector<long> a;a.resize(l);for(;(b=c-=14)>0;){for(;--b>0;){d*=b;if(h==0)d+=2000*f;else d+=a[b]*f;g=b+b-1;a[b]=d%g;d/=g;}h=e+d/f;cout<<h;d=e=d%f;}}

source: Stack Exchange

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

authors: سيف رحمان مومن

sort: votes


text:
It's Spanish Time!
I have a simple task that should be relatively easy to implement by means of code. Your goal is to write a program that will output the time written in Spanish, given the time in HH:MM format. Many people likely don't know how to do this, so I will elaborate.
Time in Spanish is fairly logical. It usually follows the pattern of "Es la/Son las (hour) y (minutes)." Hours are in a 12-hour format, and "Es la" is only used if the hour is 1 (i.e. one o'clock). The minutes are a different story. If the minute is less than 30, then it is represented as shown above. If the minute is over 30, however, then the hour is rounded up and the minute is subtracted. For example, 7:35 is translated to the equivalent of "8 hours minus 25 minutes." Some more examples will be given below. The list of Spanish numbers that are necessary can be found here. There are accents on some numbers, but these are not necessary.
Note: The source says "uno," but to be grammatically correct it should be "una." This shouldn't affect any answers so far.
Note 2: Also, "cero" is not necessary. If your program outputs "Es la una" or "Son las tres," that is fine with me. Sorry for these rule changes.
Rules

Input will be provided through STDIN or the equivalent in your language.
No reading from outside libraries.
Your code can do anything with invalid input.

Bonuses

-10 if your code adds these extra phrases - "y cuarto" for :15, "y media" for :30, and "menos cuarto" for :45 (rounded up).
-15 if your code can handle A.M. and P.M., responding with "de la mañana" and "de la tarde," accordingly.
-15 if your code can translate the current time if no input is provided.

Scoring

This is a code-golf challenge, and it will be scored by bytes, not characters.

Examples
Input: 8:10
Output: Son las ocho y diez.
Input: 6:45
Output: Son las siete menos quince (or cuarto).
Input: 1:29
Output: Es la una y veintinueve.
Input: 12:55
Output: Es la una menos cinco.
Let me know if there is anything to specify here. This is my first question, so it is definitely not perfect.

For your information, you can get feedback before you post at the sandbox.

I predict a negative score solution.

@StretchManiac I don't know how I never saw this. I've never really been active on PPCG, so I guess I haven't really looked at Meta enough.

@Sparr I doubt it. There are probably enough numbers that have to be hardcoded for this to happen - at least 45 characters worth, even accounting for patterns.

Shouldn't 12:55 be 1:55?

Also, the link you use has uno, and you are using una.

@hosch250 Es la una menos cinco, so it's 12:55. And thanks for pointing that out with the uno/una. I'll edit that now.

What should the output for 1:00 be? As a South American, I'd say Es la una (en punto).. As a code golfer, I'd say Es a una y cero..

@Dennis Hmm... I guess either would be fine. Es la una y cero is pretty repetitive, so I see your point. I didn't specify this, so I guess either one would be fine. Thanks for the feedback.

How should I input AM/PM?  Like HH:MM AM or HH:MMPM?

@hosch250 HH:MM AM, preferably. I know this makes it longer, but it makes more sense.

I thought this would be it.

My program has to wait for input, shouldn't I output the current time if they input 'now' instead?  Otherwise, it will always just output the current time without waiting for input.

Or should it be if they press 'Enter' without a time?

@hosch250 It should output the current time if the function is called without any arguments - so in your case, if they press 'Enter' without any input.

What is the expected output for 00:00?

What is the range of valid input? h==0? h>12?

And what about the full stop in examples? Is it part of requested output?

What to do about midday / midnight?

The universal answer to "What time is it": https://www.youtube.com/watch?v=1dQXhuey51M

You should add 01:21 as a test case, because at least one answerer was confused by what you said about una vs uno.

The second bonus is (almost?) never worth it because the phrases "de la", "manana" and "tarde" alone count up to 16 bytes already.

I know cero isn't nessesary, but if it makes my code shorter is it okay if I have it?

JavaScript (ES6) 308 316
Edit2 bug fix
Edit forgot to claim the bonus
As a program with I/O via popup
s='media0uno0dos0tres0cuatro0cinco0seis0siete0ocho0nueve0diez0once0doce0trece0catorce0cuarto0dieci0veint'.split(0),
N=n=>n<16?s[n]:n<20?s[16]+s[n-10]:n>29?s[0]:s[17]+(n>20?'i'+s[n-20]:'e'),
[h,m]=prompt().split(':'),
alert(((h=(10-~h+(m>30))%12)?'Son las '+N(1+h):'Es la una')+(m>30?' menos '+N(60-m):-m?' y '+N(~~m):''))

As a testable function
F=t=>(
  s='media0uno0dos0tres0cuatro0cinco0seis0siete0ocho0nueve0diez0once0doce0trece0catorce0cuarto0dieci0veint'.split(0),
  N=n=>n<16?s[n]:n<20?s[16]+s[n-10]:n>29?s[0]:s[17]+(n>20?'i'+s[n-20]:'e'),
  [h,m]=t.split(':'),
  ((h=(10-~h+(m>30))%12)?'Son las '+N(1+h):'Es la una')+(m>30?' menos '+N(60-m):-m?' y '+N(~~m):'')
)

Test In FireFox/FireBug console
for(i=0;i<13;i++)
{
   console.log(F(i+':'+i)+'. '+F(i+':'+(i+15))+'. '+F(i+':'+(i+30))+'. '+F(i+':'+(i+45)))
}

Output
Son las doce. Son las doce y cuarto. Son las doce y media. Es la una menos cuarto
Es la una y uno. Es la una y dieciseis. Son las dos menos veintinueve. Son las dos menos catorce
Son las dos y dos. Son las dos y diecisiete. Son las tres menos veintiocho. Son las tres menos trece
Son las tres y tres. Son las tres y dieciocho. Son las cuatro menos veintisiete. Son las cuatro menos doce
Son las cuatro y cuatro. Son las cuatro y diecinueve. Son las cinco menos veintiseis. Son las cinco menos once
Son las cinco y cinco. Son las cinco y veinte. Son las seis menos veinticinco. Son las seis menos diez
Son las seis y seis. Son las seis y veintiuno. Son las siete menos veinticuatro. Son las siete menos nueve
Son las siete y siete. Son las siete y veintidos. Son las ocho menos veintitres. Son las ocho menos ocho
Son las ocho y ocho. Son las ocho y veintitres. Son las nueve menos veintidos. Son las nueve menos siete
Son las nueve y nueve. Son las nueve y veinticuatro. Son las diez menos veintiuno. Son las diez menos seis
Son las diez y diez. Son las diez y veinticinco. Son las once menos veinte. Son las once menos cinco
Son las once y once. Son las once y veintiseis. Son las doce menos diecinueve. Son las doce menos cuatro
Son las doce y doce. Son las doce y veintisiete. Es la una menos dieciocho. Es la una menos tres

Yes, the least expected language to appear on a golf contest, coded by the world's worst golfer, is back!
Java - 676 bytes (716-10-15-15)
Golfed:
class A{void main(String[]a){java.util.Calendar c=java.util.Calendar.getInstance();int h,m;String s="";h=c.get(c.HOUR);m=c.get(c.MINUTE);String[]e={"doce","una","dos","tres","quatro","cinco","ses","siete","ocho","nueve","diez","once","doce","trece","catorce","quarto","çseís","çsiete","çocho","çnueve","xe","xiuno","xidós","xitrés","xiquatro","xicinco","xiséis","xisiete","xiocho","xinueve","media"};for(int i=0;++i<30;e[i]=e[i].replace("ç","dieci"),e[i]=e[i].replace("x","vient"));s+=(h==1&m<30|h==12&m>30)?"Es la ":"Son las ";s+=(m<=30)?e[h]:(h==12&m>30)?e[1]:e[h+1];s+=(m==0)?" certas":(m<=30)?" y "+e[m]:" menos "+e[60-m];s+=(c.get(c.AM_PM)==0)?" de la mañana.":" de la tarde.";System.out.println(s);}}

Ungolfed:
public class A {

    public static void main(String[] a) {
        java.util.Calendar c = java.util.Calendar.getInstance();
        int h, m;
        String s = "";
        h = c.get(c.HOUR);
        m = c.get(c.MINUTE);
        String[] e = {"doce", "una", "dos", "tres", "quatro", "cinco", "ses", "siete", "ocho", "nueve", "diez", "once", "doce", "trece", "catorce", "quarto", "çseís", "çsiete", "çocho", "çnueve", "xe", "xiuno", "xidós", "xitrés", "xiquatro", "xicinco", "xiséis", "xisiete", "xiocho", "xinueve", "media"};
        for (int i = 0; ++i < 30; e[i] = e[i].replace("ç", "dieci"), e[i] = e[i].replace("x", "vient"));
        s += (h == 1 & m < 30 | h == 12 & m > 30) ? "Es la " : "Son las ";
        s += (m <= 30) ? e[h] : (h == 12 & m > 30) ? e[1] : e[h + 1];
        s += (m == 0) ? " certas" : (m <= 30) ? " y " + e[m] : " menos " + e[60 - m];
        s += (c.get(c.AM_PM) == 0) ? " de la mañana." : " de la tarde.";
        System.out.println(s);
    }
}

Deals with the quarto and media, with the AM/PM and has no input. So I can claim all the bonuses, even though that, if I didn't implement those features, I'd have an even lower score, lol. facepalms

Python 3: 294 chars - 10 = 284
h,m=map(int,input().split(':'))
t="y"
d="yunoydosytresycuatroycincoyseisysieteyochoynueveydiezyonceydoceytreceycatorceycuarto".split(t)*2
if m>30:h=h%12+1;m=60-m;t="menos"
print(["Es la una","Son las "+d[h]][h>1],t,[d[m]or"cero",["dieci","veint"+'ei'[m>20],"media"][m//10-1]+d[m%10]][m>15]+".")

This gets the ten-point bonus for using "cuarto" and "media"
We read the hours and minutes as ints. If the minutes are above 30, we move to the next hour, measure minutes away from 60, and change the conjunction to "menos".
The list d has translations of Spanish numbers up to 15. We make d[0] be '' to prevent things like "diecicero". This is done by awkwardly calling split(' ') with an initial space; the regular split would just ignore it. The zero-minute case is handled later.
To get numbers above 15, we combine the tens-digit string with the appropriate one-digit string. 15 and 30 are written as "media" and "cuarto" at no cost.
Python 3 saves one char net over Python 2: -4 for input instead of raw_input, +2 for parens in print, +1 for //.

I'm sad to say that it's more complicated than that. 01:21 should be la una y veintiuno because hours are feminine but minutes are masculine.

@PeterTaylor I see. Is uno/una the only number affected?

Yes, although if it went up to numbers in the hundreds there would be others.

@PeterTaylor Fixed, for 5 chars.

@edc65 Whoops, I forgot to paste in the actual change of una to uno, should work now.

Fixed a bug where 20 was veinti rather than veinte. Up to 286 now.

You can save a couple characters by using "y" as a delimiter in d, because it's already saved to a variable.

@isaacg That's really cute, thanks. I edited it in.

C++: 474 ... 422 411 bytes
This version is redeeming the cuarto/media bonus (-10).
#include<cstdlib>
#include<cstdio>
int main(int u,char**v){char*b[]={"cero","una","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","once","doce","trece","catorce","cuarto","dieci","veinti","media",0,"veinte"};int h=atoi(v[1]),m=atoi(v[1]+2+(v[1][2]>57)),n=m>30,o;h=n?h%12+1:h;m=o=n?60-m:m;if(u=m>15&m!=20)o=m%10;printf("%s %s %s %s%s",h>1?"Son las":"Es la",b[h],n?"menos":"y",u?b[m/10+15]:"",b[o?o:m]);}

My first attempt ever at code golfing! Will try to improve it this weekend.
Ungolfed:
#include<cstdlib>
#include<cstdio>
int main(int u,char**v)
{
char*b[]={"cero","una","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","once","doce","trece","catorce","cuarto","dieci","veinti","media",0,"veinte"};
int h=atoi(v[1]),m=atoi(v[1]+2+(v[1][2]>57)),n=m>30,o;
h=n?h%12+1:h;
m=o=n?60-m:m;
if(u=m>15&m!=20)o=m%10;
printf("%s %s %s %s%s",h>1?"Son las":"Es la",b[h],n?"menos":"y",u?b[m/10+15]:"",b[o?o:m]);
}

Couldn't you m%=10

Good point! Unfortunately in my new revision I have to assign that value to a different variable, so I can't.

Ok, just wondering :)

401 bytes

PHP, 351 349 360 - 15 = 345 Bytes
<?$a=split(~ß,~œšßŠ‘ß›Œß‹šŒßœŠž‹ßœ–‘œßŒš–ŒßŒ–š‹šßœ—ß‘Šš‰šß›–š…ß‘œšß›œšß‹šœšßœž‹œšßŽŠ–‘œšß›–šœ–ß‰š–‘‹–ß‹š–‘‹ž)?><?=preg_filter(~Ð×ÑÔÖÅ×ÑÔÖÐš,'(($h=($1-($k=$2<31))%12+1)>1?~¬‘ß“žŒß:~ºŒß“žß).$a[$h].($k?~ß†ß:~ß’š‘Œß).(($m=$k?$2+0:60-$2)<16?$a[$m]:($m<20?$a[16].$a[$m%10]:($m<21?viente:($m<30?$a[17].$a[$m%10]:$a[18])))).~Ñ',$_GET[0]?:date(~·Å–));

This program is not command line: it takes input via $_GET[0]. You may have to disable notices in your php.ini. Now comes with auto time with no input, thanks to Niet the Dark Absol.
Tricks used:
~(...) saves one byte by bitwise inverting a string, as you don't need quote marks as PHP usually assumes all ASCII from 0x80 to 0xFF is a string.
<?=preg_filter(...,...): The <?= is a shortcut for writing <? echo. preg_filter() usually applies replacements on a string using a regex, but we can use the depreciated /e modifier to evaluate the resulting string as PHP code. Hence, instead of having to split the input string into two separate variables, we can use backreferences ($1 and $2) on the matched input string, saving large amounts of bytes.

You can claim the -15 bonus if you use $_GET[0]?:date(~·Å–) to subtract 3 from your score.

Thanks. I have made that and one other minor improvement.

Lua, 450 - 10 (cuarto/media) - 15 (manana/tarde) = 425
n={'uno','dos','tres','cuatro','cinco','seis','siete','ocho','nueve','diez','once','doce','trece','catorce','cuarto',[20]='veinte',[30]='media'}for i=1,9 do n[i+10]=n[i+10]or'dieci'..n[i]n[i+20]='veinti'..n[i]end H,M=io.read():match('(%d+):(%d+)')H,M=H+0,M+0 X,Y='tarde',' y 'if H<12 then X='manana'end if M>30 then H,M,Y=H+1,60-M,' menos 'end H=(H-1)%12+1 S=H==1 and'es la una'or'son las '..n[H]if M>0 then S=S..Y..n[M]end S=S..' de la '..X print(S)

Dropped 12 bytes by rewriting the generator for 21-29.
Dropped 1 more by replacing H>=12 with H<12 and switching the dependent expression around.
Dropped 4 more by polluting the global namespace from a function (evil, but in the interest of golfing :).
Fixed the regex, I forgot the colon.  Doesn't change the byte count, however.
Fixed the case of zero minutes, swapped table.concat out for string ops, and added @edc65's suggestion, ultimately adding 22 bytes.
I am shamed. Pulling the function body out into the main chunk reduced the length by a whopping 15 bytes.

Should use 'una' for hours, 'uno' for minutes. So '01:01' should give Es la una y uno

Python 3, 409 bytes
d='cero uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciseis diecisiete dieciocho diecinueve veinte xuno xdos xtres xcuatro xcinco xseis xsiete xocho xnueve treinta';d=str(d.replace('x','veinti')).split();t=input().split(':');i=int(t[1]);j=int(t[0]);print(["Son las","Es la"][1<(2*j+i/30)%24<=3],[d[[j%12+1,j][i<31]],'una'][j==1],'y'if i<31 else'menos',d[min(i,60-i)])

A long list of strings can be shortened like 'string1 string2 string3'.split()

@xnor Alright, thanks!

@hosch250 Also, make sure you're following the comments in the original post again. I will likely be making many minor rule changes, and these will probably help you golf.

@mdc32 Adjusting right now.  I had some errors anyway.

You can shorten d[j]if i<31 else d[(j+1)%12] to d[(j+(i>30))%12]. In general, if your two alternatives has a similar structure, you can often make a simple expression that equals each respective one depending on the Boolean.

Golfed 4 bytes, if it conflicts please notify me.

@xnor No I can't.  That returns 'cero' for 12, and it should be 'doce'.  My way returns 'doce'.  I did shorten it somewhat.

@hosch250 Then maybe I'm not understanding the spec. Can cero never be the hour? For 11:45, yours returns Son las cero menos quince.

@xnor Ugh! that should be Son las doce menos quince.

@hosch250 Look like you fixed it. It's still shorter though to do [j%12+1,j][i<31]in place of j if i<31 else j%12+1. If general, it's best to avoid the if/else ternary unless you need to short-circuit evaluating the wrong option.

Should use 'una' for hours, 'uno' for minutes. So '01:01' should give Es la una y uno

@edc65 Thanks, I changed it.

D - 484 bytes
import std.stdio,std.conv,std.string;void main(){auto n="cero una dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce quince dieciséis diecisiete dieciocho diecinueve e iuno idos itres icuatro icinco iseis isiete iocho inueve treinta".split;auto p=stdin.readln()[0..$-1];int b=to!int(p[0..$-3]),a=to!int(p[$-2..$]);auto c=a;b=a>30?b+1:b;b%=12;a=a>30?60-a:a;writefln("%s %s %s %s", b==1||b==12?"Es la":"Son las",n[b],c>30?"menos":"y",(a/10==2?"vient":"")~n[a]);}

Should use 'una' for hours, 'uno' for minutes. So '01:01' should give Es la una y uno

Ruby, 313 (338 - 15 - 10)
This solution translates the current time when no input was given and adds the three phrases "y cuarto", "y media" and "menos cuarto".
require'time'
t,x,s=Time,$*[0],%w[cero una dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce cuarto]
1.upto(9){|i|i>5?s[10+i]="dieci"+s[i]:0;s[20+i]="veinti"+s[i]}
s[20]="veinte"
s<<"media"
c=x ?t.parse(x):t.new
h,m=c.hour%12,c.min
m<31?(a=" y "):(h,m,a=h+1,60-m," menos ")
$><<(h<2?"Es la ":"Son las ")+s[h]+a+s[m]

Does it work? Tried in ideone, input '01:01', current time 20:09, output: Son las ocho y diecioch

All the test cases passed for me locally. I see something went wrong with copying the numbers, so I'll fix that.

"seite" should be "siete" and "neuve" should be "nueve"

Perl - 297 - 10 + 1 = 288 (counting the p flag)
Edit: thanks to @guifa, I can now claim a bonus :)
#!/usr/bin/perl -p
sub n{($_=shift)%10?(once,doce,trece,catorce,cuarto)[$_>9?$_-11:5]||('',dieci,veinti)[$_/10].(0,un.pop,dos,tres,cuatro,cinco,seis,siete,ocho,nueve)[$_%10]:(cero,diez,veinte,media)[$_/10]}/:/;$a=$`%12;$b=$';$c=$b>30?(++$a,$b=60-$b,menos):'y';$_=($a-1?'Son las ':'Es la ').n($a,a)." $c ".n($b,o).'.'

Here is the same code in multiple lines for readability:
sub n {
        ($_ = shift) % 10
            ? (once, doce, trece, catorce, cuarto)[$_ > 9 ? $_ -11 : 5]
                || ('', dieci, veinti)[$_ / 10]
                . (0, un.pop, dos, tres, cuatro, cinco, seis, siete, ocho, nueve)[$_ % 10]
            : (cero, diez, veinte, media)[$_ / 10]
}
/:/;
$a = $` % 12;
$b = $';
$c = $b > 30 ? (++$a, $b = 60 - $b, menos) : 'y';
$_ = ($a - 1 ? 'Son las ' : 'Es la ') . n($a, a) . " $c " . n($b, o) . '.'

Should use 'una' for hours, 'uno' for minutes. So '01:01' - should give Es la una y uno

If you just change "quince" to "cuarto" and "treinta" to "media", you'll nab a -10 bonus.

@edc65 I hope It is OK now...

Bash 423
(433 - 10 = 423, removing diacritics and cuarto we could go down to 381)
IFS=: read h m
s=y
m=${m#0}
[ $m -gt 30 ]&&h=$(($h+1))&&s=menos
[ -z ${m%0} ]&&s=en&&m=punto
n[0]=0
o[0]=0
S=" séis siete ocho nueve"
n=(punto una dos trés cuatro cinco $S diez {on,do,tre,cator,quin}ce ${S// / dieci} veinte)
n=($(eval echo "${n[@]}" veinti\$\{n[{1..9}]\}))
n[3]=tres;n[6]=seis
n=(${n[@]} media\  $(tac -s' '<<<${n[@]}))
o=("${n[@]/q*/cuarto}")
a=Son\ las
[ $h = 1 ]&&a=Es\ la
echo $a ${n[$h]/p*/cero} $s ${o[$m]/%a/o}

It already uses 'una' for hours and 'uno' for minutes. Look more carefully :)

Sorry, it's not clear at a glance and bash is difficult to test in windows. +1 then.

@edc66, the ordinals are in femenine, then ${o[$m]/%a/o} replaces the trailing a with o for the minutes.

Scala 652 bytes - 25
import java.util.Scanner
object S extends App{val s=new Scanner(System.in).useDelimiter("[:\n]")
var h=s.nextInt
var m=s.nextInt
if(m>30)m-=60 else h-=1
val n=m.abs
h%=24
val p=h%12
val l=List("una","dos","tres","cuatro","cinco","seis","siete","ocho","nueve","diez","once","doce","trece","catorce","cuarto")
val k=List("úno","dós","trés",l(3),l(4),"séis",l(6),"ócho",l(8))
println(s"""${if(p==0)"Es la"else"Son las"} ${l(p)} ${if(m>0)"y "else if(m<0)"menos "}${if(n==1)"uno"else if(n==0)""else if(n<=15)l(n-1) else if(n==30)"media"else if(n<20)"dieci"+k(n-11)else if(n==20)"veinte"else"veinti"+k(n-21)} de la ${if(h<12)"mañana"else"tarde"}.""")}

Pyth: 277 a bunch more 234 - 10 (cuarto/media bonus) = 224 bytes
Now reduced over 50 bytes from original!
=H" y "ANkmsdcz\:Kc"cero uno dos tres cuatro cinco seis siete ocho nueve diez once doce trece catorce cuarto veinte"dI>k30=k-60k=H" menos "=N?1qN12+N1)++?+"Son las "@KN>N1"Es la una"H??eKqk20?@Kk<k16+?"dieci"<k21+PeK\i@K%kT<k30"media"

Insanely long for Pyth but that's because there's some raw data. Can probably be golfed even further. Uses obvious technique of splitting task up into hours, y/menos, tens digit of minutes, and ones digit of minutes and then translates numbers using translation array and everything else using a crap-ton of ternaries.
=H" y "                 Set H to " y "
A                       Double Assignment
 Nk                     The variables N and k (hours and mins)
 m  cz\:                Map input split by ":"
  sd                    Make both int
Kc"..."d                Set K to string split by spaces
I>k30                   If k>30
     =k-60k             Set k to 60-k
     =H" menos "        Set k to menos instead of y
     =N                 Set N
      ?   qN12          If N=12
       1                Go back to one
       +N1              Increment N
)                       Close entire if block
+                       Concat of hours and minutes
 +                      Concat hours and y/menos
  ?           >N1       If hour greater than one
   +                    Concat of son las and hour
    "Son las "          "Son las "
    @KN                 Index translation array for hour
   "Es la una"          Else es la una
  H                     " y " or " menos "
 ?               <k30   If minutes less than 30
  ?  qk20               If minutes is 20
   ek                   Last element of array (veinte)
   ?   <k16             Else check if minutes<16
    @Kk                 Get minutes directly from array
    +                   Else tens and ones sum
     ?       <k21       If minutes<21
      "dieci"           "dieci"
      +PeK\i            Else get veinti from veinte
     @K%kT              Ones digit of minutes
  "media"               Else get "media"

Golfing History

10 bytes - bonus, quince and trienta can just be replaced in translation array so no changes required except translation essay and its same size.
6 bytes - reorganized ternaries - unfortunately this removed the 4 consecutive ternary operators :(
6 bytes - other various golfing
6 bytes - golfed initial hour/min assignment
+3 bytes - fixed uno/una
3 bytes - constructed veinti from veinte, not hardcoded
18 bytes - extracted dieci from teens<16
2 bytes - removed some spaces in there for no reason
2 bytes - used \ for one char strings

For 1 character strings, such as ":" and "i", use \: and \i instead.

@isaacg oh cool I didn't know you could do that, updating

authors: ابو سراب حكمي حكمي

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


text:
Decompose a number with bit-xor without the digits 0, 3, 7
Challenge
Write a function or program which takes a positive decimal number, call it A, and output two positive numbers, B and C, such that:

A == B bitxor C
B and C must not contain any of the digits 0, 3 or 7 in its decimal representation.

Examples
>>> decompose(3)
1, 2
>>> decompose(7)
1, 6
>>> decompose(718)
121, 695
>>> decompose(99997)
2, 99999
>>> decompose(4294967296)
4294968218, 922
>>> decompose(5296080632396965608312971217160142474083606142654386510789497504098664630388377556711796340247136376)
6291484486961499292662848846261496489294168969458648464915998254691295448225881546425551225669515922,
1191982455588299219648819556299554251659915414942295896926425126251962564256469862862114191986258666

Since the decomposition is not unique, your function/program does not need to output the exact same results as these provided examples.
Very detailed rules

Submissions should be in the form of a complete function or program. import statements do count towards the final score.
You may assume the input A always contains at least a digit of 0, 3 or 7.
You may assume a decomposition always exist.
You may use BigInt if they are part of the standard libraries of the language, or can be installed through the language's de jure package manager.
The function should be fast. It should take no more than 20 seconds to run on reasonably modern computer when fed a 100-digit number, and no more than 2 seconds when fed a 10-digit number.
The function/program should support input up to at least 100 digits.

If the function/program can only support integers up to N<100 digits, there will be a penalty of +10×(100/N - 1) bytes to the final score. This is to encourage golfers to support a wider range of numbers even if importing may be verbose.

There is no restriction on the presentation of input/outputs as long as they are clearly in decimal representation.

The function may input and output strings/BigInts if the built-in integer types are not sufficient.
The input may come from the function parameter, command line argument or STDIN.
The function may return the result, or just print the result directly to STDOUT.
However, signed overflow in the input/outputs are not allowed.
Approximate answers are not tolerated, the input/outputs must be exact.

Scoring
This is a code-golf. Shortest solution in bytes win.
There is a penalty if the program can only support numbers less than 100 digits:

64-bit integers (19 digits) = +42 bytes
63-bit integers (18 digits) = +45 bytes
53-bit integers (15 digits) = +56 bytes
31/32-bit integers (9 digits) = +101 bytes

Are you sure such decomposition is always possible? Can you sketch me a proof?

Someone block 1, 5, 9 in the 95 Movie Quotes question then.

@JanDvorak I don't have a concrete proof, but consider probability: There are about 7^N numbers which does not contain 0, 3 or 7 with N digits. Thus, there are roughly 7^(2N)/2 pairs. And 7^(2N)/2 >> 10^N for all N. So as long as bitxor distributes the result uniformly, we should be pretty safe. (I do have a program for decomposition and I've yet to see any non-decomposable number).

100 digits? that means Python wins straight away, as it is the only commonly used language here that supports arbitrary precision integers. Why not 19 digits, which fits in a 64-but unsigned integer? (2^64= 18 446 744 073 709 551 616)

@steveverrill: Because the original problem that leads to this is based around a 98-digit number, sorry. Also, at least Ruby and Haskell support arbitrary-sized integer natively.

@steveverrill Mathematica... GolfScript... CJam...

You've caught me out there @MartinBüttner! :-) Maybe "only python" was an exaggeration. What I meant to say is that many people's favourite languages (OK, my favourite languages) are effectively excluded because they don't support arbitrary precision integers. Mathematica, Golfscript and CJam win everything anyway. But the last two tend to get less upvotes than other languages, because a lot of people can't understand the code.

And Java (had to say that)

@steveverrill What if we add a 8*(100/N) bytes penalty if the program can only support up to N digits (+42 bytes if you can only use uint64_t)? To compensate if C# programmers rushing from System.Numerics.BigInteger to ulong just to squeeze a few bytes out.

@KennyTM You can include it if you like, as it would make the question more inclusive. So the penalty for a 64-bit integer would be 800/19=42.1 bytes and for a 99-bit integer 800/99=8.08 bytes? I'm too busy / exhausted to answer anyway. Although I did like the idea of the question, and I have upvoted it.

@steveverrill actually I intended the penalty to be 0 for N=100, ~40 for N=19 and infinity for N=0. Updated the rule for that (seems too long though :\ )

@steverrill: and Julia, and many more

CJam, 70 bytes
ri:Q{;Qmr_Q^`1$`+730`&}g_Q^p

Try it online.
Randomly selects integers until it finds a match. This barely complies with the 20 second limit for 64-bit integers (using the Java interpreter), so I've added 42 to the actual byte count.
Example run
$ cjam t <<< 7777777777; echo
2695665494
6161166119

Common Lisp, 240 224 183 173 169 bytes
Common Lisp is a bit verbose for golfing. However, this decomposes 100-digit numbers in under a second, and 200-digit integers in less than ten seconds, so no need for penalties. The algorithm is deterministic.
(defun s(z)(and #1=(some(lambda(q)(position q(format()"~a"z)))"037")(+ z(floor z(expt 10 #1#)))))
(defun d(x)(do((y x(or(s y)(s #3=(logxor x y))(return`(,y,#3#)))))(())))

The line feed between the functions is for typographic purposes only. Test run with the 100-digit reference input:
(time (d 5296080632396965608312971217160142474083606142654386510789497504098664630388377556711796340247136376))
took 677,000 microseconds (0.677000 seconds) to run.
      20,989 microseconds (0.020989 seconds, 3.10%) of which was spent in GC.
During that period, and with 8 available CPU cores,
     671,875 microseconds (0.671875 seconds) were spent in user mode
           0 microseconds (0.000000 seconds) were spent in system mode
 54,221,104 bytes of memory allocated.
(1864921261592819619661568919418981552559955289196969112566252282429216186594265918444566258544614425
 5891958562486995519825158818455999516899524658151445485616155916296966645869599949958954491929662561)

As a bonus, I'm including a version of the code that incrementally builds the solution top-down. It can manage a 1000-digit number in less than ten seconds, but cannot compete in golf due to the additional code.
(defun decompose (x)
  (flet ((s (z)
           (mapcan #'(lambda (c) (and #1=(position c #2=(format () "~a" z))
                                 (list (- (length #2#) #1# 1))))
                   '(#\0 #\3 #\7))))
    (do ((y x (let ((p (nconc (s y) (s #3=(logxor x y)))))
                (or p (return`(,y,#3#)))
                (+ y (expt 10 (apply #'max p))))))
        (nil))))

* (time (decompose (parse-integer (make-string 1000 :initial-element #\7))))
took 9,226,000 microseconds (9.226000 seconds) to run.
        90,966 microseconds (0.090966 seconds, 0.99%) of which was spent in GC.
During that period, and with 8 available CPU cores,
     9,234,375 microseconds (9.234375 seconds) were spent in user mode
             0 microseconds (0.000000 seconds) were spent in system mode
 487,434,560 bytes of memory allocated.
(8889898889152488921298888992819221914229899249999918899888899888888889999989141219898898888988988898888888888899142442899924898918898898988988895189988898888924192198992454114198911989191888889898888918888988988998888891421118891899122898888998989898888898988898888999988918888898889189918889888888899888989219188898998888988892119889198888988888894888912188898989952999888888888898899998988898889228918998949999998898898991141888898999988912121292118899889998989899999892889941898888911888898889118998898888911889889888891452888998889288921141888888942189888899988891918889118888888888989892198899199914111188988889421111188889118888918989988912989999998989891119888898888888892621229888988888999619888952462219889189899998899888889989898891118989218888888898962988891188899888888888999888888888888888888888891269188921288888888998898899214191188888888898992188998898889919888889989889899988892115549998888898889218899988998911898989199918898918988898888891889888989119899888889888998918889112189998
 4184469818464841952189561886965821566229261221619858498284264289194458622668559698924621446851546256444641488616184155821914881485164244662156846141894655485889656891849662551896595944656451462198891289692696856414192264846811616261884188919426294584158925218559295881946496911489245664261126565546419851585441144861859822815144162828551969425529258169849412525611662488849586554989254181228254465226521648916188265491499166186964881248156451994924294646681548996645996894665198811511522424996844864211629888924642289925565591484541149414914699289441561496451494562955652129199261462268846144518142486845251946444998812988291119592418684842524648484689261441456645518518812265495165189812912919529151991611962525419626921619824496626511954895189658691229655648659252448158451924925658586522262194585891859285841914968868466462442488528641466655911199816288496111884591648442984864269495264612518852292965985888414945855422266658614684922884216851481646226111486498155591649619266595911992489425412191)
* (apply #'logxor *)
7777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777

Python 2, 103 + 42 = 145 bytes
Python natively supports bigints, but this program far exceeds 20 seconds for a 100-digit number. However, it decomposes 64-bit integers in around 2 seconds.
from random import *
def d(a):
 b=c=0
 while set(`b`+`c`)&set('037'):
    b=randint(1,a);c=a^b
 return b,c

Clever idea using randomness. If you're defining a function, you don't need a while loop to keep trying random values -- you can just call the function again. Without need for control structure, you can then collapse the function to a lambda and a ternary: from random import* d=lambda a,b=0:set(\b`+`a^b`)&set('037')and d(a,randint(1,a))or(b,a^b)`. Though you might be better off just not using a function.

I considered recursion, but it causes a stack overflow for large numbers (even just 11 digits).

Python 3 (132 bytes)
(This is just to stimulate better solutions. This is my solution when solving the original problem in ASCII movie.)
def d(a):
 l=len(str(a));s=int('1'*l);u=10**(l-1)
 while u:
  while set(str(s)+str((a^s)//u))&set('037'):s+=u
  u//=10
 print(s,a^s)

Although the behavior of bitwise xor in decimal system is pretty complicated, there is one major observation: modifying the low digits will not affect the high digits. Therefore, we can work top-down: try to make the top digits free of 0, 3, 7, and then work on the next digit, until the whole number is worked out. This allows us to run in linear time, then processing a thousand-digit number can complete under 1 second. (The Common Lisp solution is also using the same technique I believe.)

But fixing low digits may affect high digits.  For instance, 997^8 == 1005.  I think there is a kernel of an idea here, but it isn't obvious.

@KeithRandall: Yes it is just like 999…999 + 1, but, given the choice of {1,2,4,5,6,8,9}, there would be some of them that won't affect the high digits. (e.g. 997^2 == 999). The inner while loop does the exhaustion to find the choice that keeps the high digits valid.

right, but then it's not obvious (to me, at least) that there is definitely a digit that will work.


text:
Place a Carcassonne tile
The board game
In the board game "Carcassonne" players place tiles by matching their edges and earn the highest scores through creating large contiguous areas of terrain. The following are (roughly) the types and quantities of tiles included in the game:
#01 x4
#02 x5
#03 x8
#04 x2
#05 x9
#06 x4
#07 x1
#08 x3
#09 x3
#10 x3
#11 x4
#12 x5
#13 x3
#14 x3
#15 x2
#16 x5
#17 x5
#18 x2
#19 x3
#20 x1
#21 x5
#22 x2
#23 x1
#24 x1
#25 x1
The Task
You must place a tile by matching edges, while trying to maintain the largest possible contiguous areas of terrain.
Placement

Tiles can only be placed in one of the (up to 4) blank spaces adjacent to any existing tile (or tiles) in the play area.
Tiles can be rotated 90, 180 or 270 degrees.

Edge-matching

Edges of a placed tile must match the touching edges of the (up to 4) neighbouring tiles, i.e. touching pixels are the same colour.

Contiguous terrain

"Closing an area of terrain" refers to placing a tile such that any contiguous area of colour could not then be continued with further tile placements.
If an alternative placement is possible, it must be chosen over any tile placement that would close an area of terrain.
If you have to choose between a number of closing placements, choose any. If you have to choose between a number of non-closing placements, choose any.
Disregard #ff00ff (the corner pixels) when calculating contiguous areas. Also disregard buildings, i.e. areas of colour already fully enclosed within a tile.

Input

Input is two images:

The play area.

The initial play area consists of tile #11 (a single tile).
The augmented play area created as output must also be supported as input.

The tile to be placed.

All of the example tiles must be supported as input.

Determine matching edges/contiguous terrain using this image data alone. No hardcoding.

Output

Output is an image showing the resultant play area after placing the tile.
The image must be compatible with your own program,  i.e. it can be used as play area input.
If it's impossible to place a tile, return an error.

You can assume that

Tiles are always 55 px by 55 px
Tiles will only ever feature the colours currently used in the example tiles.

Notes

Your answer must feature example output after at least 2 passes (more is encouraged).
This is a partial and inaccurate rendering of the original board game, you don't need to apply any of the rules or tactics not mentioned here.

Score

Your score is your submission's byte count.
Image data isn't included in your score.
Lowest score wins.

Playing a full game
You may wish to write a script that uses your submissison to play a full game, which might consist of:

Placing a tile chosen pseudorandomly from the full set of 85.
Returning the tile to the set if it can't be placed.
Repeating until every tile has been placed - or until two tiles in a row can't be placed.

It won't be included in your byte count, or improve your score, but I'll likely offer a bounty to this kind of answer.

what is the differenct between 12, 15, and 17?

thanks for catching that, 17 was a duplicate. however 15 does differ as it can potentially close an area of terrain. (btw, areas of colour aren't contiguous if only the corners of pixels touch)

So one 15 and two 2s could make 2 separate black sections of size 2.  While one 12 and two 2s could make a black sections that is 3 big instead.  Ok.

A few questions: 1. What exactly is a "contiguous area of colour"? If I put down tiles 9, 14, 15, 20 from left to right, I take it that's a "contiguous area of colour", even though it's composed of many colours? If so, why not call just it "4-connected group of tiles"? 2. When you say that the input is two images, do you mean command-line arguments specifying two image filenames? 3. In the output image, what fills any empty tiles on the game board? Transparent pixels?

if you could use the ms paint fill bucket tool to change the colour of an area it is a contiguous area. in your example there would be 7 contiguous areas. 2. that sounds reasonable. as long as you use two images as specified you can do this however you want. 3. you can depict blank space in any way you like. transparency is a good option. you could also use any colour not featured in the example tiles.

Tile #18 seems to have an additional pixel of blue on the left edge, at least if it is supposed to line up with, for example, tile #21.

Where is #11 to be positioned in the initial input play area?  In the top-left corner?

@hosch250 the play area is infinite (extends as necessary). With just the first tile on the play, the first tile is the whole play area.

@jlahd OK, I get it.

What about the river monastary and the bridge? Also, the headwater/lake tiles actually have roads extending from them as well.

It's not entirely faithful to the tile set (or rules) in the game. You can include improved tiles in your answer if you want (as long as the example tiles are supported).

Perl 5 with PerlMagick: 875 789 763
I did not count the line starting with sub w, which is used to sort positions on the distance to the center to prefer compact solutions (now working properly). In this version closing is avoided like requested but I find the opposite more interesting and true to the game. To achieve that change the line $s=$t if!grep... to $s=$t if grep....
use Image::Magick;
sub p{/x/;@o=$r->GetPixel(y=>$'+pop,x,$`+pop);"@o"}
sub o{$w=&p;"0 0 0"eq$w?3:&p eq$w}
sub f{$r->FloodfillPaint(y=>$J+$',x,$I+$&,channel,All,fill,@_)}
($i=Image::Magick->new)->Read(@ARGV);$r=$b=$i->[0];
$h=$b->Get(rows)+112;$:=$b->Get(width)+112;
$b->Extent(geometry,"$:x$h-56-56",background,none);
@v=grep p()eq"0 0 0",map{map-54+55*$_.x.($'*55-54),//..$:/55}1..$h/55;
sub w{$_=pop;/x/;abs($:-2*$`)+abs($h-2*$')}@v=sort{w($b)<=>w($a)}@v;
map{map{/x/;$I=$`;$J=$';$r=$b->Clone();
($t=$r)->Composite(image,$i->[1],x,$I,y=>$J);
if((o(27,0,27,-1)&o(0,27,-1,27)&o(27,54,27,55)&o(54,27,55,27))==1){
$s=$t if!grep{/../;$r=$t->Clone();f(none);f(red);
!grep{p()eq"1 0 0"}@v}
map{/..$/;($_,$&.$`)}map{($_.-1,$_.55)}10,27,45;
$o=$r=$t;}$i->[1]->Rotate(degrees,90)}($_)x4}@v;
$s||=$o or exit 1;$s->Trim();$s->Write("car.png")

Usage: perl car.pl board.png tile.png. Result stored in car.png. Exit status is 1 if the tile could not be placed.
Script to run a complete game. It assumes the code above is in the file car.pl and the tiles are stored in tiles directory named 01.png to 25.png.
use List::Util shuffle;$x='00';
@t=shuffle map{($x++)x$_}split'',a4582941333353325523152111;
`cp tiles/11.png car.png`;
$i++,`perl car.pl car.png tiles/$_.png`,print"placed $i\n"for@t

This runs quite slowly now. 8-12 minutes on my machine.
With closing preferred:

With closing avoided (note nothing is closed).

The area close test seems to not work properly. The city-with-road-corner tile at (0,1) was the last one placed.

@jlahd You are right. For tests I reversed the condition as it is much easier not to close a region (also it is a better strategy in the actual game to close them). But now I am not sure if this reverse condition even works properly. I will fix that today.

@jlahd Fixed, thanks for noticing. The opposite condition was OK after all BTW.

Common Lisp, 2650 2221 1992 1186 1111 bytes
Update: "Easy" golfing now done, further gains will require bigger changes.
Update 2: With the competition getting fiercer, the new version no longer favors positions inside the current playing field rectangle (that would be 57 bytes extra). This option, as well as a simple speed optimization, is by enabled by default in the downloadable version with the simulator, but not in the official answer below.
Update 3: Minor interface changes for major byte count gains.
I created a simple Web UI as well. The full package (a single LISP file and the tile images) can be downloaded here. To try it, install hunchentoot, zpng and png-read with quiclisp, load in carcassonne.lisp, and connect to localhost:8080. The code has been tested on CCL/Windows and SBCL/Linux. The above mentioned libraries are only needed for the UI/simulator part; the solution itself is plain ANSI Common Lisp.
(defun c(f p &aux b a s z(c 55))
  (macrolet((d(v l &body b)`(dotimes(,v,l),@b))
            (b(b c)`(d i c(d j c(setf,b,c))))
            (r(&rest p)`(aref,@p))
            (n(u v i j)`(and(setf l(*(f,u,v)l))
                            (find(r f(+,u,i)(+,v,j))`(0,(r f,u,v))))))
    (labels((p(p w)(d y(ceiling w 2)(d x(- w y y)(rotatef(r p y #6=(+ x y))(r p #6##7=(- w y))(r p #7##8=(- w x y))(r p #8#y)))))
            (a(y x)(or(if(= 0(r f y x))1 #4=(and(= 1(incf(r s y x)))(=(r f y x)z)(push`(,y,x)a)0))0))
            (f(y x)(setf z(r f y x))(if #4#(loop for((y x))= a while(pop a)maximize(+(a(1- y)x)(a y(1- x))(a(1+ y)x)(a y(1+ x))))1)))
      (d i 8(when(d x #1=(array-dimension f 0)(or(= 0(r f(- #1#52 i)x))(return t)))(setf f(adjust-array f`(#2=,(+ #1#c)#2#))))(p f(1- #1#)))
      (d i 4(d u #9=(/ #1#c)(d v #9#
        (let((y(* u c))(x(* v c))(l 9e9))
          (when(= 0(r f y x))
            (b #10=(r f(+ y i)(+ x j))(r p i j))
            (setf s(make-array`(,#1#,#1#))a())
            (ignore-errors(if(> #11=(*(loop for d from 1 to 53
                                            sum(+(n y #3=(+ x d)-1 0)(n #5=(+ y d)(+ 54 x)0 1)(n(+ 54 y)#3#1 0)(n #5#x 0 -1)))
                                      (1+ l))
                                (or(car b)0))
                             (setf b`(,#11#,i,y,x))))
            (b #10#0)))))
         (p p 54))
      (when b(d j(cadr b)(p p 54))(b(r f(+(third b)i)(+(nth 3 b)j))(r p i j)))
      `(,f,b))))

All line feeds and line-starting spacing are for cosmetics only, to ensure legibility, and not counted into the total sum.
You should call the function c with two arguments: The current play field, and the tile to place. Both should be 2D arrays; the tile 55x55 and the field a multiple of that. Additionally, the field array must be adjustable. The function returns a two-element list with the new field as its first argument. The second element is NIL if the tile cannot be placed, or otherwise a list containing the top-left coordinates and rotation of the latest tile on that array and the score for that tile. This information can be used for visualization purposes.
Note that in further calls, you must use the new field returned by c even if the second list element is NIL (the original array may have been adjust-arrayed and thus invalidated).
The code is now a bit on the slow side, byte count optimization resulting in redundant calculations. The example below completed in about three minutes on my system.
Example run for all 85 tiles:

Web UI screenshot:

Preferring the placement to be within the current rectangle is a good idea. I was noticing that it tends to be snakey if you take the easy route.

not the winning score, but you get the bounty for a few nice innovations.

DarkBASIC Pro: 2078 1932 1744 bytes
UPDATE: Just more golfing effort
UPDATE: Now fully meets the spec, including preferring non-closing choices.
I chose DarkBASIC because while it's rather verbose, it provides an extremely straightforward and simple command set for manipulating images.
I uploaded an EXE for people who don't have the DarkBASIC compiler (Windows).

#constant m memblock
#constant f function
#constant k endfunction
#constant z exitfunction
#constant i image
#constant e endif
#constant t then
#constant o or
#constant s paste image
#constant n next
#constant r for
set i colorkey 0,20,0:load i "map.png",1:f$="next.png"
if file exist(f$)=0 t f$=str$(rnd(24)+1)+".png"
load i f$,2:make m from i 1,1:make m from i 2,2
global ts,h,j,u,v,td
ts=i width(2):h=i width(1):j=i height(1):u=h/ts:v=j/ts:td=ts*2
create bitmap 2,h+td+1,j+td+1:r b=1 to 4:r xx=0 to u+1:r yy=0 to v+1:x=xx*ts-1:y=yy*ts-1
cls 5120:s 1,ts,ts,1:if (a(x+1,y) o a(x,y+1) o a(x-ts,y) o a(x,y-ts)) and a(x,y)=0
x1=ts*xx:y1=ts*yy:make i from m 2,2:s 2,x1,y1,1
cl=0:r fd=0 to 1:r x2=1 to ts-2:r yt=0 to 1:y2=yt*ts-yt:y3=yt*ts+yt-1
aa=x2:ab=x2:ba=y2:bb=y3:t2=y1:r t3=0 to 1:p=point(x1+aa,y1+ba):q=point(x1+ab,y1+bb)
if p<>q and rgbg(q)<>20 and t2+b>0 t goto fa
if fd and p<>0xFF0000
if l(x1+aa,y1+ba,p)=0 t cl=1
e
aa=y2:ba=x2:bb=x2:ab=y3:t2=x1:n t3:n yt:n x2:n fd:dn=1:c=xx-1:g=yy-1:make i from m 3,2:if cl=0 t goto dm
e
fa:
n y:n x
d=ts/2:r x=0 to d:r y=0 to d-1:vx=ts-1-x:vy=ts-1-y:t1=rd(x,y):t2=rd(vy,x):wr(vy,x,t1):t1=rd(vx,vy):wr(vx,vy,t2):t2=rd(y,vx):wr(y,vx,t1):wr(x,y,t2):n x:n y:n b
dm:
if dn=0 t report error "Not placed"
p=c<0:q=g<0:t1=h+ts*(p o c>=u):t2=j+ts*(q o g>=v):cls 5120:p=ts*p:q=ts*q:s 1,p,q,1:s 3,c*ts+p,g*ts+q,1:get i 1,0,0,t1,t2,1:save i "map.png",1
end
f l(x,y,w)
if x<0 o y<0 o x>=h+td o y>=j+td t z 1
p=point(x,y)
if rgbg(p)=20 t z 1
if p<>w t z 0
dot x,y,0xFF0000:rt=l(x+1,y,p) o l(x-1,y,p) o l(x,y+1,p) o l(x,y-1,p)
k rt
f rd(x,y)
w=m dword(2,0):b=m dword(2,12+(y*w+x)*4)
k b
f wr(x,y,d)
w=m dword(2,0):write m dword 2,12+(y*w+x)*4,d
k
f a(x,y)
if x<0 o y<0 o x>=h o y>=j t z 0
b=m byte(1,15+(y*h+x)*4)
k b


text:
Group the Numbers With the Same Sum
Your task is, given a square grid of digits (0-9), output one of the ways that the digits can be grouped such that:

Each digit is part of exactly one group
All groups have the same number of digits
All groups are bounded by one polygon-like shape (this means that every digit in the group is next to [left, right, up, down] at least one other digit of the same group, unless each group has 1 element).
All groups have the same sum

The input grid will always be a square:
You may choose any input method you would like (including supplying arguments to a function or method). In addition, the input will supply the number of groups that your program should group the digits into.
Example input:
Suppose your input format is stringOfDigits numberOfGroups.
An example input would be:
156790809 3

which would translate to (a grid of sqrt(9) * sqrt(9))
1 5 6
7 9 0
8 0 9

which you would have to divide into 3 groups, each of which should have 9 / 3 = 3 elements with the same sum.
Output:
Output should be the string of digits, with optional spaces and newlines for formatting, with each digit followed by a letter a-z indicating its group. There should be exactly numberOfTotalDigits / numberOfGroups elements in each group. You will never have to divide something into more than 26 groups.
Example output:
1a 5a 6b
7c 9a 0b
8c 0c 9b

Note that replacing all as with bs and bs with as is equally valid. As long as each group is denoted by a distinct letter, the output is valid.
In addition, I expect most programs to output something along the lines of this, because newlines/spaces are optional:
1a5a6b7c9a0b8c0c9b

In this case, adding all digits of group a, b, or c makes 15. In addition, all groups are bound by some polygon.
Invalid outputs:
1a 5a 6b
7c 9a 0c
8c 0b 9b

because the groups do not form polygons (specifically, the 6b is isolated and 0c is also lonely).
1a 5a 6b
7c 9a 0b
8c 0b 9b

because the group b has 4 elements while c only has 2.
Etc.
If there is no valid solution, your program may do anything (i.e. stop, crash, run forever) but if your program prints None when there is no valid solution, -15 to your score.
If there is more than one solution, you only have to print one, but -20 if your program prints all of them separated by some delimiter.
This is code golf, so shortest code (with bonuses) wins!

In the first invalid output, I think you mean the 6b is isolated, not the 0b.

Does it matter how fast our program is? What about if it's too slow to validate if it works?

156790889 3 seems like it should be 156790809 3

Pyth, 122 - 20 - 15 = 87
=Z/lzQ=ks^lz.5Jm]dUzL[-bk+bk?tb%bkb?hb%hbkb)FNJIgNZB~Jm+NksmybN;|jbS{msm+@zk@S*Z<GQxsdkUzfqSsTUz^fqsmv@*ZzbY/smvdzQJQ"None

Changes:

130 -> 120: Switched to newline separated input.

120 -> 134: Fixed a bug involving groups not of size equal to the side length of the matrix.

134 -> 120: Prints all solutions, including ones equivalent under group renaming.

120 -> 122: Fixed a bug where only paths would be generated, instead of all legal groups.

Test run:
pyth programs/sum_group.pyth <<< '156790809
3'
1a5a6b7c9a0b8c0c9b
1a5a6c7b9a0c8b0b9c
1b5b6a7c9b0a8c0c9a
1b5b6c7a9b0c8a0a9c
1c5c6a7b9c0a8b0b9a
1c5c6b7a9c0b8a0a9b

pyth programs/sum_group.pyth <<< '156790808
3'
None

pyth programs/sum_group.pyth <<< '1111
2'
1a1a1b1b
1a1b1a1b
1b1a1b1a
1b1b1a1a

Explanation:
Pyth code           (Pseudo)-Python code              Comments

(implicit)          z = input()                       z is the digit string
(implicit)          Q = eval(input())                 S is the number of groups
(implicit)          G = 'abcdefghijklmnopqrstuvwxyz'
=Z/lzQ              Z = len(z)/Q                      Z is the size of each group.
=ks^lz.5            k = int(len(z) ** .5)             k is the side length of the matrix.
Jm]dUz              J = map(lambda d:[d], range(len(z))) Locations are encoded as numbers.
L                   def y(b): return                  y will be the transition function.
 [-bQ                         [b-k,                   Move up - the row above is k less.
  +bQ                          b+k,                   Move down - the row below is k more.
  ?tb%bkb                      b-1 if b%k else b      Move left, unless at the left edge.
  ?hb%hbkb)                    b+1 if (b+1)%k else b] Move right, unless at right edge.
FNJ                 for N in J:                       This constructs the list of all
   IgNZB                       if N[Z-1]: break       Z-length connected groups.
   ~Jm+Nk                      J+=map(lambda k: N+[k],  Append to J the group of N +
      smybN                          sum(map(lambda b:  anything reachable from
                                     y(b),N)))        anywhere in N.
   ;                (end for)
|                   or                                Print first truthy thing between
 S{                 sorted(set(                       Unique elements in sorted order of
   ms               map(lambda b:sum(                 Map+sum over allowable combinations
     m+@zd          map(lambda d:z[d]+                Character in original digit string
       @S*Z<GQ      sorted(G[:Q]*Z)[                  Repeated and sorted early alphabet
        xsbd        sum(b).index(d)],                 At index of number in sum of groups
      Uz                range(len(z)))                Over possible indexes.
   f                filter(lambda T:                  To generate allowable combinations,
                                                      we will filter all groups of Q paths.
    qSsTUz          sorted(sum(T)) == range(len(z))   Ensure all locations are visited.
    ^                                                 Combinations of
     f              filter(lambda Y:                  Filter over connected Z-length groups
      qsm           equal(sum(map(lambda k:           Sum of the values of the group
         v@*ZzkY    eval((z*Z)[k]),Y)                 In the original digit string
       /smvbzQ      sum(map(lambda b:eval(b),z))/Q    must equal the sum of all values in z
                                                      divided by the number of groups.
      J             J                                 Filter over connected Z-length groups
     Q              Q                                 Combinations of length Q
 "None              "None"                            If the above was empty, print "None"

"Pyth"? You misspelled "base64".

JavaScript (ES6) 361 (376-15) 372
(Maybe can still be golfed a little more)
As a function, first param is the string of digits and second param is the number of groups.
It's a naive recursive search, stopping at first solution found (no -20 bonus).
Need some more test cases to verify performance on some bigger input.
F=(g,n,l=g.length,i=w=Math.sqrt(l),o=s=h='',
  R=(g,p,k,j=l/n,t=s/n,v=0,h=String.fromCharCode(97+k))=>(
    t-=g[p],!(t<0)&&(
      g=[...g],g[p]=h,
      S=f=>g.some((c,p)=>c<':'&&f(p)),
      --j?S(p=>(g[p+1]==h|g[p-1]==h|g[p+w+1]==h|g[p-w-1]==h)?v=R(g,p,k,j,t):0)
      :t?0:k?S(p=>v=R(g,p,k-1)):v=g
    ),v
  )
)=>([for(c of g)(s-=-c,h+=--i?c:(i=w,c+':'))],h=R(g=h,-1,n,1))?h.map((c,p)=>o+=c!=':'?g[p]+c:'')&&o:'None'

Ungolfed & Explained
F=(g,n)=>
{
  var l = g.length, // string size, group size is l/n
      w = Math.sqrt(l), // width of grid
      s,i,h,o;

  // Build a new string in h, adding rows delimiters that will act as boundary markers
  // At the same time calculate the total sum of all digits
  h='',  // Init string
  s = 0, // Init sum
  i = w, // Init running counter for delimiters
  [for(c of g)(
    s -= -c, // compute sum using minus to avoid string concatenation
    h += --i ? c : (i=w, c+':') // add current char + delimiter when needed
  )];

  // Recursive search
  // Paramaters:
  // g : current grid array, during search used digits are replaced with group letters
  // p : current position
  // k : current group id (start at n, decreaseing)
  // j : current group size, start at l/n decreasing, at 0 goto next group id
  // t : current group sum value, start at s/n decreasing

  var R=(g,p,k,j,t)=>
  {
    var v = 0, // init value to return is 0
        h = String.fromCharCode(97+k); // group letter from group

    t-=g[p]; // subtract current digit

    if (t<0) // exceed the sum value, return 0 to stop search and backtrak
      return 0;

    g=[...g]; // build a new array from orginal parameter
    g[p] = h; // mark current position

    // Utility function  to scan grid array
    // call worker function  f only for digit elements
    //   skipping group markers, row delimieters and out of grid values (that are undefined)
    // Using .some will return ealry if f returns truthy
    var S=f=>g.some((c,p)=>c<':'&&f(p));

    if (--j) // decrement current group size, if 0 then group completed
    { // if not 0
      // Scan grid to find cells adiacent to current group and call R for each
      S( p => {
        if (g[p+1]==h|g[p-1]==h|g[p+w+1]==h|g[p-w-1]==h) // check if adiacent to a mark valued h
        {
          return v=R(g,p,k,j,t) // set v value and returns it
        }
      })
      // here v could be 0 or a full grid
    }
    else
    {
      // special case: at first call, t is be NaN because p -1 (outside the grid)
      // to start a full grid serach
      if (t) // check if current reached 0
        return 0; // if not, return 0 to stop search and backtrak

      if (k) // check if current group completed
      {
        // if not at last group, recursive call to R to check next group
        S( p => {
          // exec the call for each valid cell still in grid
          // params j and t start again at init values
          return v=R(g,p,k-1,l/n,s/n) // set value v and returns it
        })
        // here v could be 0 or a full grid
      }
      else
      {
        return g; // all groups checked, search OK, return grid with all groups marked
      }
    }
    return v
  };
  g = h; // set g = h, so g has the row boundaries and all the digits

  h=R(h,-1,n,1); // first call with position -1 to and group size 1 to start a full grid search

  if (h) // h is the grid with group marked if search ok, else h is 0
  {
    o = ''; // init output string
    // build output string merging the group marks in h and the original digits in g
    h.map( (c,p) => o += c>':' ? g[p]+c: '') // cut delimiter ':'
    return o;
  }
  return 'None';
}

Test In FireFox/FireBug console
F("156790809",3) output 1c5c6b7a9c0b8a0a9b
F("156790819",3) output None

authors: Александр Иванов


text:
Evaluate CDF of Student-t distribution
The goal of this codegolf is evaluating the cumulative distribution function of the student-t probability distribution. This is not trivial since there is no closed form and the function is dependent of two variables v and x. The distribution function is

For getting the CDF you could integrate this function from -inf to x. As you can see the evaluation of this function relies much on integration as you'd also have to evaluate nontrivial values of the gamma function.
Details
You can can write a program or function that accepts a two numbers xand v as input, where x is the position (must at least accept floats from -10 upto 10) at which the CDF is evaluated and v is the number of degrees of freedom. v is a positive integer (range 1 upto 1450) but it must be possible to set it to infinity (for v=inf the student-t distribution is equal to the normal distribution). But you can specify that e.g. v = -1 should denote infinity. The output consists must be a number between 0 and 1 and must have an accuracy of at least 4 decimal places.
If your language does not support runtime inputs or arguments on program call you may assume that both arguments are stored in variables (or another 'memory unit')
Restrictions
You may not use special functions like the gamma function or probability distribution functions as well as numerical integration functions or libraries (as long as you do not include their source in your code which counts for the score) etc. The idea is using only basic math functions. I tried to make a list of what I consider as 'basic' but there might be others I forgot - if so please comment.
Explicitly allowed are
+ - / *
% (modulo)
! (factorial for integers only)
&& || xor != e.t.c. (logical operators)
<< >> ^ e.t.c. (bitshift and bitwise operators)
** pow (powerfunction for floats like a^b including sqrt or and other roots)
sin cos tan arcsin arccos arctan arctan2
ln lb log(a,b)
rand() (generating pseudorandom numbers of UNIFORM distribution)

Scoring
Lowest number of bytes wins.
Entry
Please explain how your code works.
Please show the output of your program for at least 5 different arguments. Among those should be the following three. For your own values please also provide 'exact' values (like from wolframalpha or what ever you prefer).
x = 0      v= (any)  (should return 0.5000)
x = 3.078  v= 1      (should return 0.9000
x = 2.5    v= 23     (should return 0.9900)

If possible, it would be great if you could provide some fancy plots of the values calculated with your program (the code for plotting does not count for the score).
(from Wikipedia):

Many languages natively support powerful numeric integration algorithms, which aren't "special functions like the gamma function or probability distribution functions etc.". These algorithms are implemented using only the basic mathematical operators you've listed. Is the use of such library functions allowed?

Thank you for pointing this out. No, I'd like the participants to program it 'from scratch', so they should implement the integration method in the program itself (it does not matter whether it is 'stolen' from a library, as long as it is included in the code and counts for the score.)

So numerical integration is allowed provided it is included in the program? That shouldn't be too dificult, a simple riemann sum or trapezium rule can be implemented with a for loop, provided it starts at a low enough value. On the other hand, a polynomial approximation should be able to solve this to the required accuracy. Is that allowed? (What if I call it an "analytically derived" Taylor series, or even an "empirically derived" one?)

Yes this is allowed, the goal is having the required accuracy on the whole given domain. I am looking forward to seeing different approaches! If you want you could even do the whole think with one big lookup table, but it has to be included in the bytecount=)

May we generate random numbers (like floats between 0 and 1)?

Good question, I didn't think about that but I think I'm gonna allow that, I guess you are after MC-methods, right? (Or is there any other 'shortcut' that makes it way easier to solve the challenge with random numbers than without?)

Does it have to be 4 significant digits (or is it 4 decimal places)? For example according to http://www.wolframalpha.com/input/?i=t+distribution+probabilities for x=2.5788 v=1500 I get 0.9950, the same answer to 4 significant digits as for v=inf.(table at http://mathworld.wolfram.com/Studentst-Distribution.html ). But for x=-2.5788 v=1450 I get 0.005048, which only matches the result for v=inf in its last digit. At x=-10 v=1450 I get 4.096E-23. The asymmetric number of decimal places required by current wording may require a datum at x=-10 rather than the obvious x=0 or x=-inf

This question has turned out harder than I thought. First I tried integrating (1+x^2/v)^(-v/2-.5) numerically in the ranges -9999...x and -9999...9999 and dividing one by the other (taking 9999 as an approximation for infinity and knowing that the gamma part would cancel out) but I ran into problems with machine limits. I have a way of calculating the gamma function in half-integer steps inductively. There's a complete formula at http://www.vosesoftware.com/ModelRiskHelp/index.htm not requiring integration, but it's pretty complicated.

@steveverrill Oh I didn't consider that, so would you suggest altering the question to 4 decimal places (E.g. If the exact value is 0.0001624... the acceptable answer would be 0.0002)?

@flawr I've gone ahead and edited it, and fixed a spelling mistake in the title too. Roll it back if you disagree, but I think it's better that way. I dont think centering the calculations on x=-10 was your intention, and v=1450 is more than enough to make this challenging.

@steveverrill The changes are ok, I just didn't understand what you mean by the second part? Why do you mean by centering the calculations on x=-10? Would you suggest v=1450 as limit?

@flawr per my previous comment, around v=1450 is where the curve becomes indistinguishable from v=inf based on a precision of 4 decimal places, so now there shouldn't be a need for a limit on v. Gamma(1450) is a big number but just about manageable. It would be easier if it was lower :-) The regarding the x=-10, the point of my edit was to avoid the need for excessive precision at the low end of the x domain, so that part is solved too. I was just reiterating why I think the change is a good one. Because I'm embarrased about changing the rules on a question I'm planning to answer.

Ah ok now I understand, well there are really some problems I didn't consider (e.g. the limits of the computers, I only thought about the algorithms in a mathematical way.) So no need to feel embarrassed, I am really glad you helped eliminating the 'impossible' aspects=)

Can I use a built-in value of π?

@TwiNight Yes you can, I'll add that.

My MC convergence rate essentially becomes 0. Can't get 4 digits ahhhhhh! I'm guessing this is a problem with Box Muller.

Well it seems this thread is not getting flooded with answers, so feel free to post your approach anyway!

You can use Box Muller (or many of the more algorithmically complex but better methods) to generate normal i.i.d. variables using uniform random. Then you can use (http://stats.stackexchange.com/a/70270) to generate student-t random variables (should be an exact result). Generate a lot of these student-t and rely on almost-non-existant-convergence to find the density. I'm doing this in R and its loop performance is essentially 0. I figure an implementation in a faster language with couple billion samples could possibly get the solution fairly close (assuming normal r.v. gen is good...)

BBC BASIC, 155 ASCII characters, tokenised filesize 140
Download emulator at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html
  a=1s=.000003INPUTx,v
  IFv<1v=9999
  FORw=1TOv-1a=w/a
  NEXTb=SGN(x)*s*a/SQR(v)IFv MOD2b=b/PI ELSEb=b/2
  f=.5FORz=0TOABS(x)STEPs
  f+=b/(1+z*z/v)^(v/2+.5)NEXTPRINTf

The code is in two parts. The first calculates the coefficient that is independent of x. and stores it in b. The algorithm is a bit like a continued fraction, but a mathematician would probably call it a simple quotient of two products. It's based on a formula from the Wikipedia page in the question, which is similar to a factorial but has the product (v-1)(v-3)... divided by the product (v-2)(v-4)... This is possible because we are only interested in half-integral values of the gamma function (arbitrary values of the gamma function would be a lot harder.) Using this formula we never have to calculate either gamma function, so we avoid large numbers. The largest intermediate value is approximately the square root of v.
The second is a straightforward integration from 0 to x by summation. It is known that f(0) is 0.5 so we start from there and work outwards. the sign and magnitude of b are modified before the loop, in order to be able to give the final answer directly.
Pretty version, ungolfed
This contains a few extra lines to add colour and to plot the data. The range x=0 to endpoint, and f(x)=0.5 to 1 is shown. Also v is modified to 2^v to be able to show the full range of v values without exceeding the limits on colour. In order to speed the drawing up, there are two less digits in s than in the golfed version. Even so, there is only one discrepancy when compared with http://www.wolframalpha.com/input/?i=student+t-distribution+probability: 0.8130575 rounds up to 0.8131. The golfed version give the correct answer (0.8130) for this and all the other cases below.
  a=1                              :REM accumulator for gamma series
  s=.0001                          :REM step size for x integration
  INPUTx,v
  IFv<1 v=9999                     :REM if v<1, set v to a value that gives results indistinguishable from infinity
  GCOLv                            :REM pick a colour
  v=2^v                            :REM for the pretty version, modify v to 2^v
  FORw=1TOv-1
    a=w/a                          :REM calculate series as per Wikipedia
  NEXT
  b=a/SQR(v)                       :REM divide a by the necessary values...
  IFv MOD2 b=b/PI ELSE b=b/2       :REM to give the coefficient, per Wikipedia

  b*=SGN(x)*s                      :REM modify according to sign and step size
  f=.5                             :REM initialise f(x)=.5 at x=0
  FORz=0TO ABS(x) STEPs
    f+=b/(1+z*z/v)^(v/2+.5)        :REM perform integration as simple "barchart" sum
    PLOT69,z*100+200,(f-.5)*1600   :REM plot a point
  NEXT
  PRINT f


text:
The Fatal Error Challenge
Objective
Write a routine that accepts a string of printable ASCII characters, s, and returns a string containing the same characters as s,  reordered so that no two-character substring appears more than once. The program must process all benchmark strings (see below) in under one minute each on a modern computer. I will also award a special bonus of 50 rep to the lowest scoring answer that processes any valid 30-character string in under one minute.
For example, given the input Mississippi, a valid output would be issiMspiips (no two-character substrings appear twice), while an invalid output would be ipMsispiiss (since the substring is appears twice).
The routine may take the form of:

a complete program reading from stdin (or equivalent) or the command line, and outputting to stdout (or equivalent)
a function accepting a single string argument and returning a string

You may assume that the input string always admits at least one valid output.
The Challenge
Your routine must comprise 5 or more lines of code separated by newlines. Empty lines (which includes lines containing only whitespace) are ignored in all contexts and do not count towards total line count.
Swapping any two lines in your source code must produce a fatal error. By "fatal error", we refer to any of the following conditions:

the source code fails to compile, with the compiler/interpreter declaring a fatal error
the routine aborts with a runtime fatal error or an unhandled runtime exception
the routine is forced into an abrupt, abnormal program termination that produces no output of any kind except for a possible error message and/or stack dump

Alternatively, contiguous blocks of code containing no newline characters may be used in place of lines. These blocks should each be displayed on their own line in the source file, with the understanding that newlines are stripped out before the source code is compiled/interpreted.
For example, the code
aaaa
bbbb
cccc

would condense to
aaaabbbbcccc

before being evaluated.
In this mode, the fatal error condition applies to swapping any two code blocks (and thus to swapping lines in the source code before newlines are stripped out). Hence in the above example the routines aaaaccccbbbb, bbbbaaaacccc, and ccccbbbbaaaa must all produce fatal errors, either at compiletime or runtime.
Submissions using this alternative mode should declare its use.
Scoring
Let n be the number of non-empty textlines in your source file, with n ≥ 5. Let c be the number of bytes comprised by the longest textline (by byte length) in your source file, not counting any trailing newline.
A submission's score is given by c(n + 10).
The submission with the lowest score is the winner.
Best of luck. ;)
Benchmark Strings
Abracadabra Alacazam
Is Miss. Mississauga Missing?
Ask Alaska's Alaskans
GGGGAAAATTTTCCCCgggaaatttccc
A Man A Plan A Canal Panama

Are capital letters different from lowercase letters? i.e. Input is CooliO, output oOoCli?

@FryAmTheEggman: Yes. Capital letters differ from lowercase letters. In general, consider only the ASCII code values of the characters.

Does repetitions restrict to letter pairs appearing in the input? E.g. Is Mspiisiipss valid since the only repetition is ii which does not occur in Mississippi?

@TwiNight: Even repeated substrings that do not appear in the original string are not allowed.

May I assume anything about input length? (background: got a brilliant idea for a BF solution)

@Pietu1998: You can assume the input string is nonempty and comprises 30 characters or less (in the spirit of "any valid 30-character string in under one minute").

PHP, score = 289 (17×(7+10))
PHP's built-in functions make it quite easy to do this badly. The following code just shuffles the string until a valid result is obtained:
function f($s){
while(preg_match(
'/(..).*?\1/',$s)
+preg_match('/(.'
.')\1\1/',$s))$s=
str_shuffle(
$s);return $s;}

Benchmarks
Average and maximum execution times calculated using the following code:
$s = 'Mississippi';
$t_total = 0;
$t_max = 0;
for ($i=0; $i<10; $i++) {
  $t0 = microtime(true);
  echo f($s);
  $t = microtime(true) - $t0;
  printf("  %10.7f\n",$t);
  $t_total += $t;
  if ($t > $t_max) $t_max = $t;
}
printf("Avg: %10.7f secs; Max: %10.7f secs\n",$t_total/$i, $t_max);

Results:

Mississippi: Avg:  0.0002460 secs; Max:  0.0005491 secs
Anticonstitutionnellement: Avg:  0.0001470 secs; Max:  0.0002971 secs
Pneumonoultramicroscopicsilicovolcanoconiosis: Avg:  0.0587177 secs; Max:  0.1668079 secs
Donaudampfschiffahrtselektrizitatenhauptbetriebswerkbauunterbeamtengesellschaft*: Avg:  9.5642390 secs; Max: 34.9904099 secs
baaacadaeafbbcbdbebfccdcecfdde†: Avg:  5.0858626 secs; Max:  9.8927171 secs

* I changed ä to a to avoid multi-byte issues
† This was the hardest 30-character string I could come up with. It's actually the first 30 characters of the De Bruijn sequence for k='abcdef' and n=2, with the first 'b' moved to avoid an instant match.

This doesn't really satisfy > The program must process any valid 30-character string in under one minute on a modern computer., considering the potentially infinite runtime.

@Bob I've added some benchmarks to the answer. The code may be inefficient, but the likelihood of it taking more than one minute to process a 30-character string is, I think, very small indeed.

Dyalog APL (11(5+10)=165)
f←{a←{⍴⍵}
b←a⌸2,/⍵
c←b⊢⍵[?⍨a⍵]
1∨.≠b:∇c⋄⍵
}

Proof:

Lines 1 and 5 bound the function. Swapping any line for those would result in ⍵ occurring outside of a function, which is a SYNTAX ERROR.
Line 2 defines b, so it cannot be swapped for lines 3 or 4, which depend on b. There would be a VALUE ERROR. (And it obviously can't be swapped with 1 or 5 either.)
Line 3 defines c, so it cannot be swapped for line 4, which depends on c. (And we've already proven no other line can be swapped with line 3.)
Line 4 depends on the variables from lines 2 and 3 and must therefore be last.

+1. But what does it all mean??

APL(Dyalog), 6(5+10) = 90
{1∧.=
+/∘.≡⍨
2,/⍵:⍵
⋄∇⍵[
?⍨⍴⍵]}

I'm using the alternative, so:
{1∧.=+/∘.≡⍨2,/⍵:⍵⋄∇⍵[?⍨⍴⍵]}

This is the same old algorithm.

Explanation
2,/⍵ gives an array of character pairs in the input string
+/∘.≡⍨ generates a numerical array of how many pairs does each pair equal (including itself)
1∧.= checks if each element of that array equals 1, and logical AND the results together
:⍵ If that is true (1), return the input string
∇⍵[?⍨⍴⍵] else scramble the input string and do a recursive call

Swapping
If line 1 is swapped with line 2, then you end up with +/∘.≡⍨{...} which is just a mess of functions and operators that gives SYNTAX ERROR.
If line 1 is swapped with line 3 or 4, then you have ⍵ outside of a function definition, and that's a SYNTAX ERROR.
If line 1 is swapped with line 5, unbalanced braces alone would cause SYNTAX ERROR, so don't worry about the other 4 syntax errors.
If line 5 is swapped with line 2/3/4, again you have ⍵ outside of a function definition.(SYNTAX ERROR)
If line 2 is swapped with line 3, you end up with 1∧.=2,/⍵:⍵. This syntax is called a guard (think of it as a conditional). The guard condition must evaluate to 0 or 1 or a 1-element array of 0 or 1. Here, it evaluates to something more complex than that (a scalar containing a 2-element array). So this is a DOMAIN ERROR.
If line 2 is swapped with line 4, you get the statement 1∧.=, which attempts to apply the function ∧.= without the required left argument. (SYNTAX ERROR).
If line 3 is swapped with line 4, again you get a mess of functions and operators (1∧.=+/∘.≡⍨) so you get SYNTAX ERROR.

Benchmarks
(numbers in milliseconds)
Abracadabra Alacazam
11 1 3 5 2
Avg: 4.4

Is Miss. Mississauga Missing?
1260 2000 222 117 111
Avg: 742

Ask Alaska's Alaskans
7 2 3 3 4
Avg: 3.8

GGGGAAAATTTTCCCCgggaaatttccc
31 15 24 13 11
Avg: 18.8

A Man A Plan A Canal Panama
377 2562 23 301 49
Avg: 662.4

I am still thinking about different splittings. Also I have a deterministic, systematic way of doing the task. I just can't make it into an algorithm (take away the creative part of "making the numbers right") and can't make sure it works every time.

Haskell, 129 = 3x(33 + 10)
this uses the alternative mode.
imp
ort
 Da
ta.
Lis
t;a
%[]
=[[
]];
a%s
=[x
:j|
x<-
s,n
ot$
isI
nfi
xOf
[la
st
a,x
]a,
j<-
(a+
+[x
])%
(s\
\[x
])]
;g
s=[
]%s
!!0

or in a readable form:
import Data.List
a%[]=[[]]
a%s=[x:j|x<-s,not$isInfixOf[last a,x]a,j<-(a++[x])%(s\\[x])]
g s=[]%s!!0

Haskell is a very strict language. for example, the import must come first; the definitions of s must come together; all the types must agree and there is no way to cast between them, and so forth. this leads to having a non-fatal error almost impossible. in fact, having a runtime fatal error is too almost near impossible.
note that if g is a valid function but has an the wrong type (any type different then [a]->[a] or String -> String and the like) than this is a fatal error because it's impossible to apply g to the inputs.
outputs:
Abracadabar Alaazcma
Is Miss. iMsiasusgsa sMniig?s
Ask Alasak's lAaankss
GGAGTGCAATACTTCCggagtaacttcc
A Man AP la nAC  aalnnaPama


text:
Tic-Tac-Toe and Chess, with fewest [distinct] characters
In this form of the game Tic-Tac-Chec, the goal is to move chess pieces to get four-in-a-row. Your goal here is to figure out if a position has a winning move.
Rules
The rules are similar, but not identical, to those of Tic-Tac-Chec.
The board is 4 by 4 squares. Each player has a rook, bishop, knight, and queen. On your turn, you have two options. You can move one of your pieces already on the board, following  standard chess rules. Or you can place a piece not already on the board, on any unoccupied place.
If you move an existing piece onto an opponent's piece, their piece is taken off the board and returned to them. However, you may not place a new piece on top of an opponent's piece.
As soon as one player has all of their pieces in a row (or column, or diagonal), they win.
Challenge
Write a full program that accepts a board from STDIN, and outputs whether the white player can win on the next turn.
Input
Four strings of 4 characters each. Each character is either a space or a chess piece. Only rooks, bishops, knights, and queens are used, and at most one of each (per color) may appear. Neither player already has a four-in-a-row.
You can choose whether to accept as input the Unicode symbols for the chess pieces, or letters. If you choose letters, RBKQ represents white pieces, and rbkq represents black pieces.
Output
If the white player can win on the next turn, output true or 1. Otherwise, output false or 0.
Program
Choose a number X. Your program may contain at most X distinct characters, and no character may appear more than X times.
Winning
Lowest X wins. In case of a tie, fewest characters wins.
Examples
These examples assume the input uses letters to represent the pieces.
rkb

RB Q
true - the white player can place the knight to complete the bottom row.
-----------------------------------
rk

RBbQ
false - the black bishop prevents the white knight from completing the row.
-----------------------------------
rk
 K

RBbQ
true - the white knight can capture the black bishop and complete the row.
-----------------------------------
rkRB

 Qb
K
true - the white rook can move down one to complete the diagonal.

So oOo code is going to win?

@KennyTM No char may appear more than X times will render oOo useless

@Optimizer OK sorry misread the rules.

Could the examples be put into a more legible format, it is quite difficult to see what the positions of the pieces are and to which colour they belong.

Is whitespace allowed?

Are you OK with things like exec(encode(len(s))) where s is a ginormous string of spaces, more than there are atoms in the universe?

@xnor Sure, but that won't win, since "no character may appear more than X times"

@MartinBüttner I've allowed using letters instead of Unicode symbols.

@Tally See above comment.

@ciuak Wwhitespace characters are treated like any other kind of character.

I've made some 4×4 boards based on the examples given. If they need to be changed, you can edit the markup here and paste into the Wikipedia sandbox to see the results.

@squeamish Thanks. The K stands for knight, not king. And the fourth example has the queen and bishop in the center columns, not the rightmost ones.

The repeated confusion about the winning criterion is due to the misleading title. it sounds like you are scoring based on least duplication of characters, but the title still states fewest distinct characters.

APL (Dyalog Unicode), 369 characters, score 28
{Q←(QQ←⍴⍵)[1]
R←∨/¨⍵=⊂'RBQK'
B←({⍵(⍵[↑(⍳Q),¨¨⊂1--Q-⍳Q])}↑(⍳Q)=⊂⍳Q),{⍵,{⍵[{⍵[(1--1)1]}¨⍳QQ]}¨⍵}(⊂QQ)⍴¨(⍳Q)=⊂⍳Q
K←(Q-1)={∨/1↑⍴{(,⍵)/,⍳⍴⍵}⍵}¨B×⊂R
1-∨/K:1-1
K←↑∨/K/B
BB←{(,⍵)/,⍳⍴⍵}K×1-R
R←↑∨/BB-B←{(,⍵)/,⍳⍴⍵}R×1-K
1-⍴B:⍵[BB]=1↑''
BB←(1-∨/¨'RBQK'=⊂⍵[(,K)/,⍳⍴K])/'RBQK'
'K'=BB:×/∨/¨(⍳1--1)=⊂R∨-R
1-∨/(1-(⍳1--1)='RB'⍳BB)×(=/,{∨/1-×⍵})R∨-R:1-1
×/(1↑'')=⍵[B--(×⊂R)×⍳-1-∨/R]}↑⍞⍞⍞⍞

Try it online!
Character statistics:
 -  1  B  )  (  ⍵  /  Q  ⍳  R  '  ∨  LF   K  ,  =  ←  }  { ⊂ × ¨ ⍴ ↑ ] [ ⍞ :
27 26 22 20 20 19 19 18 15 15 14 12  12  12 12 11 10 10 10 9 9 9 8 8 7 7 4 4
chars 28

Decisions made during optimizing the score:

Boolean guard : is needed for early returns from a dfn {}. Either LF (\n) or a statement separator character ⋄ cannot be removed as a side effect.
I didn't try to avoid four letters RBQK as avoiding it requires at least ⎕A and the code would get messy.
Removed composition ∘, reflex/flip ⍨, and self ⊢ in favor of dfns and explicitly writing down arguments with parentheses.
Removed ≢ (tally) in favor of ⍴ (shape/reshape), as tally = first element of shape, and reshape is unavoidable.
Removed ⍉ (transpose) and ⌽ (reverse/rotate) in favor of explicit indexing [] combined with index generator ⍳. Although there are one-char functions to do the indexing (⌷, ⊃), none is suitable for transpose operation.
Removed ⊃ (first/pick) in favor of ↑ (mix/take), as take is unavoidable and indexing+mix can simulate both uses of ⊃.
Removed ∧ (logical and) in favor of × (times), and | (abs/mod) by using the workaround x∨-x for |x (abs) and explicit membership ∊ (which was removed later) for x|y (mod). ⊤ was also removed that way.
Removed ∘.f in favor of f⊂ or f¨⊂. Similar trick was used to simulate ∊ (membership) and ~ (set minus): x∊y → ∨/¨x=⊂y, x~y → (1-∨/¨x=⊂y)/x
Removed ⍸ (extract indices of ones) with the workaround (,x)/,⍳⍴x.
Removed zero with 1-1, four by extracting from ⍴⍵, and + with --.
Removing blanks in plain code is easy, but this code has ' '. I avoided it with 1↑'', which "overtakes" length 1 from an empty string and gives a single blank. (It is a slightly different thing from the literal ' ', but they are compatible in most cases.)

Ungolfed with comments
{
  ⍝ 4×4 boolean matrix where 1 means a white piece
  whites←⍵∊'RBKQ'
  ⍝ one matrix per a winning position; roughly looks like
  ⍝ 1 0 0 0 ... 1 1 1 1 ... 1 0 0 0
  ⍝ 1 0 0 0     0 0 0 0     0 1 0 0
  ⍝ 1 0 0 0     0 0 0 0     0 0 1 0
  ⍝ 1 0 0 0     0 0 0 0     0 0 0 1
  masks←((⊂,⊂∘⌽)∘.=⍨⍳4),(⊢,⍉¨)(⍳4)⌽¨⊂4 4⍴4↑1
  ⍝ 1 if the white is about to win in that specific winning position
  filter←3=masks{≢⍸⍺∧⍵}¨⊂whites
  ⍝ No three-in-a-row: return false
  ~∨/filter:0

  ⍝ fetch the mask closest to white's winning
  mask←(⍸filter)⊃masks
  ⍝ coordinates of misplaced piece (from) and empty position (to)
  from←⍸whites>mask
  to←⍸whites<mask
  ⍝ No from: the remaining place must be empty
  ~≢from:' '=⍵[to]

  ⍝ get the type of the piece to move
  type←'RBKQ'~⍵[⍸mask]
  ⍝ Knight: true if 1×2 steps away, ignoring any obstacles
  'K'=type:∧/1 2∊|⊃from-to
  ⍝ two booleans indicating if it can move in diagonals (BQ) or
  ⍝ cardinal directions (RQ)
  diag cross←0 2⊤⊃'RB'⍳type
  ⍝ two booleans indicating if the direction to move is actually
  ⍝ diagonal or cardinal
  isdiag←=/|⊃from-to
  iscross←0∊|⊃from-to
  ⍝ Not aligned with the piece to move: return false
  diag cross⍱.∧isdiag iscross:0
  ⍝ If aligned, true if all cells between from and to are blanks
  ∧/' '=¯1↓⍵[from+(×v)×⍳⌈/⊃|v←to-from]
}↑{⍞}¨⍳4  ⍝ Take 4 lines of input, format as matrix and pass to function

C, 53 distinct chars
This uses "#%&()*+,-./01234569;<=>BKQR[\]acdefghilmnoprstu{|}, space and newline, distributed as follows: 24×\n, 33×, 20×", 2×#, 3×%, 16×&, 46×(, 46×), 13×*, 12×+, 35×,, 10×-, 2×., 2×/, 18×0, 9×1, 4×2, 4×3, 4×4, 4×5, 3×6, 3×9, 34×;, 6×<, 46×=, 2×>, 2×B, 2×K, 3×Q, 2×R, 8×[, 1×\, 8×], 39×a, 23×c, 5×d, 19×e, 15×f, 1×g, 22×h, 36×i, 5×l, 1×m, 35×n, 9×o, 33×p, 44×r, 20×s, 43×t, 15×u, 8×{, 14×|, 8×}.
#include <stdio.h>
#include <string.h>
int n(char*a,char*e,int i)
{int c=0;for(;a<e;)c+=*a++=="\n"[0];return c==i;}

int p(char *t, int r, int u)
{char h[]=" RBQK";char*p=t+r;char*a;int c=0;
for(int i=0;i<=3;++i,p+=u){char*s=strchr(h,*p);if(s&&s==h==0){++c;*s=" "[0];}else{a=p;}}
if(c-3)return 0;
char o=h[strspn(h, " ")];
p=strchr(t, o);
if(p==0)return*a==" "[0];
if(p<a){char*s=p;p=a;a=s;}
if(o=="K"[0])return(p-a)==3&&n(a,p,1)||(p-a)==2+5&&n(a,p,1)||(p-a)==9&&n(a,p,2)||(p-a)==11&&n(a,p,2);
if((p-a)%5==0||n(a,p,0))return (int)strchr("RQ", o);
return((p-a)%4==0&&n(a,p,(p-a)/4)||(p-a)%6==0&&n(a,p,(p-a)/6))&&strchr("BQ",o);}

int f(char *t)
{for(int i=0;i<4;++i)if(p(t,i,5)||p(t,i*5,1))return 1;
return p(t,0,6)||p(t,3,4);}

int main()
{char t[20];fread(t,19,1,stdin);t[19]=0;
if(f(t))puts("true");else puts("false");}

Explanation
#include <stdio.h>
#include <string.h>

/* count newlines */
int n(char *a, char *e)
{
    int c = 0;
    for (;a<e;) c += *a++=='\n';
    return c;
}

/* check a single row, column or diagonal */
int p(char *t, int start, int stride)
{
    char h[] = " RBQK"; /* pieces not in line */
    char *p = t+start;
    char *a;
    int c = 0;
    for (int i = 0;  i <= 3;  ++i, p+=stride) {
        char *s = strchr(h, *p);
        if (s && s == h == 0) {
            /* a white piece */
            ++c;
            *s = " "[0];
        } else {
            /* candidate target square */
            a = p;
        }
    }

    /* did we find three white pieces in this line? */
    if (c != 3)
        return 0;

    char o = h[strspn(h, " ")];

    p = strchr(t, o);

    if (p==0)
        return *a == " "[0];

    /* ensure a < p */
    if (p < a) {
        char *s = p;
        p = a;
        a = s;
    }

    /* knight moves */
    if (o == 'K')
        return (p-a)==3 && n(a,p)==1
            || (p-a)==7 && n(a,p)==1
            || (p-a)==9 && n(a,p)==2
            || (p-a)==11 && n(a,p)==2;

    /* rook moves */
    if ((p-a)%5 == 0 || n(a,p)==0)
        return 0==strchr("RQ", o)==0;

    /* bishop moves */
    return
        ((p-a)%4==0 && n(a,p)==(p-a)/4 ||
         (p-a)%6==0 && n(a,p)==(p-a)/6)
        && strchr("BQ", o);
}

/* main predicate function */
int f(char *t)
{
    /* try rows and columns */
    for (int i = 0;  i < 4;  ++i)
        if (p(t, i, 5) || p(t, i*5, 1))
            return 1;
    /* try diagonals */
    return p(t, 0, 6) || p(t, 3, 4);
}

int main()
{
    char t[20];
    fread(t, 19, 1, stdin);
    t[19]=0;
    if (f(t)) puts("true"); else puts("false");
}

It works by looking for a row, column or diagonal containing three of the white pieces; a points to the target position (not already containing a white piece).  Then the missing piece (o) is identified - it's the one we didn't remove from string h as we saw it.
If the piece is not on the board, it must be in the hand, and it can only be played into a space.  Otherwise (if we found it on the board), it must be in a position where it can move into the target square.  Since moves are reversible, we swap if necessary, so that a < p.
We test knight moves first - there are four legal downwards moves, and we avoid wrapping around the left/right edges of the board by verifying the number of newlines we pass.
After that, we test rook moves, and then bishop moves, using a similar algorithm (and a queen can use either of these moves).
Test program
int expect_true(char *board)
{
    if (strlen(board) != 19) {
        fprintf(stderr, "Wrong length board:\n%s\n\n", board);
        return 1;
    }
    if (!f(board)) {
        fprintf(stderr, "Expected true, but got false, for\n%s\n\n", board);
        return 1;
    }
    return 0;
}

int expect_false(char *board)
{
    if (strlen(board) != 19) {
        fprintf(stderr, "Wrong length board:\n%s\n\n", board);
        return 1;
    }
    if (f(board)) {
        fprintf(stderr, "Expected false, but got true, for\n%s\n\n", board);
        return 1;
    }
    return 0;
}

int main()
{
    return
        + expect_true("rkb \n"
                      "    \n"
                      "    \n"
                      "RB Q")
        + expect_false("rk  \n"
                       "    \n"
                       "    \n"
                       "RBbQ")
        + expect_true("rk  \n"
                      " K  \n"
                      "    \n"
                      "RBbQ")
        + expect_true("rk  \n"
                      "    \n"
                      "K   \n"
                      "RBbQ")
        + expect_true("rkRB\n"
                       "    \n"
                       " Qb \n"
                       "K   ")
        + expect_true("rk  \n"
                      "    \n"
                      "K   \n"
                      "RBbQ");
}

Counting program (in C++)
#include<algorithm>
#include<iostream>
#include<map>

int main()
{
    std::map<char,int> m;
    for (int c;  (c = getchar()) != EOF; )
        ++m[c];

    for (auto e: m)
        std::cout << e.first;

    std::cout << "\n distributed as follows: ";
    for (auto e: m)
        std::cout << e.second << "×`" << e.first << "`, ";
}

Suggest 6+3 for 9 And 16+3 for 19

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