text:
Golf a Venn Diagram generator
Golf a Venn Diagram generator

In order to properly celebrate John Venn's 180th birthday, today your task will be creating a program that outputs a Venn Diagram!
Input:
A positive integer N that will define the range of numbers appearing in the diagram (From zero to N) and three sets of positive integers.
Output:
A 3 set Venn diagram showing all integers from 0 to N and the relationships of the sets by displaying them in the proper regions of the diagram, similar to this one.
Notes

Use stdin (or whatever your language's equivalent is) to get the
values.
You can define the input format for the sets and for N (Separated by comma, slash or whatever works best for you).
Numbers that do not appear in any of the sets but are within the specified range must appear on the diagram, just not inside any region.
The sets don't need to be named.
The output can be a drawing or ascii-art.
The diagram can have any shape as long as the boundaries are unambiguously distinguishable (if you chose ASCII art, using + (or similar) for crossing boundaries is essential, for example).
The regions may but don't have to be shaded.
Any built-in functions or third party libraries that generate Venn Diagrams are disallowed.
Standard loopholes apply.

This is code-golf, so the shortest code, in bytes, wins.

It looks like you should have added a note that solutions have to scale for arbitrary input sizes. Currently only a few of them do that (as far as I can tell only the ASCII ones). I don't like changing rules after the contest has started, but without this requirement, someone could probably really abuse it with a simple layout that only works for one character in each set (if I did that I'd probably cut the code size to a third or so).

@MartinBüttner Yeah, some of them scale pretty bad. But adding a note now that there are 7 answers seems like a bad idea. Should add the note and them comment on everyone's post to let them know that the diagram should scale well up to X?

Setting a limit will still allow just hard-coding that limit. I think that proper scaling is actually the most difficult part of the challenge. So either leave it as it is, or change it to say that it must deal with arbitrary set sizes (which technically isn't even a change, since you didn't limit the input sizes I think arbirtrary input sizes should be assumed anyway).

@Ryan Note that I state "by displaying them in the proper regions of the diagram" in the output section. Some answers (yours included) don't display the innermost section correctly if said section has more than 5 elements, so I think it's invalid

Relevant xkcd: https://xkcd.com/1810/

Mathematica 343 264
UnGolfed
m=Input[]; data=Input[];

(* The circles to represent set boundaries *)
{R1,R2,R3}=Circle[#,5]&/@{{-2,8.5},{2,8.5},{0,5}};

(*converts  {1,0,1} to base 10, ie, the number 5.
bool[x_]:=FromDigits[Boole[x],2]

(* determines the region in which each number from 0 to `m` resides *)
encode[num_]:=bool[Table[MemberQ[data[[k]],num],{k,3}]]

(*Centroid of each region; the first is a location for numbers in none of the three sets *)
points={{7,4},{0,2},{4,10},{3,6},{-4,10},{-3,6},{0,11},{0,7}}

(* Plots the venn diagram with numbers in regions *)
Graphics[{
Text@@@({#[[1]],points[[#[[2]]+1]]}&/@({#[[All,1]],#[[1,2]]}&/@GatherBy[{#,encode[#]}&/@Range[0,m],Last])),
Opacity[.1],R1,R2,R3
}]

Assuming
10 was input for m and {{1,2,3,4,5,9},{1,2,3,6,8},{7,2,9}} was input for d,

Golfed 264
I was surprised that all of the computation could be carried out within the Graphics function itself.  With the exception of the inputs, it is a one-liner.
m=Input[];d=Input[]
Graphics@{Text@@@({#[[1]],{{7,4},{0,2},{4,10},{3,6},{-4,10},{-3,6},{0,11},{0,7}}[[#[[2]]+1]]}&/@({#[[All,1]],#[[1,2]]}&/@GatherBy[{#,FromDigits[Boole[Table[d[[k]]~MemberQ~#,{k,3}]],2]}&/@Range[0,m],Last])),Circle[#,5]&/@{{-2,8.5},{2,8.5},{0,5}}}

+1 for the appearance of the circles. I'm surprised they look so good in grey. The scattering of the numbers is weird though. You're using RandomSample to pick the location?

Gray works because the opacity is 10%.  RandomSample was used to pick the location. Once a location has been chosen, it is removed from the set of candidates for additional picks. I played around with other methods (e.g. employing the centroid of a sub-region, but didn't like the results). BTW, I like your approach to fitting labels.

To save characters, I switched to Circles, so the gray disks are gone.  Most of the savings comes from the fact that all members of a region are plotted at the center of that region.

Ruby, 654 590 566 542 505 bytes
This was fun. I used ASCII. I wasn't able to test every possible combination yet, so if you find a glitchy test case, please let me know.
require'set'
u=(0..gets.to_i).to_set
a,b,c=eval(gets).map &:to_set
i=' '
m,M,n,N,o,O,p,P,q,Q,r,R,s,S=[a-b-c,b-a-c,c-a-b,a&b-c,b&c-a,a&c-b,a&b&c].map{|u|[t=u.to_a*i,t.size]}.flatten
H,V,X=?─,?│,?┼
puts'┌'+H*(A=[1+M+[P,S].max,1+R].max)+?┐+(u-a-b-c).to_a*i,V+i*M+?┌+(b=H*(T=-M+U=A-1)+X+H*(B=[N,Q].max))+?┐,V+m+V+p+i*(T-P)+V+n+i*(B-N)+V,'│┌'+H*(K=M-1)+X+b+X+H*(C=[O-B-1,0].max)+?┐,(v=V*2+i*K)+V+s+i*(T-S)+V+q+i*(B-Q)+V+i*C+V,v+?└+b+?┘+i*C+V,V*2+r+i*(U-R)+V+o+i*(-O+D=B+C+1)+V,'└┼'+H*U+?┘+i*D+V,' └'+H*(A+D)+?┘

It expects the input on STDIN in the following format
10
[[1,2,3,4,5,9],[1,2,3,6,8],[7,2,9]]

And will then reward you with this beauty
┌───────┐0 10
│   ┌───┼───┐
│4 5│1 3│6 8│
│┌──┼───┼───┼┐
││  │2  │   ││
││  └───┼───┘│
││9     │7   │
└┼──────┘    │
 └───────────┘

I don't think I can be bothered to add an ungolfed version. Please have a look at the original version in the edit history for a somewhat more readable version.
This could certainly be golfed further by making the set boundaries less tight or even keeping them fixed like some of the graphical ones do, but I prefer that it looks nice and is done "properly" despite being golfed.

If you hadn't reach today's cap you'd reach the 10K club today with this answer, what a pity

@WilliamBarbosa Maybe it'll give me the necessary upvotes tomorrow. ;)

That's a nice looking Venn diagram. I'm guessing the appearance of the diagram is the main reason for all you upvotes. What happens for larger sets? I'm guessing it stays the same height and just gets wider and wider?

@steveverrill yes exactly. each of the 8 subsets is just printed as a space delimited list in the right position. the boundaries are always the same shape, and each section's width is determined to be the minimum possible to fit everything inside. of course, it might look nicer if I computed line break to keep each subset roughly square, but then again this is code-golf after all ;). also it looks even better without the additional spacing between lines

Saw the little angle characters and did a double-take, thinking it was APL or something. :)

BBC BASIC, 243 ASCII characters (tokenised file size 211 bytes)
Download emulator at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html
Golfed
  INPUT"N",n
  DIMs(n+1)
  FORi=0TO2PRINT"S";i
  REPEATINPUTx:s(x)=s(x)+2^i:UNTILx>n
  NEXTMODE4r=360CIRCLE460,r,r
  CIRCLE640,664,r
  CIRCLE820,r,r
  FORi=0TO7FORx=0TOn:IFs(x)=i PRINT;x
  NEXTREADa
  VDU28,a+1792;a+5;
  NEXT
  DATA19,4873,2572,4893,2586,5907,3091,34

BBC Basic is very arbitrary about which newlines/whitespace you can eliminate. Apart from stripping out unnecessary newlines there's another trick here that's not in the ungolfed version: I assign the viewport (see explanation below in ungolfed comments) at the END of the plotting loop, not at the beginning. This means that the elements outside the set are plotted the top left, and the cursor is trapped in a viewport at top right at the end of the program. The reason for this is to eliminate the VDU26.
Ungolfed
Each set of numbers is terminated by the user entering the number N+1 (a slightly unusual choice, this is to avoid errors caused by trying to write outside the range of an array.) Then it changes from a text mode to a graphics mode and plots the Venn diagram.
The input data is stored in an array, one cell for each value to be displayed. The data is stored as a 3-bit value: 1 for Set0 + 2 for Set1  + 4 for Set2 giving a number in the range 0 to 7. BBC basic has no shift operator, so the power operator is used instead: 2^i instead of 1<<i in C for example.
After plotting the circles, an outer loops goes through each of the eight regions, moving to the required coordinates (as per a data table.) An inner loop prints all the numbers in that region (those with the corresponding 3-bit value in the array.)
  INPUT"N",n                                 :REM create an array called s() with range 0..n+1
  DIMs(n+1)
  FORi=0TO2
    PRINT"S";i                               :REM prompt the user for data for set 0, set 1 and set 2.
    REPEATINPUTx:s(x)=s(x)+2^i:UNTILx>n      :REM input numbers and store as a bit table. Repeat until user enters n+1.
  NEXT
  MODE4                                      :REM change to graphics mode.
  r=360
  CIRCLE460,r,r                              :REM plot a circle at x,y,r.
  CIRCLE640,664,r                            :REM for the bottom two circles y=r.
  CIRCLE820,r,r
  FORi=0TO7                                  :REM for each region of the venn diagram
    READa                                    :REM read a 2 byte value for the  coordinates of the top left corner of a text viewport from the DATA statement: x+256y
    VDU28,a+1792;a+5;                        :REM create a 5x7 viewport (limits each region to 7 numbers.) 1792=7*256
    FORx=0TOn:IFs(x)=i PRINT;x               :REM print all numbers in the array belonging to that region
    NEXT
  NEXT
  VDU26                                      :REM Restore the viewport to the whole screen, to ensure the command prompt does not mess up the display at the end of the program.
  DATA34,19,4873,2572,4893,2586,5907,3091

Montage of typical input and output (ungolfed version)
In the golfed version, the position of the numbers outside the sets is exchanged with the command prompt >.

Does this work for arbitrarily large inputs?

@MartinBüttner in principle yes the algorithm can do it, but the display lets it down (as is likely to be the problem with other solutions.) I hint in the program comments that each region is limited to 7 numbers before it begins to scroll (the numbers are in a vertical column as I thought wrapping would look horrible.)  The emulator I am using can handle much higher screen resolutions, but I have gone for one of the "authentic" BBC micro screen modes which is quite limiting. If someone ports this to Java, the only practical limit will be the human ability to read the diagram.

Ah yeah, I was just wondering whether the circles would adapt to the input size... of course my solution will also be unreadable for large inputs if your terminal wraps the lines, but as long as it's displayed with scrollbars it can handle any input size.

even if this was ported to java you'd have to add code to make the circles bigger for more text

Javascript 1235
http://jsfiddle.net/44a4L/7/
Tested in google chrome v36.
Input is taken in the variables upper, set1, set2 and set3.
Update: Now automatically scales depending on the size of input.
function t(e,t){z.getElementById(e).innerHTML+=" "+t}z=document;s=200+upper*20;z.body.innerHTML+="

";for(i=0;i<=upper;i++){i1=i2=i3=false;if(set1.indexOf(i)!=-1)i1=true;if(set2.indexOf(i)!=-1)i2=true;if(set3.indexOf(i)!=-1)i3=true;if(i1&&i2&&i3)t("s123",i);else if(i1&&i2)t("s12",i);else if(i1&&i3)t("s13",i);else if(i2&&i3)t("s23",i);else if(i1)t("s1",i);else if(i2)t("s2",i);else if(i3)t("s3",i);else t("m",i)}

Sample output:

Pretty nice! I was able to squeeze it a bit tighter, see http://jsfiddle.net/44a4L/2/ - look at the "t" function, CSS and body.innerHTML. Same logic though. I'm sure it could still be squeezed.

This is the most beautiful one so far, it's a pity it doesn't scale well. Three elements inside the innermost area makes it break. Do you plan on making it scale somehow?

@WilliamBarbosa scaling is implemented now

Gorgeous! Stunning! Spectacular! (Had to use more than one superlative because SE hates brevity.)

HTML + JavaScript (E6) 752 761
Input format: max set1 set2 set3 (each set is a comma separated list of numbers)
Example: 10 1,2,3,4,5,9 1,2,3,6,8 7,2,9

Example 2: 30 2,4,6,8,10,12,14,16,18,30 3,6,9,12,15,18,21,30 5,10,15,20,25,30

All the sections auto size thanks to html rendering.

Javascript E5 version Works in Chrome and MSIE 10 (maybe 9)

Not (so) golfed

Python - 603
import re
n,a,b,c=eval(input())
h=set(range(n+1))-a-b-c
g=a&b&c
d,e,f=a&b-g,b&c-g,a&c-g
l,m=set(a),set(b)
a-=b|c
b-=l|c
c-=l|m
for t in'abcdefgh':exec("%s=' '.join(map(str,%s))"%(2*(t,)))
l=len
x,y,z=max(l(a),l(f)+2,3),l(max(d,g)),max(l(b),l(e)+2,l(c)-l(f+g)-2,3)
j=[0]*4
for t in'abcdefg':exec("%s=%s.ljust([x,z,x+y+z-2,y,z-2,x-2,y][ord('%s')-97])+'|'"%(3*(t,)))
s='\d| '
w=re.sub
for r in (1,3):q=r//2;j[r]=['','| '][q]+'|'+[a+d+b,f+g+e][q]+['',' |'][q];j[r-1]=w('\|','+',w(s,'-',j[r]))
j[0]+=h
o=j[2]
j[2]='| +'+j[2][3:-3]+'+ |'
p='  |'+c
q='  '+w('\|','+',w(s,'-',p))[2:]
for l in j+[o,p,q]:print(l)

Input is N followed by the three sets, seperated by commas (e.g. 8, {1,2,4}, {2,3,4,5}, {4,6,8}).
It outputs a set in ACSII art like the following:
+---+-+---+0 7
|1  | |3 5|
| +-+-+-+ |
| |2|4| | |
+-+-+-+-+-+
  |6 8  |
  +-----+

Haha, two nearly identical solutions within 5 minutes. (3 hours after the challenge was posted...)

Please refer to note number 6. Your edges and crossing boundaries need to be a different character, such as "+".

perl 388b 346b 488b
This has output similar to another entry:
@a=split($",<>);
$n=pop @a;
@a=map[split(',')],@a;
for$i(0..2){$b{$_}+=1<<$i foreach@{$a[$i]}}
push@{$c[$b{$_}]},$_ for(0..$n);
$l|=length($d[$_]=join($",@{$c[$_]}))for(0..$n);
print$h=(("+-"."-"x$l)x3)."+
";
sub j{sprintf"% ".(sprintf"%ds",$l+($_[0]<4)+($_[0]==7)),$d[$_[0]]}
sub r{join('|',map{j($_)}@_)}
$h=~s/\+-/|+/;
$h=~s/-\+$/+|/;
print "|".r(1,3,2)."|
".$h;
$h=~s/[|+]{2}/++/g;
print "||".r(5,7,6)."||
".$h;
$h=~s/\+\+/ +/;
$h=~s/\+\+/+ /;
$h=~s/-\+-/---/g;
$l=$l*3+3;print " |".j(4)."|
",$h,$d[0]

Test run and output:
# echo "1,2,3,7,13 2,3,8,11,13,6,9 3,4,5,11,12,13,14 15" | perl venn.pl ;echo
+----------------+----------------+----------------+
|             1 7|               2|           6 8 9|
|+---------------+----------------+---------------+|
||               |            3 13|             11||
++---------------+----------------+---------------++
 |                                       4 5 12 14|
 +------------------------------------------------+

Hm, I'm not sure the layout is really unambiguous if you haven't seen the input.

You're right, this isn't venn-y enough

@WilliamBarbosa ok, I made it look like faubiguy's entry

Python 3 - 353
# 353 bytes, input format like: 6 1,2,3 2,3,4 1,3,4
import sys
from turtle import*
_,n,*q=sys.argv
n=set(range(int(n)))
a,b,c=map(set,map(eval,q))
for x,y in(0,0),(-115,-185),(115,-185):goto(x,y),pd(),circle(200),up()
for x,y,s in(200,331,n-a-b-c),(-101,278,a-b-c),(-254,-49,b-a-c),(95,-49,c-a-b),(-172,164,a&b-c),(58,164,a&c-b),(-49,-39,b&c-a),(-49,52,a&b&c):goto(x,y),write(s or'',font=None)
ht()
done()

Did anybody else play with Logo as a kid?
Sample: python3 turtletest.py 15 1,2,3,4,5,9,10,12 1,3,4,6,7,9 1,2,7,8,9

will the font/circles scale for arbitrarily large input?

No, still thinking about that one.

@JasonS Still thinking?

T-SQL 2095
Assumes @N is an int containing N. Assumes @A, @B, and @C are tables containing the three sets of numbers. Didn't try to golf it too much.
DECLARE @D INT=@N,@E INT=0,@F CHAR='/',@G CHAR='\',@H CHAR='-',@I CHAR='|',@J CHAR='+'DECLARE @ TABLE(Z INT,Y INT,X INT,W INT,V INT,U INT,T INT,S INT)INSERT INTO @(Z)SELECT A.P FROM @A A JOIN @B B ON A.P=B.P JOIN @C C ON A.P=C.P INSERT INTO @(Y)SELECT A.P FROM @A A JOIN @B B ON A.P=B.P LEFT JOIN @C C ON A.P=C.P WHERE C.P IS NULL INSERT INTO @(X)SELECT C.P FROM @C C JOIN @A A ON C.P=A.P LEFT JOIN @B B ON C.P=B.P WHERE B.P IS NULL INSERT INTO @(W)SELECT B.P FROM @B B JOIN @C C ON B.P=C.P LEFT JOIN @A A ON B.P=A.P WHERE A.P IS NULL INSERT INTO @(V)SELECT A.P FROM @A A LEFT JOIN @B B ON A.P=B.P LEFT JOIN @C C ON A.P=C.P WHERE C.P IS NULL AND B.P IS NULL INSERT INTO @(U)SELECT C.P FROM @C C LEFT JOIN @A A ON C.P=A.P LEFT JOIN @B B ON C.P=B.P WHERE B.P IS NULL AND A.P IS NULL INSERT INTO @(T)SELECT B.P FROM @B B LEFT JOIN @C C ON B.P=C.P LEFT JOIN @A A ON B.P=A.P WHERE A.P IS NULL AND C.P IS NULL WHILE @N>=0BEGIN INSERT INTO @(S)SELECT @N WHERE @N NOT IN(SELECT*FROM @A UNION SELECT*FROM @B UNION SELECT*FROM @C)SET @N-=1 END DECLARE @Z TABLE(A CHAR(5),B CHAR(5),C CHAR(5),D CHAR(5),E CHAR(5),F CHAR(5),G CHAR(5),H CHAR(5))INSERT INTO @Z SELECT @F,@H,@F,@H,@G,@H,@G,''WHILE @E<=@D BEGIN INSERT INTO @Z SELECT @I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT V FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT X FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT U FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT S FROM @)),'')SET @E+=1 END INSERT INTO @Z SELECT @F,@H,@J,@H,@G,'',@I,''SET @E=0WHILE @E<=@D BEGIN INSERT INTO @Z SELECT @I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT Y FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT Z FROM @)),''),@I,'',@I,''SET @E+=1 END INSERT INTO @Z SELECT @G,@H,@J,@H,@F,'',@I,''SET @E=0WHILE @E<=@D BEGIN INSERT INTO @Z SELECT @I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT T FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT W FROM @)),''),@I,'',@I,''SET @E+=1 END INSERT INTO @Z SELECT @G,@H,@G,@H,@F,@H,@F,''SELECT*FROM @Z

Less golfed version:
--finding the sets
DECLARE @D INT=@N,@E INT=0,@F CHAR='/',@G CHAR='\',@H CHAR='-',@I CHAR='|',@J CHAR='+'
DECLARE @ TABLE(Z INT,Y INT,X INT,W INT,V INT,U INT,T INT,S INT)
INSERT INTO @(Z)
SELECT A.P FROM @A A JOIN @B B ON A.P=B.P JOIN @C C ON A.P=C.P
INSERT INTO @(Y)
SELECT A.P FROM @A A JOIN @B B ON A.P=B.P LEFT JOIN @C C ON A.P=C.P WHERE C.P IS NULL
INSERT INTO @(X)
SELECT C.P FROM @C C JOIN @A A ON C.P=A.P LEFT JOIN @B B ON C.P=B.P WHERE B.P IS NULL
INSERT INTO @(W)
SELECT B.P FROM @B B JOIN @C C ON B.P=C.P LEFT JOIN @A A ON B.P=A.P WHERE A.P IS NULL
INSERT INTO @(V)
SELECT A.P FROM @A A LEFT JOIN @B B ON A.P=B.P LEFT JOIN @C C ON A.P=C.P WHERE C.P IS NULL AND B.P IS NULL
INSERT INTO @(U)
SELECT C.P FROM @C C LEFT JOIN @A A ON C.P=A.P LEFT JOIN @B B ON C.P=B.P WHERE B.P IS NULL AND A.P IS NULL
INSERT INTO @(T)
SELECT B.P FROM @B B LEFT JOIN @C C ON B.P=C.P LEFT JOIN @A A ON B.P=A.P WHERE A.P IS NULL AND C.P IS NULL
WHILE @N>=0
BEGIN
    INSERT INTO @(S)
    SELECT @N WHERE @N NOT IN(SELECT*FROM @A UNION SELECT*FROM @B UNION SELECT*FROM @C)
    SET @N-=1
END

--displaying the venn diagram
DECLARE @Z TABLE(A CHAR(5),B CHAR(5),C CHAR(5),D CHAR(5),E CHAR(5),F CHAR(5),G CHAR(5),H CHAR(5))
INSERT INTO @Z
SELECT @F,@H,@F,@H,@G,@H,@G,''
WHILE @E<=@D
BEGIN
    INSERT INTO @Z
    SELECT @I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT V FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT X FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT U FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT S FROM @)),'')
    SET @E+=1
END
INSERT INTO @Z
SELECT @F,@H,@J,@H,@G,'',@I,''
SET @E=0
WHILE @E<=@D
BEGIN
    INSERT INTO @Z
    SELECT @I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT Y FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT Z FROM @)),''),@I,'',@I,''
    SET @E+=1
END
INSERT INTO @Z
SELECT @G,@H,@J,@H,@F,'',@I,''
SET @E=0
WHILE @E<=@D
BEGIN
    INSERT INTO @Z
    SELECT @I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT T FROM @)),''),@I,ISNULL((SELECT CONVERT(CHAR,@E,5) WHERE @E IN(SELECT W FROM @)),''),@I,'',@I,''
    SET @E+=1
END
INSERT INTO @Z
SELECT @G,@H,@G,@H,@F,@H,@F,''
SELECT*FROM @Z


text:
Calculate the Riemann Zeta Function
Calculate the Riemann zeta function to the maximum primitive precision in your language (for C-family, that would be double or long double, var in JS, etc.) No need for BigDecimal or the like unless you need it to use a double-equivalent precision.

Efficiency (be sane) doesn't matter.
If it's not in a common language, I can't test it, but I hope somebody does.
No libraries or built-in math functions.
Recursion is cool!

See my JS entry for a sample program.

Judging by your example implementation it only needs to work for real inputs greater 1?

@MartinBüttner Yes.

And what about those math functions? You're using the power function yourself. Which math functions are allowed and which aren't?

How is input/output to be handled? Examples?

@MartinBüttner Okay. Only basic math functions equivalent to Java/JS's Math.

I think without power function you will be pretty lost, and many programming languages do not require a math library for calculating powers! The next thing that is unclear: how dos double apply to complex arguments? (Since the zeta function is defined for Re(z)>0 where z is complex.)

@SimonKuang You may want to list those functions in your question.

I was hovering over the submit post button right when it got closed.  That's life I guess :P

JavaScript (Chrome): 78
function zeta(r){for(var t=0,a=1,n=1;t!=a;a=t,t+=1/Math.pow(n++,r));return t}

No math libraries

And apart from that I think it will fail for r=1+epsilon where epsilon>0 small enough. Even though one summand might be smaller than working precision, the sum of the following summands can be bigger. Best example for this is the series sum 1/n for n=1 to infinity = zeta(1).

source: Stack Exchange

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

sort: votes


text:
Raise to the Power
Challenge
Challenge is writing a program that takes a positive numbers a and a nonzero number b and outputs a^b (a raised to the power b).  You can only use + - * / abs() as mathematical functions/operators. These can only be applied to scalar values, but not to whole lists or arrays.
Examples:
1.234 ^ 5.678 = 3.29980
4.5   ^ 4.5   = 869.874
4.5   ^-4.5   = 0.00114959

Relevant: http://xkcd.com/217/
Details
You can write a function or a similar construct for using in console. If you cannot use console input you can assume that both numbers are saved in variables and ouptut via standard output or writing to a file. The output has to be correct to at least 4 significat digits. You can assume that both a and b are nonzero. A runtime of significantly more than 1 minute is not acceptable. The least number of bytes will win. Please explain your program and your algorithm.
EDIT: Only positive bases have to be considered. You can assume a>0. Be aware that both numbers do not have to be integers!!!

Are you asking us to raise to a decimal power? Like say, 4.5 ^ 4.5?

Does this mean we have to output imaginary numbers too if the base is negative?

What should the output for -0.5 ** 0.5 be?

Ok I did not think of that case, thank you: Negative bases  must not be correctly implemented. @fuandon exactly, real numbers can have decimals (at least in most programming languages=)

I'd like to add a test case with b<0: `4.5 ^ -4.5 = 0.0011496'

Aw, Python's e syntax doesn't work with floats. :c

"positive numbers" -> "positive number"

Python, 77
As with some other answers this is based on log and exp. But the functions are computed by numerically solving ordinary differential equations.
def f(a,b,y=1):
 if a<1:a=1/a;b=-b
 while a>1:a/=1e-7+1;y*=b*1e-7+1
 return y

Does it satisfy the requirements? For the examples in the question, yes. For large a, it will take a very long time. For large a or b, it will become inaccurate.
Examples:
a            b            f(a, b)      pow(a, b)      <1e-5 rel error?
       1.234        5.678       3.2998       3.2998   OK
         4.5          4.5      869.873      869.874   OK
         4.5         -4.5   0.00114959   0.00114959   OK
         0.5          0.5     0.707107     0.707107   OK
         0.5         -0.5      1.41421      1.41421   OK
          80            5  3.27679e+09   3.2768e+09   OK
     2.71828      3.14159      23.1407      23.1407   OK

Update: flawr asked for more detail on the maths so here you go. I considered the following initial value problems:

x'(t) = x(t), with x(0) = 1. The solution is exp(t).
y'(t) = by(t), with y(0) = 1. The solution is exp(bt).

If I can find the value of t such that x(t) = a, then I'll have y(t) = exp(bt) = a^b. The simplest way to numerically solve an initial value problem is Euler's method. You compute the derivative the function is supposed to have, and then take a, step, in the direction of the derivative, and proportional to it, but scaled by a tiny constant. So that's what I do, take tiny steps until x is as big as a, and then see what y is at that time. Well, that's the way I thought of it. In my code, t is never explicitly computed (it is 1e-7 * the number of steps of the while loop), and I saved some characters by doing the calculations for x with a instead.

That looks great, I am happy to see another different approach! Can you tell us a bit more about these differential equations? I know generally what they are but I was not able to figure out how you program uses them=)

@flawr: OK, I updated with some more details about the maths.

JavaScript (E6) 155 174 191
Edit 2 As suggested by @bebe, using recursive function (performe worse but shorter)
Slightly changed R function to avoid 'too much recursion'
Test suite added. The function performs well for bases < 3000 and exponent in range -50..50.
Edit Golfed more and better precision
Any real number can be approximate with a rational number (and IEEE standard 'real' numbers store rationals in fact).
Any rational number can be expressed as a fraction a/b with a and b integers. x^(a/b) is root b of (x^a) or (root b of x)^a.
Integer exponentiation is quite easy by squaring.
Integer root can be approximated using numerical methods.
Code
P=(x,e)=>(
  f=1e7,e<0&&(x=1/x,e=-e),
  F=(b,e,r=1)=>e?F(b*b,e>>1,e&1?r*b:r):r,
  R=(b,e,g=1,y=1e-30,d=(b/F(g,e-1)-g)/e)=>d>y|d<-y?R(b,e,g+d,y/.99):g,
  F(R(x,f),e*f)
)

Test In FireFox or FireBug console
for (i=0;i<100;i++)
{
  b=Math.random()*3000
  e=Math.random()*100-50
  p1=Math.pow(b,e) // standard power function, to check
  p2=P(b,e)
  d=(p1-p2)/p1 // relative difference
  if (!isFinite(p2) || d > 0.001)
    console.log(i, b, e, p1, p2, d.toFixed(3))
}

Good job, not terribly precise but it the algorithm is nice=)

Can you explain what this e&1&&(r*=b) does, except multiplying r by b?

@flawr if(e&1 != 0) r *= b

Thanks, I was not aware of that exploit, but it seems to be a nice one for golfing=)

oh and 149:
P=(x,e,f=1<<24)=>(e<0&&(x=1/x,e=-e),((b,e,r=1)=>e?F(b*b,e>>1,e&1?r*b:r):r)(((b,e,g=1,y=1e-16)=>(d=(b/F(g,e-1)-g)/e,d>y|d<-y?R(b,e,g+d):g))(x,f),e*f))

@bebe unbelievable (and ununderstandable... recursion instead of loops?)

sorry for bothering you again but i forgot to name the two functions. this is valid: P=(x,e,f=1<<24)=>(e<0&&(x=1/x,e=-e),((b,e,r=1)=>e?F(b*b,e>>1,e&1?r*b:r):r)(((b,e,g=1,y=1e-16)=>(d=(b/F(g,e-1)-g)/e,d>y|d<-y?R(b,e,g+d):g))(x,f),e*f)) i hope you can golf down more (tweet size maybe?) by losing precision and skipping operations (that i honestly don't understand)

@bebe don't leave this way!U posted the same code...

here's the working code: P=(x,e)=>(F=(b,e,r=1)=>e?F(b*b,e>>1,e&1?r*b:r):r,R=(b,e,g=1,y=1e-16,d=(b/F(g,e-1)-g)/e)=>d>y|d<-y?R(b,e,g+d):g,e<0&&(x=1/x,e=-e),f=1<<24,F(R(x,f),e*f)) (i must be tired)

Haskell, 85 90
Standard exp-log algorithm.  Now with different name, shaving off a few more characters:
a%b|a>1=1/(1/a)%b|0<1=sum$scanl((/).((-b*foldr1(\n b->(1-a)*(b+1/n))c)*))1c
c=[1..99]

raise is now called (%), or % in infix notation, even making its use consume fewer bytes: 4.5%(-4.5)
The ungolfed version also uses just 172 bytes:
raise a b | a > 1     = 1 / raise (1/a) b
          | otherwise = expo (-b* ln (1-a))

ln x = foldr1 (\n a -> x*a+x/n) [1..99]

expo x = sum $ scanl ((/) . (x*)) 1 [1..99]

JS (ES6), 103 bytes
t=(x,m,f)=>{for(r=i=s=u=1;i<1<<7+f;r+=s/(u=i++*(f?1:u)))s*=m;return r};e=(a,b)=>t(b,t(a,1-1/a,9)*b-b,0)

Examples :
e(1.234,5.678) = 3.299798925315965
e(4.5,4.5)     = 869.8739233782269
e(4.5,-4.5)    = 0.0011495918812070608

Use Taylor series.
b^x = 1 + ln(b)*x/1! + (ln(b)*x)^2/2! + (ln(b)*x)^3/3! + (ln(b)*x)^4/4! + ...
with natural logarithm approximation :
ln(b) = (1-1/x) + (1-1/x)^2/2 + (1-1/x)^3/3 + (1-1/x)^4/4 + ...
I used 128 iterations to compute b^x (more iterations is difficult due to factorial) and 262144 iterations for ln(b)

Maybe you should golf less but add more precision: e(80,5) ->1555962210.2240903 - should be 3276800000

@edc65, you're right, fixed for 5 more chars.

It's very nice to see some different approaches!

golflua 120
I use the fact that
a^b = exp(log(a^b)) = exp(b*log(a))

and wrote my own log & exp functions. The values a and b need to be entered on newlines when run in the terminal:
\L(x)g=0~@ i=1,50 c=(x-1)/x~@j=2,i c = c*(x-1)/x$g=g+c/i$~g$\E(x)g=1;R=1e7~@i=1,R g=g*(1+x/R)$~g$a=I.r()b=I.r()w(E(b*L(a)))

Sample runs:
4.5, 4.5  ==> 869.87104890175
4.5, -4.5 ==> 0.0011495904124065
3.0, 2.33 ==> 12.932794624815
9.0, 0.0  ==> 1
2.0, 2.0  ==> 3.9999996172672

An ungolfed Lua version is,
-- returns log
function L(x)
   g = 0
   for i=1,50 do
      c=(x-1)/x
      for j=2,i do
         c = c*(x-1)/x
      end
      g = g + c/i
   end
   return g
end

-- returns exp
function E(x)
   g=1;L=9999999
   for i=1,L do
      g=g*(1+x/L)
   end
   return g
end

a=io.read()
b=io.read()

print(E(b*L(a)))
print(a^b)

Can you provide some example outputs?

@flawr: I suppose I can...and now done

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


text:
Determine a string's Scrabble score and validity
Your task is to determine if a given string is of proper length and can be represented with Scrabble tiles and, if so, output the sum of each letter's score.
If you don't know how to play Scrabble:, you have 100 tiles with various letters A–Z printed on them, as well as two wildcards that can represent any letter. Each letter has a certain number of points, and each tile (but not necessarily word) can only be used once. When a word is played, the point value of each tile used is added up, which becomes the score. As there are a limited number of letters available, a word can only have a certain letter as many times as that letter has tiles + any unused wildcards. The Scrabble board is 15×15 cells, so the word must be between 2 and 15 characters long.
For a list of the quantity and score of each letter in the English version, see below or http://boardgames.about.com/od/scrabble/a/tile_distribute.htm (archive).

Letter  Qty  Points        Letter  Qty  Points
-------------------        -------------------
A       9    1             O       8    1
B       2    3             P       2    3
C       2    3             Q       1    10
D       4    2             R       6    1
E       12   1             S       4    1
F       2    4             T       6    1
G       3    2             U       4    1
H       2    4             V       2    4
I       9    1             W       2    4
J       1    8             X       1    8
K       1    5             Y       2    4
L       4    1             Z       1    10
M       2    3             [wild]  2    0
N       6    1

Further rules

The program shall take a single string of input from STDIN or the like.
The input will always contain only uppercase letters.
If the string contains more copies of a letter than there are unused wildcards or tiles for that letter OR the string's length is not between 2 and 15 inclusive, the program should output Invalid.
Otherwise, the score should be added up with using data from the chart above and output.
Do not use wildcards unless necessary.
Do not worry about bonuses such as double word scores or whether the string is a real word.
The program shall output the result through STDOUT or the like.
Loopholes that are forbidden by default are not allowed.
Using an external source such as a website, as well as any libraries, APIs, functions, or the like that calculate Scrabble scores or proper quantities are not alllowed.
This is code-golf, so fewest bytes wins.

Walkthrough
Input: CODEGOLF
C -> 3, O -> 1, D -> 2, E -> 1, G -> 2, O -> 1, L -> 1, F -> 4
3 + 1 + 2 + 1 + 2 + 1 + 1 + 4 = 15
Output: 15

Testcases

Input             Output
------------------------
SCRABBLE          14
JAZZ              19
STACKEXCHANGE     32
XYWFHQYVZVJKHFW   81
PIZZAZZ           Invalid
KIXOKEJAJAX       Invalid
MISUNDERSTANDING  Invalid

Might want to add a test case for a valid word which uses wild cards (eg. JAZZ = 19, not 29)

You know, this challenge would be so much more evil if it involved a language whose Scrabble tiles cannot be represented with a single character, like Spanish, Basque, Hungarian, Tuvan or Welsh.

Are answers specifically required to output "Invalid", or may we choose any behavior as long as it is clearly not a score? For example, -1?

@KamilDrakari It must say exactly Invalid.

Perl 5 228 205 186 184 178 177 153 150 149 142 137 135
Run with perl -E.
Golfed:

$_=<>;@a=@b=map-ord,'            0 0@0 H        ``'=~/./g;say s!.!($a[$q=64-ord$&]+=8)<8?$-+=1-29/$b[$q]:++$j!ge~~[2..15]&&$j<3?$-:Invalid

This solution uses some non-printable characters, so a hexdump is provided below:
00000000: 245f 3d3c 3e3b 4061 3d40 623d 6d61 702d  $_=<>;@a=@b=map-
00000010: 6f72 642c 2703 0904 0909 2030 2030 030e  ord,'..... 0 0..
00000020: 4030 0e20 0704 4809 1809 601d 0e0e 6027  @0. ..H...`...`'
00000030: 3d7e 2f2e 2f67 3b73 6179 2073 212e 2128  =~/./g;say s!.!(
00000040: 2461 5b24 713d 3634 2d6f 7264 2426 5d2b  $a[$q=64-ord$&]+
00000050: 3d38 293c 383f 242d 2b3d 312d 3239 2f24  =8)<8?$-+=1-29/$
00000060: 625b 2471 5d3a 2b2b 246a 2167 657e 7e5b  b[$q]:++$j!ge~~[
00000070: 322e 2e31 355d 2626 246a 3c33 3f24 2d3a  2..15]&&$j<3?$-:
00000080: 496e 7661 6c69 64                        Invalid

Alternatively, using Ctrl+Key:
$_=<>;@a=@b=map-ord,'^C^I^D^I^I 0 0^C^N@0^N ^G^DH^I^X^I`^]^N^N`'=~/./g;print s!.!($a[$q=64-ord$&]+=8)<8?$-+=1-29/$b[$q]:++$j!ge~~[2..15]&&$j<3?$-:Invalid

Ungolfed+commented:
# Read in input
$_=<>;
# @a and @b: represents approximately 8x the number of tiles (when rounded up). The
#   non-multiple-of-8 values distinguish tiles that are given equally, but are worth
#  different values
@b=@a=map-ord,"...."~=/./g;
# above is equivalent to
# @a=@b=(-03,-09,-04,-09,-09,-32,-48,-32,-48,-03,-14,-64,-48,-14,-32,-07,-04,-72,-09,-24,-09,-96,-29,-14,-14,-96);
say
    # for each character
    s!.!
        # $q: A->-1, B->-2, etc.
        # decrement number of $q tiles, add points if needed, otherwise
        #    increment j, which counts number of wilds used
        # truncate(1-29/b[q]): decimal values were chosen specifically
        #    for this to return the point value. b[q] is the number of tiles
        #    of the qth letter after a originally given.
        #  $- contains the score, is initially zero (if in a one line program,
        #   as the golfed version is), and is always an integer
        ($a[$q=64-ord$&]+=8)<8 ? $- += 1 - 29/$b[$q] : ++$j
    # s returns length, check if between 2 and 15
    !ge ~~ [2..15]
    # make sure less than 3 negative tiles (aka wilds)
    && $j < 3 ?
        # print score
        $-
    # or invalid
    : Invalid

you can squeeze at least 20 bytes out of those arrays with some creative manipulation

Gah, always one step ahead of me. :) Have an upvote.

This has been interesting, our scores have been so close all the way. +1.

Does this work with -M5.010 (penalty of 0 because it specifies a version of the language to use) rather than -e (penalty of 1)? You might be able to save a byte in the arguments.

C, Rev 2, 151 145 138
Inspired by the 159-byte code in @bebe's comment, I squeezed another 8 14 21 characters out:
4 bytes saved by rearranging the length counter i. This is initialised to 1 (assuming the program takes no arguments) then multiplied by 4 every time a letter is read. It overflows to zero when the word length is greater than 15, so to check if the word length is bad, we simply check if i<5 (I put i<9 so it will still give invalid for one-letter words if the user accidentally intialises i to 2 by putting a single argument on the command line.)
4 bytes saved by changing the loop condition test to a simple &31. This requires that the word is terminated with a space (ASCII 32) or a null character (ASCII 0.) Normally keyboard input is terminated by a newline (ASCII 10) so the program's a bit inconvenient to use, because you have to type the space then press return as well to get the computer to read the buffer. For newline-terminated strings, I could match but not beat the way bebe does it.
 6 13 bytes saved by changing the encoding to -(number of tiles of each letter)-(score for that letter-1)*13. This now requires a range from -4 for L,S,U to -118 for Q,Z. The reason for using negative numbers is to avoid the unprintable ASCII range 0 to 31. Instead the range used is the two's complement of the negative numbers 256-4=252 to 256-118=138. These are printable, extended ASCII characters. There are issues with copying and pasting these in Unicode (the way it simplifies back to ASCII depends on the code page installed which can lead to unpredictable results) so I have included the correct ASCII codes in the program comment.
The advantage of this encoding is the elimination of the variable r as the number of tiles is always reduced by 1 (as it is stored as a negative number, we do t[x]++. Additionally, the postfix operator means we can perform this increment at the same time as adding the score to s.
//char t[]={32,247,228,228,239,244,215,240,215,247,164,203,252,228,250,248,228,138,250,252,250,252,215,215,164,215,138,0};
b,s;
main(i,x){
  for(char t[]=" ÷ääïô×ð×÷¤ËüäúøäŠúüúü××¤×Š";x=getchar()&31;i*=4)
    t[x]%13?
      s-=t[x]++/13-1:
      b++;
  printf(i<9|b>2?"Invalid":"%d",s);
}

C,184 Rev 1 173 (or 172 with compiler option)
I'm using GCC, and with the compiler option -std=c99 it will allow me to move char t[]="...." into the initialization of the for loop for a saving of one additional semicolon. For readability, I have shown the program without this change, and with whitespace left in.
#define T t[x[1][i]-65]
i,b,s;
main(int r,char**x){
  char t[]="Z>>QxS=SZW6(>
m<(<(SSWSm";
  for(;x[1][i];i++)
    T/10?
      s+=r=T%10+1,T-=r*10:
      b++;
  printf(i<2|i>15|b>2?"Invalid":"%d",s);
}

The trick is in the datatable. For each letter an ASCII code of the form (total score of tiles for that letter)*10+(score of one tile-1) is stored in the table t[]. At runtime, these total scores are reduced as tiles are used up.
The total score of all the tiles for each letter ranges from 12 for E down to 4 for L,S,U. This form of encoding enables only printable ASCII characters to be used (ASCII 120,x for E down to ASCII 40,( for L,S,U.) Using the number of tiles would need a range from 120 down to 10, which is why I avoided it.
Thanks to a #define macro, a single symbol T is used in the main program to retrieve the letter index ifrom the first commandline argument, subtract ASCII A=65 from it to give an index ,and look it up in the table T: t[x[1][i]-65].
The for loop is used more like a while loop: the loop ends when a zero byte (string terminator) is encountered in the input string.
If the tiles of that letter are not exhausted (T/10 is nonzero) s is incremented by  the tile score T%10+1 to keep a total score. At the same time the tile score is stored in r, so that the value in the able represented by T can be decremented by r*10 to indicate that one tile has been used. If the tiles are exhausted, the wildcard/blank counter b is incremented.
The printf statement is fairly self-explanatory. if the wordlength is out of bounds or the blank count is too high, print Invalid otherwise print the score s.

Since it's now another day, you can save one character by replacing r+=(r==7)3 with r+=r-7?0:3.  Also you don't need the brackets round T-=r9,s+=r.

@Alchymist Thanks for the tip about the brackets, I always forget there's no issues with operator precedence between ? and :. Your other point is superseded, as I have completely changed the encoding so there's no need for any special handling of Q and Z. Now down to 173/172 with your help.

with getchar() it's 159: l,w,f;main(t,i){for(char b[]="Z>>QxS=SZW6(>
m<(<(SSWSm";(i=getchar()-65)>=0;l++)b[i]/10?f+=t=b[i]%10+1,b[i]-=t*10:w++;printf(l<2|l>15|w>2?"Invalid":"%d",f);} although I still don't get why char*foo=<string> crashes. it could save 2 chars.

@bebe char*foo="string" is a string literal, and its contents are not allowed to be modified. On the other hand, char foo[]="string" creates an array of chars initialized to string\0, which may then be modified.

@bebe cool, I missed the idea of using getchar(). I have used your improvements to the code (with my variable names for consistency with the rest of my answer), plus an improvement to the wordlength validity check, and a cheeky improvement to the loop condition test (I tried shortening yours but could not do so with the same functionality.) I also tried getche() and getch() but my compiler (gcc on cygwin) would not link them automatically.

JavaScript (ES6) - 241 230 199 182
f=s=>{for(i=t=_=0,E=12,A=I=9,B=C=M=P=28,D=17,F=H=V=W=Y=41,G=16,J=X=92,K=53,L=S=U=4,N=R=T=6,O=8,Q=Z=118;c=s[i++];)this[c]%13<1?_++:t+=1+this[c]--/13|0;alert(i<3|i>16|_>2?"Invalid":t)}

Edit - changed the way I encoded the quantities/scores to reduce size and remove non-ascii variables
Edit 2 - changed the quantity/score encodings to integers instead of strings
Edit 3 - switched to %13 (thanks @edc65), inverted the encoding, modified the values directly, and a few other minor improvements
Tested in Firefox console.

+1 very clever. Suggestions: 1.f[c]=1+f[c]||1 -> f[c]=-~f[c], 2.why not use % 13

192 f=s=>{for(E=12,A=I=9,B=C=M=P=28,D=17,F=H=V=W=Y=41,G=16,J=X=92,K=53,L=S=U=4,N=R=T=6,O=8,Q=Z=118,$=2,t=i=0;c=s[i++];)(f[c]=-~f[c])>(l=this[c])%13?--$:t+=l/13+1|0;alert(i<3|i>16|$<0?"Invalid":t)}

@edc65 - Thanks heaps. Hadn't seen that first trick, but didn't end up using it as I'm directly modifying the values now (mentally filing it away for future golf). %13 is a stroke of genius though. I got stuck thinking I had to store things in digits, but maths doesn't care about the difference between base10 and base13.

Nice! (Doesn't work in Chrome's console, BTW: SyntaxError: Unexpected token >.)

@DLosc - Yeah, I think Firefox is the only browser at the moment that supports all the ECMAScript 6 stuff (Chrome doesn't like the f=s=>{...} notation).

You mean... Firefox is more advanced than Chrome? =O

Python 3, 217 201
b=2;i=s=0;w=input()
while i<26:n=w.count(chr(i+65));q=int('9224c232911426821646422121'[i],16);b-=max(0,n-q);s+=min(n,q)*int('1332142418513113a11114484a'[i],16);i+=1
print(["Invalid",s][-b<1<len(w)<16])

Ungolfed:
b=2    # number of blanks available
i=s=0  # letter index 0..25, running score tally
w=input()

# Loop through each letter of the alphabet
while i<26:
    # Get number of occurrences in the word
    n=w.count(chr(i+65))
    # Get quantity of the letter from hex encoded string
    q=int('9224c232911426821646422121'[i],16)
    # Remove blanks for each occurrence over that letter's quantity
    b-=max(0,n-q)
    # Score the non-blank tiles, getting scores from hex-encoded string
    s+=min(n,q)*int('1332142418513113a11114484a'[i],16)
    # Increment
    i+=1

# If b > -1 and 1 < len(w) < 16, print the score; otherwise, print "Invalid"
print(["Invalid",s][-b<1<len(w)<16])

Edit: Thanks to @BeetDemGuise for a tip that ultimately led me to much more than a 1-character reduction!  Original code below:
q=[77-ord(x)for x in'DKKIAKJKDLLIKGEKLGIGIKKLKL'];b=2;s=0;w=input()
for c in set(w):n=w.count(c);o=ord(c)-65;b-=max(0,n-q[o]);s+=min(n,q[o])*(1+int('02210313074020029000033739'[o]))
print(["Invalid",s][-b<1<len(w)<16])

Its quite minimal but you can save 1byte by encoding your scores string in hex: int('1332142418513113a11114484a'[o],16)  :)

JavaScript - 232 201
t=[9,2,2,4,12,2,3,2,9,1,1,4,2,6,8,2,1,6,4,6,4,2,2,1,2,1];w=r=0;for(i=y=z.length;i--;){x=z.charCodeAt(i)-65;if(!t[x])w++;else{t[x]--;r+=-~"02210313074020029000033739"[x]}}alert(w>2|y<2|y>15?"Invalid":r)

z stores word. Outputs as alert.
Edit: improved as per recommendations below.

s is only used once, so you don't need to make it a variable at all; you can remove that declaration and replace r+=s[x] with r+=-~"02210313074020029000033739"[x]. Also, you don't need parentheses around (w>2|y<2|y>15) in the alert.

BEFUNGE 93 - 210 bytes.
But it doesn't check the 15 letter limit.
v1332142418513113:11114484: >01g:"0"-!#v_1-01p1+\v
 9224<232911426821646422121v  "Invalid"<      vp0<
<vp00p10"20"p200p900
>>~:55+-!#v_"@"-::1g:"0"-! #^_1-\1p0g+"0"-02g+>02p
_v#:-1<    #p90+g90-"0"g1:<
     @.g20<        @,,,,,,,<

C, 197
Assumes the string is provided as a command line argument, e.g. ./scrabble STACKEXCHANGE
s;n;m=31;main(int c,char**v){char d[]="BIBBDLBCBIAADBFHBAFDFDBBABA@ACCBADBDAHEACAACJAAAADDHDJ";for(;c=*v[1]++&m;d[c]--,s+=d[c+27]&m)n+=1+m*(!(d[c]&m||d[c=0]&m));printf(n>1&&n<16?"%d":"Invalid",s);}

Haskell - 538
Save it as scrabble.hs and then compile it using
ghc --make scrabble && ./scrabble

Then enter your word as input and press enter
l=['A'..'Z']
sc=zip l [1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10]
vfs a y =snd $ filter (\x -> fst x == y) a !! 0
q = zip l [9,2,2,4,12,2,3,2,9,1,1,4,2,6,8,2,1,6,4,6,4,2,2,1,2,1]
i s =filter (\x -> (fst x) >=0) [(length [x | x <- s, x == a] - vfs q a,a) | a <- l]
main = do
 s <- getLine
 if length s <= 15 && length s > 2 && sum (map fst (i s)) <= 2 then
  putStrLn $ show (sum [vfs sc x| x <- s] - sum [(vfs sc (snd x)) * (fst x) | x <- (filter (\x -> fst x > 0) (i s))])
 else do
  putStrLn "Invalid"

You can remove a lot of spaces and in Haskell `['A', 'B', 'C'] == "ABC". Also you can use only one space for each level of indent. And you can use shorter names. There is a lot for golfing.

@Ray Have done that, I am new to Haskell, is there a way to represent lists of Ints more concisely than [1,2,3]?

"ABCDEFG" can be written as ['A'..'G'], [1,2,3] can be written as [1..3]

How do you obtain your byte count?  wc gives me over 500 characters for your code.

@TheSpanishInquisition Just got a update for my st3 word count extension, the author had swapped the two counts accidentally, edited to 538

Python 2.7 - 263
I couldn't come anywhere close to DLosc's answer, but this treats each letter as a 'bag' that you pull from, until its empty, then you pull blanks, and when that is empty it errors.
S=input().lower()
X={chr(97+i):[int(y)+1]*(77-ord(x))for i,(x,y)in enumerate(zip('DKKIAKJKDLLIKGEKLGIGIKKLKL','02210313074020029000033739'))}
B=[0,0]
try:
 if len(S)>15:1/0
 print sum(map(lambda x:X[x].pop()if len(X[x])>0 else B.pop(),S))
except:
 print "invalid"

This is a neat approach! You need raw_input if it's Python2 (one thing I like about Python3). The input is guaranteed uppercase, so remove .lower() and change 97+i to 65+i. Input less than 2 characters also needs to be invalid. You can raise the zero-division error without an if statement: divide your total score by (1<len(S)<16). A couple other tweaks like putting the prints on the same line as the block headers and deleting the space before "Invalid" brings it down to 250 by my count. :)

Haskell, 290 283
As far down as I could make it for now:
import Data.List
t="CdC8d::Od;D;d41N:dd:6dNdN;;4;6"
s w@(_:_:_)=let d=concat(zipWith(replicate.(`div`11).f 33)t("AEIO"++['A'..]))\\w;y=drop 15w in if length(d++w++y++y++y)>100 then s""else show$187-(sum$map((`mod`11).f 0.(t!!).f 61)d)
s _="Invalid"
f n=(-n+).fromEnum
main=interact s

This code abides by the rules very strictly, so make sure you don't pass it any extra characters (such as end-of-line).  Use like this: echo -n "JAZZ" | runghc scrabble.hs.
Explanation
The pattern (_:_:_) makes sure that only strings of at least two characters are considered, everything else results in "Invalid" (fallback pattern _).  The table of tiles is encoded as 11*nTiles+value converted to ASCII with an offset that allows the lookup modulo 11 to work, where the letters AEIO are duplicated because they occur more than 6 times each.  The pool of tiles is then created using replicate, from which the characters in the word are removed as they occur (list difference, \\).  The pool contains 98 tiles, so if the total length of the word and the remaining part of the pool is larger then 100, then we have used too many wildcards.  Also, the word minus the first 15 letters is added three times to the length computation so any word longer than 15 letters automatically appears to use up three wildcards and therefore is invalid.  Scoring is done on the remaining pool, which initially had 187 points, which we simply subtract from.  Note the f 61 rather than f 65, 65 being the ASCII number of 'A', because of the duplicate "AEIO" at the beginning of the pool.  The rest is just boilerplate.

Python3 - 197
s,i,c,r=input(),0x1a24182424416141611a2381612341151891243224c142232391,[],[]; p=len(s)
for w in s:e=8*ord(w)-520;c+=[s.count(w)<=i>>e+4&15];r+=[i>>e&15]
print(['Invalid',sum(r)][all([p>2,p<15]+c)])

Let's put the bignums to use :D
(It doesn't handle wildcards currently, I've skipped reading that rule entirely, damn)

Ruby - 195
b=2
i=s=0
w=$*[0]
(?A..?Z).map{|l|n=w.count(l);q='9224c232911426821646422121'[i].to_i(16);b-=[0,n-q].max;s+=[n,q].min*'1332142418513113a11114484a'[i].to_i(16);i+=1}
p(-b<1&&w.size<16?s:'Invalid')

I'm assuming the output of "Invalid" is fine, if not I would need to do $><<(-b<1&&w.size<16?s:'Invalid') which would bump it up to 198

Clojure - 325
I haven't done clojure in a while so I'm sure there are several ways to improve my solution .ie the qty and pts lists
(let[w(first *command-line-args*)o(map #(count(filter #{%}(seq w)))(map char(range 65 91)))i(apply +(filter neg?(map #(- % %2)'(9 2 2 4 12 2 3 2 9 1 1 4 2 6 8 2 1 6 4 6 4 2 2 1 2 1) o)))](println(if(or(> -2 i)(not(<= 2(count w)15)))"Invalid"(apply +(map #(* % %2)o'(1 3 3 2 1 4 2 4 1 8 5 1 3 1 1 3 10 1 1 1 1 4 4 8 4 10))))))

Some what Un-golfed
(let [word    (first *command-line-args*)
      letters (map char(range 65 91))
      occ     (map #(count (filter #{%} (seq word))) letters)
      invalid (apply + (filter neg? (map #(- % %2)
                '(9 2 2 4 12 2 3 2 9 1 1 4 2 6 8 2 1 6 4 6 4 2 2 1 2 1)
                occ)))
      score   (apply + (map #(* % %2) occ '(1 3 3 2 1 4 2 4 1 8 5 1 3 1 1 3 10 1 1 1 1 4 4 8 4 10)))]
    (println
      (if (or (> -2 invalid)
              (not (<= 2 (count word) 15)))
        "Invalid"
        score)))

ES6: 184 (non-strict)
w is assumed to already contain the word. r is the output string.
i=0,o=[..."291232342c124322491181541236181231a61416141242418241a"].map(c=>parseInt(c,16)),r=!w[16]&&w[2]&&[...w].every(c=>o[c=c.charCodeAt()*2-129]-->0?i+=o[c+1]:o[0]--)?i+"":"Invalid"

Here's it explained and a little less golfed:
// The sum.
i = 0,

// The data for the letters. It's encoded similar to the Ruby version, with
// the first being the wildcard holder. The rest hold in hex form the
// following: first = quantity left, second = value.
// The .map(c => parseInt(c, 16) simply parses all the hex characters.
o = [..."291232342c124322491181541236181231a61416141242418241a"]
  .map(c => parseInt(c, 16)),

// The result, `r`.
r = !w[16] || // If there is a 16th character in the word or no 2nd character,
    w[2] &&   // then the next section isn't evaluated. It immediately equates
              // to true, thus returning "Invalid".
   [...w] // Convert the string into an array of characters (ES6 equivalent to
          // `.split('')`
    .every(c => // This loop terminates when the callback returns a falsy
                // value.
      // Gets the ASCII value, subtracts 65, doubles it (the lookup table is
      // in pairs within one array), and decrements the counter at that entry.
      // The lookup table also doubles as a data holder.
      o[c = c.charCodeAt() * 2 - 129]--
        > 0 ?  // Test if there is something to take away. This must return
               // false at 0 and -1 so wildcards can be taken.
        i += o[c+1] : // If there was something to take away, then add the
                      // letter value to the sum.
        o[0]--) // Otherwise, take a wildcard. If this is already at 0, then
                // it returns falsy.
      ? "Invalid" : i + "" // This is where the text is returned.

Dart - 201
main(a,{x:0xa14281424214161416a132181632145181194223421c24323219,i,r:0,m,s:2}){if((m=a[0].length)>1&&m<16)for(i in a[s=0].codeUnits)x>>(m=i*8-520)&15>0?r+=(x-=1<<m)>>m+4&15:++s;print(s<2?r:"Invalid");}

This requires bignums, so it won't compile to JavaScript.
With more whitespace:
main(a,{x:0xa14281424214161416a132181632145181194223421c24323219,i,r:0,m,s:3}){
  if((m=a[0].length)>1&&m<16)
    for(i in a[s=0].codeUnits)
      x>>(m=i*8-520)&15>0
      ? r+=(x-=1<<m)>>m+4&15
      : ++s;
  print(s<3?r:"Invalid");
}

PHP, 180 170 168 bytes
for($q=str_split(KDKKIAKJKDLLIKGEKLGIGIKKLKL);$o=31&ord($argv[1][$i++]);)$s+=$q[$o]++>L?$q[0]++>L?$f=1:0:X02210313074020029000033739[$o]+1;echo$f|$i<3|$i>16?Invalid:$s;

Yay! beating JS!
breakdown
for(
    $q=str_split(KDKKIAKJKDLLIKGEKLGIGIKKLKL);  // init quantities: L=1,A=12
    $o=31&ord($argv[1][$i++]);                  // loop through characters: map to [1..26]
)
    $s+=                                          // increase score by ...
        $q[$o]++>L?                                 // old quantity below 1?
        $q[0]++>L?$f=1                              // no more wildcards? set error flag
        :0                                          // wildcard: 0 points
        :X02210313074020029000033739[$o]+1;         // else: letter score
echo$f|$i<3|$i>16?Invalid:$s;                   // output

I´m so glad there is no letter score larger than 10.


text:
Push Button Probabilities
The Challenge
The challenge is that I have a standard mechanical push button lock and you need to find out every possible code that could unlock it.
With a standard mechanical push button lock you have all single digit numerals and sometimes a few letters.
With this specific push button lock there are specific rules.
Rules

The buttons available to press are as follows :
1, 2, 3, 4, 5, 6, 7, 8, 9, 0, X, Y, Z
Only 4 button presses are allowed (Length of the push button code has to be 4 characters long)
No button can be pressed twice (Therefore no doubles such as 1232 as you can't press 2 twice and the same goes for the letters)
The order of the buttons is irrelevant and they can be pressed in any order. (This means the code 1560 is the same as 5610 and are both the same combination in the case of this specific lock and so only one should be recorded as a possible entry)

You have completed the challenge when your code compiles and does the following on seperate lines.

It follows the rules.
Print every entry that is not repeated.
Print the probability of pressing 4 buttons within the rules and the chance of picking a correct combination.

This is Code-Golf so the shortest answer wins.

This seems a bit dull, consider making the challenge more general. You could also post it in teh sandbox first for some feedback.

Ah. I was looking for something like a rules or regulations for codegolf and I couldn't see one. Now I realise that it was in front of me the whole time. I'll give that a try first.

I just tried to add it to the Sandbox however I don't have 5 reputation in Codegolf so I am unable to do so.

It is admittedly a bit of a catch 22, try and answer an easy question to get some rep, on PPCG it's considered harder to ask a good question than to answer a question.

So you just want us to iterate/print all 13 choose 4 combinations? At that point, the probability for a single guess is 1/C(13,4), or 1/715.

@crystalwolf upvoted your question. Now you have > 5 reputation


text:
Create shortest log organizer
Create the shortest script that organizes all the logs by month and date.
Rules
Syntax
organize <folder to scan> <folder to place logs>

folder cannot be root
the two folder should be different and not contain one another

Behaviour
The script should scan all the *.log files in <folder to scan> and copy them to <folder to place logs> in sub-folders corresponding to the year and month of the last modified  time of the log file, named like year_month.
Example:
organize /var/log/apache2 /temp/logs

would give folder structure like this:
/temp/logs/
|-- 2014_01
|-- 2014_02
|-- 2014_03
|-- 2014_04
|-- 2014_05

Languages, environment
All languages and OSs are permitted but need to be specified.
But since this is a code-golf question, script languages (python, bash, windows batch) will be more fit from the start.

Are we sorting them based on create date, modified date, filename, etc? If name, how is the name formatted?

@Geobits A edited to make it more clear, "sub-folders corresponding to the year and month of the last modified time of the log file"

Is target folder exists or it should be created first?

Bash - 79 bytes
stat -c" $2/-%n-%y" $1/*.log|awk -F- '{d=$1$3"_"$4;system("mkdir"d";cp "$2d)}'

Batch - 104 bytes
@cmd/von/c"for /r %1 %%a in (*.log)do @set a=%%~ta&set a=!a:~6,4!_!a:~3,2!&mkdir %2\!a!&copy %%a %2\!a!"

What if there are more than one log file per month?

@Kondybas that would be fine.

@Kondybas Do you mean more than one log file with the same name per month?

Eeeh, oops! You're right :)

Bourne Shell / FreeBSD 9.2+ - 92(83) bytes
#!/bin/sh
ls -lD"%Y_%m" $1/*.log|cut -wf6-|while read A B;do mkdir $2/$A;cp $1/$B $2/$A;done

Cobra - 223
OS: Any with Mono/.NET
Because this is the perfect task for an obscure compiled language! < /sarcasm>
class P
    def main
        a,b=CobraCore.commandLineArgs[1:]
        for f in Directory.getFiles(a,'*.log')
            m=b+File.getLastWriteTime(f).toString('yyy_MM')
            Directory.createDirectory(m)
            File.copy(f,m+f[f.lastIndexOf('/'):],true)

Powershell (124 bytes)
Get-ChildItem $($s+"\*.log")|%{$n=$d+"\"+$_.LastWriteTime.ToString("yyyy_MM");if(!(Test-Path $n)){md $n}mi $($s+$_.Name) $n}

Has the added bonus of scanning for only .log files in the given folder if there are multiple file types. If not, then I can knock this down to 112. $s is the full source folder path, and $d is the destination folder path.