text:
How to shorten this J code? (Or write shorter code in another language)
I decided to learn J so that I could better take part in code golfing. Starting it off relatively simple, I tried writing a solution to this problem:

Find the sum of all the multiples of 3 or 5 below 1000.

After a bit of tinkering, I came up with the following J code that solves it:
x=:i.1000
+/x#(0=3|x)+.0=5|x

Basically, what I'm doing is taking two lists of numbers from 1 to 1000, and finding one modulo 3, and the other modulo 5. Then I OR them together to get a list of indicies where a number is divisible by either 3 or 5. I then use that to sum the numbers.
What I ask is, how do I shorten this? I'm new to J and so do not have enough experience to shorten it any further.
Also, if anyone has a solution shorter than this in another language, I'd be interested to see that as well!

Project Euler problem 1

6 bytes: 233168

Employing a few forks, a hook and the fact that J works well on lists:
+/(#~[:+./0=3 5|/])i.1000

This answer uses your algorithm, but just uses some J tricks to make it a bit shorter. I'm fairly sure that this can be made shorter still, and I wouldn't be surprised if there's a slightly different way of doing it that results in an even shorter solution.
Here's a list of some things I've done here.
First, I've combined the 3|x and the 5|x into one operation 3 5|/x. This uses the table adverb / to do both operations at once:
   3 5|/i.20
0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4

Next, I've combined the |/, the 0=, the +., and the # into a train of verbs using forks and a hook. The verb train breaks down into groups of three:
3 5|/]

this is the same as the above, except I'm using ] to grab the list to the right of the brackets.
0=x

x is the result of the previous fork which is fed into the next.
[:+./x

as before the result so far gets fed into this fork. [: tells the verb +./ that it should use its monadic (one argument) form. The / inserts the +. between the top and bottom rows of the result so far.
#~x

This is the hook. The result so far is fed in as the right argument, but the left argument is the value outside the brackets (i.1000) again. So this is equivalent to (i.1000)#~x. The ~ just reverses the order of the arguments.
Then at the end I just use the +/ as you did.

Is there anyway you could add a small explanation to what/how you're doing it?

Yep, just working on that now. :-)

+/(#~0=[:*/3 5|/])i.1e3 is two chars shorter. Basically changing OR with multiplication and shortening the number 1000.

Using a slightly different method than my other answer:
+/+/((]*[>])3 5*/i.)1000

Here, I'm multiplying 3 and 5 by all the numbers up to 1000, throwing away anything that's not less than 1000 and then summing them. It's a shame about the ugly +/+/ at the end.
Here we have a fork:
3 5*/i.

followed by a hook:
(]*[>])x

EDIT:
As randomra points out, I forgot about duplicates. This should fix that:
+/~.,((]*>)3 5*/i.)1000

I've also realised that [>] is the same as > (not the first time I've had that redundancy in my answer)

You double count numbers divisible by 15.

Ooh, never considered that.

your first "+/" just removes shape - can use monadic ; instead
double count can be fixed with "nub" ~.
your approach is good and leads to 22 bytes +/~.;((]*>)3 5*/i.)1e3

@jayprich my shortest version is 23 bytes at the end of the answer. It's pretty much what you've got without the 1e3 for the 1000.

a couple of swerves on the above to shave some bytes off
correct result 233168

25 bytes +/x#(0=3|x)+.0=5|x=:i.1e3
24 bytes +/(#~[:+./0=3 5|/])i.1e3
22 bytes +/~.;((]*>)3 5*/i.)1e3

J, testing HCF 21 bytes
+/(*1&<@(15&+.))i.1e3

TIO


text:
Evaluate the binomial theorem!
Your mission, even if you don't accept it, is to input three numbers from STDIN or file:

5 0.5 6

What you must do is evaluate this:

(5a + 0.5b)^6

This basically means that the first two numbers are the coefficients of a and b and the third is the exponent in a binomial expansion.
Rules:

The first two numbers are either integers or simple terminating fractions.
The third number is a positive integer.
Do not use any inbuilt binomial functions from libs. (thanks to comments)
The shortest code wins!

Go on, do it.

The interesting part of this has already been done as Generate Pascal's triangle

What's the objective winning criteria?

@PeterTaylor: not necessarily, for example the APL-like languages have binomials built in (as ! at least in APL and J). Indeed, the winner of that question used J's !. It would certainly have been longer if he had to hand-code it, and assuming that this question does not allow their use.

@GigaWatt: I'm assuming shortest code wins, since it's tagged as code-golf.

C (C99), 223 chars
#include <stdio.h>
#include <math.h>
int f(int n,int k){
    return k==0?1:(n*f(n-1,k-1))/k;
}
int main(void){
    float a,b;int n;
    scanf("%f%f%d",&a,&b,&n);
    for(int k=0;k<=n;k++)
        printf("%d*(%fa)^%d*(%fb)^%d+",f(n,k),a,n-k,b,k);
    puts("0");
}

Input:
1 1 2

Output:
1*(1.000000a)^2*(1.000000b)^0+2*(1.000000a)^1*(1.000000b)^1+1*(1.000000a)^0*(1.000000b)^2+0

Do you have check if k==0? I think a simple k would do the same.

My brief attempt at optimization: http://ideone.com/tUlfKs

@GigaWatt: Well, it wouldn't be C99 then.

Mathematica 36
InputForm@Expand[(#1 a + #2 b )^#3] &

Usage
InputForm@Expand[(#1 a + #2 b )^#3] &[5, .5, 6]

Result:
15625*a^6 +9375.*a^5*b +2343.75*a^4*b^2 +312.5*a^3*b^3 +23.4375*a^2*b^4 + 0.9375*a*b^5 + 0.015625*b^6

F# 153 chars 156 bytes
let a,b,n=1.,2.,3
let rec C k=if k=0 then 1 else (n-k+1)*C(k-1)/k
List.iter(fun i->printf"%+ga^%ib^%i"(pown a (n-i)*pown b i*float(C i)) (n-i) i)[0..n]

Python 2, 144 bytes
a,b,n=input();f=lambda n:-~(n and~-n*f(~-n))
for k in range(-~n):print"+ "[0**k]+"%d*(%d*a^%d)*(%d*b^%d)"%(f(n)/f(k)/f(n-k),a**(n-k),n-k,b**k,k)

Try it online!

source: Stack Exchange

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

sort: votes


text:
Generate Pascal's Pyramid
Pascal's Pyramid is an extension of Pascal's Triangle to the third dimension. Starting with a 1 as the apex, the elements of each successive layer can be determined by summing the three numbers that are above it. The nth layer contains the coefficients of (a + b + c)^(n-1).
You are to create a program that, given an input n, outputs the first n layers of Pascal's Pyramid. There must be two newlines between the different layers, and they must be in order. Within each layer, each row must be on a separate line, with the elements separated by spaces. Apart from that, you may format the pyramid however you like.
Your code should be reasonably fast generating a pyramid with 10 layers.
For example, your program, when given 4 as input, should output something like this:
1

1
1 1

1
2 2
1 2 1

1
3 3
3 6 3
1 3 3 1

May the shortest code win!

possible duplicate as it is a sub-problem of Pascal's Pyramid and Higher Dimensions

@Howard that question gets you to generate only a single layer of the pyramid, while this gets you to generate the whole pyramid.

1 is 0th layer.  For an input of 4 do you mean to go up to the coefficients of (a + b + c)^3 or (a + b + c)^4?

@ejrb the program should generate the first n layers - changed the formula to (a + b + c)^(n-1) to reflect that.

Python, 110
l=1
exec"print;n=1;r=0;exec\"c=0;exec'print n,;n*=r-c;c+=1;n/=c;'*r;print n;r+=1;n=n*l/r-n;\"*l;l+=1;"*input()

Original, ungolfed solution:
for layer in range(1, input() + 1):
    print
    n = 1
    for row in range(1, layer + 1):
        for col in range(1, row):
            print n,
            n *= row - col
            n /= col
        print n
        n *= layer - row
        n /= row

k 31
q)k)f:{,/{x**|x}{x{0+':x,0}\1}@'!x}
q)f 4
1
1
1 1
1
2 2
1 2 1
1
3 3
3 6 3
1 3 3 1

Python (134 128)
Factorials are probably more space-efficient, but I wanted to be fancy.
for n in range(1,input()+1):
 a=r=1.
 while a:
  b=a;j=1.;a*=(n-r)/r
  while b:print int(b),;b*=(r-j)/j;j+=1
  print;r+=1
 print

Uses the ratio property of Pascal's Triangle.
e.x. 1 4 6 4 1, 1:4, 4:6, 6:4, 4:1 = 1:4, 2:3, 3:2, 4:1
for n in range(1,input()+1): #Generate layers
 a=r=1.               #a is the first value of a row in a layer; r represents the row
 while a:          #when a is 0, there are no more rows in the pyramid.
  b=a;i=1.;a*=(n-r)/r #b will calculate the values of that row
                      #use ratio property to determine next value of a
                      #i is a counter representing the ith item in row r
  while b:print int(b),;b*=(r-i)/i;i+=1 #Output values using ratio property
  print;r+=1          #increment row; loop
 print

while a has the same functionality as while a!=0 assuming a is always an integer.  same for b

Mathematica (112)
For[j = 0, j < 11, j++, For[i = 0, i <= j, i++, Print[Row[Array[Binomial[i, # - 1] &, i + 1], " "]]]; Print[""]]

Older method(166):
b = "stdout"; For[k = 0, k < 11, k++, For[i = 0, i <= k, i++, For[j = 0, j <= i, j++, WriteString[b, Binomial[i, j], " "]]; WriteString[b, "\n"]]; WriteString[b, "\n"]]

The following prints it in a different format, but is only 94 characters:
For[i = 0, i < 11, i++, Print[Column[Table[Binomial[n, k], {n, 0, i}, {k, 0, n}]]]; Print[""]]

 Mathematica 65 64
c=Column;c[c@Table[n~Binomial~k,{n,0,p},{k,0,n}]~Table~{p,0,#}]&

Usage
c=Column;c[c@Table[n~Binomial~k,{n,0,p},{k,0,n}]~Table~{p,0,#}]&@5

The top layer should be {1}, not {{1},{1,1}}. Use {p, 0, #}

@DavidCarraher Yep, I haven't noticed it. Thanks

q)k)f:{,/{p**|p:x{0+':x,0}\1}'!x}

q)f 4

1
1
1 1
1
2 2
1 2 1
1
3 3
3 6 3
1 3 3 1

Code and Preformatted Text

is preferable to use 4 space indentation. That also makes the font monospace and highlights the syntax when possible. Just like in the strangely similar answer by rrr.

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


text:
Evaluate the primorial of a number
The primorial of a number is the product of all the primes until that number, itself included.
Take a number from STDIN as the input and evaluate its primorial, also known as the prime factorial.
Don't use libraries. Shortest code wins.
Test cases:
1 1
2 2
3 6
4 6
5 30
6 30
7 210
8 210
9 210
10 210
11 2310
12 2310
13 30030
14 30030
15 30030
16 30030
17 510510
18 510510
19 9699690

Essentially the same task as Sum of primes between given range, just with multiplication instead of addition and the starting value of the range is fixed.

As demonstrated below: multiplication is very different from summation, especially for primes.

J, 13 characters
*/p:i._1 p:1+

Examples:
   */p:i._1 p:1+7
210

   */p:i._1 p:1+12
2310

Damn. Just beat me.

Did I just see an instance of telepathy?!

@SohamChowdhury, no, you saw an instance of a trivial answer to a trivial question.

Boohoo you just trolled me.

Does J have a built-in way of calculating primes?

@arshajii See, e.g. here.

Python 2, 49 bytes
P=k=1
exec"P*=P**k%k<1or k;k+=1;"*input()
print P

Counts up k from 1 to the input, updating the primorial P by multiplying P by k whenever it's prime. Since P contains all lower prime factors, a sufficiently high power of P will contain k as a factor if and only if k is non-prime. The power P**k suffices, and we check whether P**k%k<1, multipling P by 1 if so (doing nothing) and by k otherwise.

PARI/GP, 22 bytes
prodeuler(x=1,input,x)

Mathematica 21
The large Pi represents the product function.
PrimePi@n returns the number of primes up to and including n.
Prime@i returns the ith prime.

C'mon... the product function is one char?! That's an ingenious workaround!

Thanks. It's somewhat like the case of "a+b", which is shorthand for Plus[a,b] or "a.b.c", which stands for the dot product, Dot[a,b,c].

Python, 72 characters
Quickly golfed, I imagine there are better python solutions.
n=t=1;exec"t*=(1,n)[all(n%i for i in range(2,n))];n+=1;"*input();print t

I used wikipedia to verify up to 71
Usage:
$ python primorial.py
100
2305567963945518424753102147331756070

$ python primorial.py
101
232862364358497360900063316880507363070

Whoops, just updated it so it actually works!

Mathematica, 27 chars
Times@@Prime@Range@PrimePi@

Usage
Times@@Prime@Range@PrimePi@100
(*
2305567963945518424753102147331756070
*)

I counted only 27 chars.

@DavidCarraher You're right. Thanks

Is that @ symbol at the end meant to be there? On it's own that'd be invalid syntax. You could probably just omit it.

C, 125 bytes
p(n,x){return x==1?n:n%x?p(n,x-1):1;}
f(n){return n==1?1:p(n,n-1)*f(n-1);}
main(){int n;scanf("%d",&n);printf("%d\n",f(n));}

Haskell, 90 chars
main=getLine>>= \v->print.product.takeWhile(<=read v)$[n|n<-[2..],all((>0).rem n)[2..n-1]]

or (also 90 chars):
main=getLine>>=print.product.flip takeWhile [n|n<-[2..],all((>0).rem n)[2..n-1]].(>=).read

Compilation
ghc primorial.hs

Usage
$ echo "12" | ./primorial
2310

or
$ ./primorial
12<ENTER>
2310

Some room for improvement here. takeWhile is unnecessary, we can just add an upper limit for the [2..] instead. Instead of getLine + read, we can use readLn. Also, do-notation is slightly shorter than using >>=. Result: main=do v<-readLn;print$product[n|n<-[2..v],all((>0).rem n)[2..n-1]] (68 characters)

R - 48
x=1:scan();prod(x[rowSums(outer(x,x,`%%`)<1)<3])

MATLAB/Octave, 23 bytes
prod(primes(input('')))

Try it online!

Casio-Basic, 41 bytes
prod(seq(piecewise(isPrime(x),x,1),x,1,n

Since the calculator doesn't have a "select" function of any kind, a piecewise/hybrid function is used to return the number if it's prime, otherwise return 1. seq does this over a range of integers from 1 to n, and prod multiplies the whole list together.
40 bytes for the function, +1 byte to enter n in the parameters box.

Smalltalk, Squeak 4.x flavour
Let's say we read n from stdin in 38 chars (this kind of requirement is just killing!)
n:=FileStream stdin nextLine asNumber.

If only product were defined in Collection in base image, this could be as simple as
^(0class primesUpTo:n+1)product

or:
^((2to:n)select:#isPrime)product

Unfortunately, we have to code #product by ourself in 48 chars (86 total).
(0class primesUpTo:n+1)inject:1into:[:p :i|p*i]

Or if primesUpTo: is considered as a library, we can use isPrime in 62 chars (100 total)
^(1to:n)inject:1into:[:p :i|i isPrime ifTrue:[p*i]ifFalse:[p]]

If even isPrime is forbidden we can find by ourselves in 67 chars (105 total)
p:=1. 2to:n do:[:i|((2to:i-1)anySatisfy:[:d|i\\d=0])or:[p:=p*i]].^p

Or for the fun, we can use a sieve in 108 chars (146 total)
s:=(p:=y:=1)<<n-2. 2to:n do:[:x|y:=(z:=y)*2+1.(z+1bitAnd:s)=0or:[p:=p*x.s:=z<<(n//x*x+x)//y+z+1bitAnd:s]].^p

Explanation of the sieve at http://smallissimo.blogspot.fr/2011/07/revisiting-sieve-of-erathostenes.html
Nota: bitAnd: has a short-cut operator & in Pharo 2.0, which would reduce Sieve cost to 94 chars (132 total)
s:=(p:=y:=1)<<n-2. 2to:n do:[:x|y:=(z:=y)*2+1.z+1&s=0or:[p:=p*x.s:=z<<(n//x*x+x)//y+z+1&s]].^p

Haskell, 76 bytes
main=interact$ \n->show$product[x|x<-[2..read n],and[x`mod`y>0|y<-[2..x-1]]]

Example:
$ echo 12 | ./primorial
2310

Java 7, 213 bytes
class M{public static void main(String[]a){c(new Long(a[0]));}static void c(long n){long r=1,i=0;for(;++i<=n;r*=p(i)?i:1);System.out.print(r);}static boolean p(long n){int i=2;while(i<n)n=n%i++<1?0:n;return n>1;}}

Ungolfed:
class M{
  static void c(long n){
    long r = 1,
         i = 0;
    for (; ++i <= n; r *= p(i) ? i : 1);
    System.out.print(r);
  }

  public static void main(String[] a){
    c(new Long(a[0]));
  }

  static boolean p(long n){
    int i = 2;
    while(i < n){
      n = n % i++ < 1 ? 0 : n;
    }
    return n > 1;
  }
}

Usage: java -jar M.jar 17
Output: 510510

Anything after Java SE 7 Update 21 is disallowed for being released after the challenge was created. Make sure what you use is from that update or before. https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7

Jelly, 3 bytes
ÆRP

Try it online!

RProgN 2, 6 bytes
S²P¬-*

Explained
S²P¬-*
S       # Produce as stack from 1 to the input.
 ²  -   # Filter it by the function provided
  P¬    # Is it not a prime?
     *  # Get the product of the now list of primes.

Try it online!

Japt, 6 bytes
õ fj ×

Try it here

05AB1E, 3 bytes
ÅPP

Try it online!


text:
Convert to and from the factorial number system
The Factorial Number System, also called factoradic, is a mixed radix numeral system. The factorials determine the place value of a number.
In this system, the right most digit can be either 0 or 1, the second rightmost digit can be 0, 1 or 2, and so on. This means that an n digit factoradic number can have a maximum value of (n + 1)!.
For example, to convert the factoradic number 24201 to decimal you would do this:
2 * 5! = 240
4 * 4! = 96
2 * 3! = 12
0 * 2! = 0
1 * 1! = 1
240 + 96 + 12 + 0 + 1 = 349

Hence the factoradic number 24201 is 349 base 10.
To convert a decimal number (with 349 as an example) into a factoradic number, you would do this:
Take the largest factorial less than the number. In this case it is 120, or 5!.
349 / 5! = 2 r 109
109 / 4! = 4 r 13
13 / 3! = 2 r 1
1 / 2! = 0 r 1
1 / 1! = 1 r 0

Hence 349 base 10 is the factoradic number 24201.
Your challenge is to create the shortest program or function that converts an input number to the other base.
The input will be a string representation of a non-negative integer. A factoradic number will be preceded by a ! (eg. !24201), while a decimal number will not be preceded by anything. You may assume that the maximum input will be 10! - 1 - 3628799 in decimal and 987654321 in factoradic. This means that letters will not appear in a factoradic input/output.
The program doesn't need to prepend a ! to a factoradic output, and may output a string or an integer. The input may be in any reasonable format.

Test cases:
Input: 1234
Output: 141120

Input: 746
Output: 101010

Input: !54321
Output: 719

Input: !30311
Output: 381

Mentioned in this XKCD comic yesterday :)

APL, 39 37 characters
{A B←(9⍴10)(⌽1+⍳9)⌽⍨'!'∊⍵⋄A⊥B⊤⍎⍵~'!'}

Examples:
      {A B←(9⍴10)(⌽1+⍳9)⌽⍨'!'∊⍵⋄A⊥B⊤⍎⍵~'!'}'1234'
141120
      {A B←(9⍴10)(⌽1+⍳9)⌽⍨'!'∊⍵⋄A⊥B⊤⍎⍵~'!'}'!54321'
719

I think you can replace ⍴⍵∩'!' with '!'∊⍵ to save a character.

@Volatility Yes you can. I also found another one.

IMO having the word "pwn" in your script is well worth the extra character.

I agree with ejrb. Would you break this down please?

Replace ~'!' with ∩⎕D to save a character.

Python 2.7 (163 157 152)
i=raw_input()
exec("b='';a=362880;j=int(i);x=9;"+'b+=`j//a`;j%=a;a/=x;x-=1;'*9,"a=x=1;b=0;"+'b+=a*int(i[-x]);x+=1;a*=x;'*~-len(i))['!'in i]
print int(b)

More readable version:
i=raw_input()
if'!'in i:a=x=1;b=0;c='b+=a*int(i[-x]);x+=1;a*=x;'*~-len(i)
else:b='';a=362880;j=int(i);x=9;c='b+=`j//a`;j%=a;a/=x;x-=1;'*9
exec c;print int(b)

Breakdown:
Factoradic -> Decimal, when i is in the form !(number)
a=1   #Factorial value (multiplied every iteration)
x=1   #Index value
b=0   #Output
iterate ~-len(i) times:    #PSEUDOCODE! bitwisenot(a) = ~a = -a-1
    b+=a*int(i[-x])        #add the value of the xth last character in the factoradic #
    x+=1                   #Increment x
    a*=x                   #Set a to x!, (x-1)! * x = x!

Decimal -> Factoradic
b=''                       #Output
a=362880                   #Factorial value, set to 9! here
j=int(i)                   #Integer value of the input
x=9                        #Index value
iterate 9 times:           #PSEUDOCODE! This block is in an exec() loop
    b+=`j/a`               #Add floor(j/a) to b
    j%=a                   #Take out all multiples of a in j
    a/=x                   #Set a to (x-1)!, x! / x = (x-1)!
    x-=1                   #Decrement x

Nice solution. I think you can replace '!'==i[0] with '!'in i, and can use a=x=1. Also, you don't need brackets around the exec statement.

You could also replace (len(i)-1) with ~-len(i).

@Volatility, grc: Thanks! I should learn my bitwise operators :)

Nice answer, I took the liberty of trying to replace the if statement with (a,b)['!'in i] and managed to shave off 6 characters.  It's not as readable as it was though... pastebin link

@erjb: Thanks for the suggestion! I used a 2-tuple with the code as a string in-line with the exec function, which saves two more characters :)

GolfScript (48 44 43 chars)
.~\{1{):?\.?%\?/@}9*{*+}+9*}:^{:N,{^N=}?}if

This is a self-contained program. The factoriadic => decimal conversion is quite slow, because it does a search using the decimal => factoriadic conversion rather than a direct base conversion.
The input format allows for a very short mode switch: .~ copies the input string and evaluates it, so if the input is just a number we end up with e.g. "1234" 1234 on the stack, and if it starts with ! (logical not, with any non-empty string being truthy) we end up with e.g. 0 30311 on the stack. Then the value at the bottom of the stack is truthy for decimal => factoriadic and falsy for factoriadic => decimal.

PHP <7.1 178 171 170 168 164 155 147 144 138 126 123 bytes
for($b=$j=1,$i=strlen($x=$argn);+$x?$b<=$x:--$i;$b*=++$j)$r+=$x[$i]*$b;if(+$x)for(;$j>1;$x%=$b)$r.=$x/($b/=$j--)|0;echo+$r;

Run as pipe with -r or test it online.

no extension required
no sub function needed: the factorial base is being reused (incresed/decreased in the loops)
pure integer and string arithmetics, should even work in php 3 (and still works in php 7):
decimal 0 returns empty string instead of 0. (both other PHP answers do too.) If that is unacceptable, add +5 for the extra case.

ungolfed:
// two loops in one: compute the decimal number from a factorial
// or find the first factorial larger than a decimal $x
// the latter inits $r with '0': $i=strlen -> $x[$i]=='' -> (int)$x[$i]==$x[$i]*$b==0
// $b is the current digit´s base; $j is the bases´ latest factor
for($b=$j=1,$i=strlen($x=$argn);+$x?$b<=$x:--$i;$b*=++$j)
    $r+=$x[$i]*$b;
// and now for dec->fact ...
if(+$x)
    for(;$j>1;$x%=$b)
        // both $b and $j are one step too far in the first iteration;
        // -> decrement must precede the actual loop body
        // -> can be merged into the digit calculation -> all braces golfed
        $r.=$x/($b/=$j--)|0;
        // now: go on with the remainder (see loop head)
echo+$r; // final type cast removes leading zeros (from the first loop)
    // and fixes the '0' result (no operations at all on that input!)

abandoned golfing ideas:

$b<=$x --> $b<$x (-1)
would break pure decimal factorials (i.e. those that result in a factorial number with only one non-zero digit).
JMPC´s solution suffers from that; HamZa´s does not.
floor($x/$b) -> (int)($x/$b)
could be a bit faster, but type casting precedes division, so I need the parentheses and don´t gain a byte. $x/$b|0 does the trick
The loop in fact->dec is similar to the factorial-find in dec->fact. Same increment, body does not matter, but unfortunately different preset and different post condition. Dang; could have golfed -21 there.
YAY I found a solution. Took quite a bit of golfing, but chopped off another -4 (no: -9) and closed all bugs/loopholes.

Any more potential ... or am I done golfing?

@JörgHülsermann Thanks for the hint.

+$r instead of $r|0 save one byte. Same for if($x|0)

JavaScript (ES 6) 139 137 122 113 111
tried a different approach using some array magic; but I ended up at 174 172 bytes with that:
f=x=>{if('!'==x[0]){a=x.split``.reverse();i=b=1;r=0;a.pop();a.map(d=>{r+=d*b;b*=++i})}else{t=[];for(i=b=1;b<=x;b*=++i){t.unshift(b)}r='';t.map(b=>{r+=x/b|0;x%=b})}return r}

So I just took my PHP code and translated it. Could remove all the $s and a few ;, but the necessity to initialize vars ate up some of that benefit. Managed to golf both answers down a bit further, though.
golfed
f=x=>{for(r=0,b=j=1,i=x.length;x|0?b<=x:--i;b*=++j)r+=x[i]*b;if(x|0)for(r='';j>1;x%=b)r+=x/(b/=j--)|0;return r}

first version returns '' for decimal 0; add +2 to fix
second version requires string input
both tested in Firefox, Edge and Opera

ungolfed
f=x=>
{
    for(r=0,b=j=1,i=x.length;x|0?b<=x:--i;b*=++j)
        r+=x[i]*b;
    if(x|0)
        for(r='';j>1;x%=b)
            r+=x/(b/=j--)|0;
    return r
}

test suite

dec	resultexpected	ok?

ES5 doesn't have arrow notation IIRC. And if you're going to use ES6, then .split('') => .split\``

@Zacharý Gna I should have noted what browser I tested it in ... probably Firefox or Opera. So ES 6?

Yeah, arrow notation is ES6.

Oh, that caught me off guard, I thought the code block at the top was your solution! Regardless, I don't think you need to say f=. Also, can r+=(x/(b/=j--)|0) be r+=x/(b/=j--)|0?

Python, 128 chars
This takes about half an hour to run, but it's small:
A=[`x`for x in xrange(10**9)if all(x/10**d%10<d+2 for d in range(9))]
i=raw_input()
print A.index(i[1:])if'!'in i else A[int(i)]

It builds a list of all <= 9 digit factoradic numbers in numeric order, then does a lookup or index to convert.
If you want to test, just replace 10**9 with 10**6 and restrict yourself to 6-digit variadic numbers.
I could technically save a character by using range(10**9) instead of xrange(10**9).  Don't try this at home.

No space is needed between d+2 and for

Perl 6, 66 65 60 bytes
-1 byte thanks to Jo King
{/\!/??:1[.flip.chop.comb Z*[\*] 1..*]!![R~] .polymod(2..*)}

Try it online!

Jelly, 15 bytes
ḊV€;0Æ¡µÆ!ṖḌƊ¬?

Try it online!
How it works
ḊV€;0Æ¡µÆ!ṖḌƊ¬?     Main link (monad). Input: integer or string
             ¬?  *) If the given input is a string, run 1); otherwise run 2)

ḊV€;0Æ¡  1) Factorial base -> integer
ḊV€         Remove "!" and map each char to number
   ;0       Append zero (this is needed to run the built-in correctly)
     Æ¡     Built-in conversion

Æ!ṖḌ  2) Integer -> factorial base
Æ!       Built-in conversion
  ṖḌ     Remove a zero at the end, and convert to decimal

Why *) works
¬ is element-wise logical NOT. When given a single integer, it becomes a single zero, which is false. However, when given a string, each element (character) is turned to a zero, and the whole result is an array of zeroes which is true.
Zero as an integer is a special case. It goes through the "factorial -> integer" route, but it still gives zero which is correct.
Without factorial base built-in, 25 bytes
⁵R!µ³%Ḋ:ṖUḌ
⁵R!ḋḊUV€ƊµÇ¬?

Try it online!
How it works
⁵R!µ³%Ḋ:ṖUḌ  Aux. link (monad). Integer -> factorial base
⁵R!µ         Set (1..10)! as left argument
    ³%Ḋ:Ṗ    Compute each digit: (input % (2..10)!) // (1..9)!
         UḌ  Reverse and convert the digit array to decimal

⁵R!ḋḊUV€ƊµÇ¬?  Main link (monad).
         µÇ¬?  If the input is a string, apply the left chain;
               otherwise, apply the aux. link above
⁵R!            (1..10)!
   ḋ           Dot product with...
    ḊUV€Ɗ      Remove "!", reverse, map each character to digit

Mathematica 213 177 175
A factorial number is wrapped in f[], whether it is input or output.
g@{n_,j_,r_}:=If[j==0,FromDigits@r,g@{q=QuotientRemainder[n,j!];q[[2]],j-1,Append[r,q[[1]]]}]
z@n_:=If[!IntegerQ@n, g[{n[[1]],9,{}}], f@Tr@(p=1;# (p++)!&/@Reverse@IntegerDigits@n)]

Usage
z[24201]

f[349]

z[f[349]]

24201

Conversion of factorial to decimal number.
QuotientRemainder[n,j!] recursively acts on the digits of the factorial number from left to right, decrementing j at each step.   QuotientRemainder[349, 5!], for instance, returns {2, 109} and so on.
Conversion of decimal to factorial number.
Moving right to left, the pure function, # (p++)! &, multiplies each digit,#, by the appropriate factorial.

GolfScript, 69 characters
10,1>{1$*}*](.0=33={1>01/-1%0\{~@(@*@+}/\}{~\-1%{1$<},{1$1$/@@%}/}if;

Takes input from STDIN as usual and prints the result. Online test.

Haskell, 221 chars
Code Golf
m v@(a:b)|a=='!'=(sum.zipWith(*)g.map(read.(:[])).reverse) b|True=(fst.until((<0).fst.snd)(\(s,(i,b))->(s*10+b`quot`f i,(i-1,b`rem`f i))).(\n->(0,((1+).last.takeWhile((n>=).f)$[1..], n))).read) v;g=scanl1(*)[1..];f=(g!!)

Usage
$ ghci factorial.hs
ghci> m "1234"
 141120
ghci> m "!54321"
 719

Ungolfed code
parse v@(a:b) | a == '!' = to b
              | otherwise = from v

to = sum . zipWith (*) factorials . map (read . (:[])) . reverse

from = fst . until finished next . boostrap . read
    where finished = ((<0) . fst . snd)
          next (s,(i,r)) = (s * 10 + r `quot` factorial i, (i-1 ,r `rem` factorial i))
          bootstrap n = (0, (lastFact n, n))
          lastFact n = (1+) . last . takeWhile ((n>=) . factorial) $ [1..]

factorials = scanl1 (*) [1..]

factorial = (factorials!!)

By far the most readable entry. Haskell FTW!

PHP 231 214 204
Newest Answer
function g($x){return $x?$x*g($x-1):1;}function f($x,$e){if($x[0]=="!"){for($t=1;$t<$c=strlen($x);$t++){$e+=$x[$t]*g($c-$t);}}else{while(g(++$p)<=$x);while(--$p){$e.=floor($x/g($p));$x%=g($p);}}return$e;}

Old Answer
 function f($n){if($n[0]=="!"){$n=str_split($n);$c=count($n);$f=$y=1;while($c-->1){$e+=($f*$n[$c]);$f*=++$y;}return$e;}else{for($i=$c=1;$i<$n;$i*=$c){$r[$c++]=$i;}foreach(array_reverse($r)as$t){$e.=floor($n/$t);$n=$n%$t;}return$e;}}

Example
echo f('349')."\n"
    .f('!24201')."\n"
    .f('1234')."\n"
    .f('746')."\n"
    .f('!54321')."\n"
    .f('!30311');

Output
24201
349
141120
101010
719
381

I count 212 for the new answer, not 214. $e needs no initialization (-6) and the foreach(range()) can be replaced with a simple for loop (-9). I like the idea, though.

wrong result for pure factorials. 24 should return 1000 but returns 400. fix: g(++$p)<$x --> g(++$p)<=$x (+1)

@Titus Thanks for both of your replies! I updated my answer. I appreciate you helping me improve my answer when yours seems far superior.

I count 2 less than you, again: 204, not 206. Do You include a Windows line break in your byte count?
syntax error in for construct: , should be ;
I have another 7 changes saving 20 bytes on that code. Want them?

D'oh! I fixed those when testing it, but forgot to copy it back. Well spotted. Also sure, I'll be grateful for any suggestions you provide.

Well, it´s actually only 5 changes, but one of them has three parts.
a) obsolete second argument for f() (-3)
b) obsolete blank in function g (-1)
c) obsolete braces in the true branch (-4)
d) swap true and false branches, invert the if condition, then use my sexy type cast to int (-6) This will not affect the decimal 0 result!
e) the remaining for construct can be rewritten with a very nice while(++$t<$c=strlen($x)): increment before body --> $t needs no initialization (-6)

sorry, d) gives only -5. forgot that you have to add a whitespace between else and for. but f) replace floor() with a sexy type cast (-5)

VBA 225
Thanks to Titus for the help! Still looking to golf some more.
Sub a(b)
Set w=WorksheetFunction
e=Len(b)
If IsNumeric(b) Then
i=0
For d=0To 8
h=w.Fact(9-d)
g=b Mod h
If g<b+i Then
i=1
f=f &Int(b/h)
b=g
End If
Next
Else
For d=2To e
f=f+w.Fact(e-d-1)*Mid(b,d,1)
Next
End If
MsgBox f
End Sub

I don´t know VBA, but is there a way to check b for a numeric value instead of comparing the first character?

@Titus There is a numeric check, and the equivalent here would be: If Not IsNumeric(b) Then, but that takes more characters. Now, I didn't go in and re-examine all the code; there may be a slightly better way to do this with IsNumeric overall. -- Correction, there is a slight improvement here. Thanks!

I found another four bytes: For d=9To 1Step-1 and Fact(d) --> For d=0To 8 and Fact(9-d) and another two if you do For d=2To e and Fact(e-d+1)*Mid(b,d,1)

Can the type cast to Int be written in another way?

@Titus Look at you, running circles around me. :) I'm tweaking now... As for Int(), I don't think there is a simpler(smaller) method, no.

I thought about an implicit type cast like the |0 in PHP and JS; looked it up and that is clearly no option in VB. But there could be two more white spaces to drop. Done running. ;)

K, 102
"I"$,/$*:'|:'{{(x-y*g),g:_(x:*x)%y:*/1+!y}\[x,0n;|1+!{$[(x>(*/1+!y))&x<*/1+!y+1;y;.z.s[x;1+y]]}[x;0]]}

Could definitely be improved.
k)"I"$,/$*:'|:'{{,[;g]x-y*g:_(x:*x)%y:*/1+!y}\[(x;0n);|1+!{{$[(x>(*/1+!y))&x<*/1+!y+1;y;.z.s[x;1+y]]}[x;0]}x]} 349
24201
k)"I"$,/$*:'|:'{{,[;g]x-y*g:_(x:*x)%y:*/1+!y}\[(x;0n);|1+!{{$[(x>(*/1+!y))&x<*/1+!y+1;y;.z.s[x;1+y]]}[x;0]}x]} 746
101010
k)"I"$,/$*:'|:'{{,[;g]x-y*g:_(x:*x)%y:*/1+!y}\[(x;0n);|1+!{{$[(x>(*/1+!y))&x<*/1+!y+1;y;.z.s[x;1+y]]}[x;0]}x]} 1234
141120

D (159 chars)
int x(string n){import std.conv;int r,i=9,f=9*'鶀',d;if(n[0]<48){while(r.text.x<n[1..$].to!int)r++;}else{d=n.to!int;while(i){r=r*10+d/f;d%=f;f/=i--;}}return r;}

Ungolfed and with program entry point
All command line arguments are printed as <original> -> <converted>. Only decimal to factoradic is actually implemented in x. The other way round just calls x with all decimal numbers (0..*) until the result equals the input. This takes ~3 seconds for the largest input (!987654321).
Executable online version: http://dpaste.dzfl.pl/46e425f9
void main(string[] args) {
    import std.stdio;
    foreach (arg; args[1 .. $]) {
        writefln("%s -> %s", arg, x(arg));
    }
}

int x(string n) {
    import std.conv;
    int r, i=9, f=9*'鶀', d;  // 鶀's Unicode index equals 8*7*6*5*4*3*2*1

    // If the first character value is less than 48 ('0') it should be a '!'.
    if (n[0] < 48) {
        // Call x with different input (0..*) until it matches our n.
        // r.text.x is rewritten as x(text(r)).
        while (r.text.x < n[1..$].to!int) r++;
    } else {
        d = n.to!int;
        // Try d / 9!, d / 8!, etc. just as in the problem description.
        while (i) {
            r = r*10 + d/f;
            d %= f;
            f /= i--;
        }
    }
    return r;
}

I think it might be possible to change string n to char[]n to save one byte (I know I'm late here).

Also, I think if(n[0]<48){while(r.text.x<n[1..$].to!int)r++;} can become if(n[0]<48)while(r.text.x<n[1..$].to!int)r++; to save two bytes.

Perl 6, 150 bytes
{/^\!/??([+] [Z*] .comb.skip.reverse,[\*] 1..*)!!(reduce
->\a,\b{a[0]~a[1] div b,a[1]%b},("",+$_),|(first
*[*-1]>$_,[\,] [\*] 1..*).reverse[1..*])[0]}

PHP, 124 bytes
for($f=1;("$">$a=$argn)&&~$c=strrev($a)[$n];)$r+=$c*$f*=++$n;for(;$a>=$f*=++$i;);for(;~-$i;$a%=$f)$r.=0|$a/$f/=$i--;echo+$r;

Try it online!
Extended
for($f=1;("$">$a=$argn)&&~$c=strrev($a)[$n];) # runs in case of "!" at the beginning
  $r+=$c*$f*=++$n; #reverse string multiply with the next factorial "!"*$f=0
for(;$a>=$f*=++$i;); # runs not in case of "!" at the beginning string comparing. search the factorial that is higher as input value
for(;~-$i;$a%=$f) # runs only when the second loop had runs
  $r.=0|$a/$f/=$i--; # concat the value of the division with the highest factorial used
echo+$r; # Output result

APL(NARS), 36 chars, 72 bytes
{⍵⊆⎕D:10⊥(9..2)⊤⍎⍵⋄t+.×⌽!⍳≢t←⍎¨,1↓⍵}

it seems that 10⊥(9..2)⊤ is better than the recursive function, thanks to Howard for the other APL solution that show that... (even if i not understand 100%). Input for numbers without '!' <10!. Test:
  u←{⍵⊆⎕D:10⊥(9..2)⊤⍎⍵⋄t+.×⌽!⍳≢t←⍎¨,1↓⍵}
  u¨'1234' '746' '!54321' '!30311' '!24201'
141120 101010 719 381 349
  u '0'
0
  u '!0'
0
  u '9'
111
  u '!111'
9
  u '!9'
9

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


text:
Number of holes in a polygon
The Problem: Count the number of holes in a connected polygon. Connectivity of the polygon is guaranteed by the condition that every triangle in the input triangulation shares at least 1 side with another triangle and that there is only one such connected set of triangles.
Input is a list L of n points in the plane and a list T of 3-tuples with entries from 0...n-1. For each item in T the tuple (t_1,t_2,t_3) represents the three vertices (from the list L) of a triangle in the triangulation. Note that this is a triangulation in the sense of 'polygon triangulation', because of this there will never be two triangles in T that overlap. An additional stipulation is that you will not have to sanitize the input, L and T do not contain any repeats.
Example 1: If L = {{0,0},{1,0},{0,1},{1,2}} and T = {{0,1,2},{1,2,3}} then the polygon specified has a hole count of 0.

Example 2: If L = {{0,0},{1,0},{2,0},{2,1},{2,2},{1,2},{0,2},{0,1},{.5,.5},{1.5,.5},{1.5,1.5},{.5,1.5}} and T = {{5,6,11},{5,10,11},{4,5,10},{3,8,10},{2,3,9},{2,8,9},{1,2,8},{0,1,8},{0,8,11},{0,7,11},{6,7,11},{3,4,10}} then the polygon input should result in an output of 2.

The task is to write the shortest program (or function) that takes L and T as input and returns the number of holes. The 'winner' will be recognized as the entry with the least character count (tentative end date 1st of June).
Sample input formatting (note the 0 indexing):
0,0
1,0
0,1
1,2
0,1,2
1,2,3

"Connectivity of the polygon is guaranteed by the condition that every triangle in the input triangulation shares at least 1 side with another triangle." -- no. That's not a sufficient condition. Take, for example, T=1,2,3/1,2,4/5,6,7/5,6,8. Every triangle shares an edge with another triangle, but the triangulation is disconnected

May we assume the input represents a valid partial triangulation (no two triangles overlap and no triangle is present twice) and the triangulation is connected?

Note that the number of holes is not the genus of the shape. Every subset of plane has a genus of 0. "The genus of a connected, orientable surface is an integer representing the maximum number of cuttings along non-intersecting closed simple curves without rendering the resultant manifold disconnected"

May we also assume the input is edge-connected in the sense it is not possible to remove a finite set of points to render the shape disconnected? (ex: T=1,2,3/1,4,5 is connected but not edge-connected)

Thank you for the clarification questions Jan. As a summary: (1) Yes, there will be neither overlap nor repetition (2) Yes, you may assume input is edge-connected in the sense prescribed (3) 'genus' is not strictly applicable I agree: should I strike usage of it in favor of "number of holes"?

Alternatively I could claim that the exterior of the polygon (out to infinity in all directions) is also considered a face in the complex and then 'genus' would be valid, no?

Genus would still be invalid. Any closed curve separates the region in two or more regions - the genus is zero. Filling a circular (or polygonal) hole by a disk (a circular - or polygonal - region of the plane) doesn't change the genus in any way. Only if the triangles didn't lie in a plane, the genus could be non-zero.

May I assume the points are not duplicated (in L) either? :-)

Affirmative, this is the case.

There's nothing wrong with self-answers in general on stackExchange, and there's nothing wrong with self-answers here (except it's kinda discouraging if the optimal solution appears right away with the question. But then it's about not posting the answer right away - but you can still declare its length and see if someone else finds it or beats it). Moreover, the comment formatting has broken your indentation.

? "The 'winner' will be recognized as the entry with the least character count (tentative end date 1st of April)"

+1 The more I look into this question, the greater my appreciation for it. I now realize that it can be solved regardless of the size of the holes.

Can the vertex of one triangle appear mid-edge on another?

@KeithRandall Technically if the input is supposed to be a valid triangulation then the presence of a vertex 'mid-edge' on would create a 4 sided face. The presence of such a face in the triangulation should not interfere with topological or visual techniques for counting holes, but if it is relevant to your solution you may assume that this will not occur in the input.

@DavidCarraher Is this not a satisfactory 'win-condition' for code-golf? I wondered when writing this question if 'char-count' as the goal might not be unfair.

The condition is fine. It's the date I was referring to. (April 1)

I think my brain preformed a -- when I wanted a ++. Thanks.

I'm not sure why this business about end dates has started cropping up recently. You're allowed to change the accepted answer, so there's no need to set an end date. It's reasonable to have a mental idea that you'll wait a week before selecting an answer in order not to scare people into thinking that the first answer is unbeatable, but as long as you're active on the site you can change the selected answer if someone posts a better one. Relevant meta discussions include http://meta.codegolf.stackexchange.com/q/542/194 and http://meta.codegolf.stackexchange.com/q/193/194

Can we assume that each list in T is sorted?

@Volatility I'm going to say no to that. While when I constructed the examples I numbered my triangles from lowest index vertex to highest, I think it would be more likely for the 'author' of a triangulation to maintain constant orientation within the triangles instead of switching to accomodate the names of the vertices.

GolfScript (23 chars)
~.{2*2/~}%{$}%.&,@@+,-)

Assumes input format using GolfScript array notation and quoted (or integral) coordinates. E.g.
$ golfscript codegolf11738.gs <<<END
[["0" "0"] ["1" "0"] ["2" "0"] ["2" "1"] ["2" "2"] ["1" "2"] ["0" "2"] ["0" "1"] [".5" ".5"] ["1.5" ".5"] ["1.5" "1.5"] [".5" "1.5"]] [[5 6 11] [5 10 11] [4 5 10] [3 8 10] [2 3 9] [2 8 9] [1 2 8] [0 1 8] [0 8 11] [0 7 11] [6 7 11] [3 4 10]]
END
2

(Online equivalent)
or
$ golfscript codegolf11738.gs <<<END
[[0 0] [1 0] [0 1] [1 2]] [[0 1 2] [1 2 3]]
END
0

(Online equivalent)

Python, 71
What follows is a program (not a function) that calculates the desired number.
len(set().union(*(map(frozenset,zip(t,t[1:]+t))for t in T)))-len(L+T)+1

Example usage:
>>> L = ((0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,1),(.5,.5),(1.5,.5),(1.5,1.5),(.5,1.5))
>>> T = ((5,6,11),(5,10,11),(4,5,10),(3,8,10),(2,3,9),(2,8,9),(1,2,8),(0,1,8),(0,8,11),(0,7,11),(6,7,11),(3,4,10))
>>> len(set().union(*(map(frozenset,zip(t,t[1:]+t))for t in T)))-len(L+T)+1
2

+1 for using the splat, using frozenset instead of sorting, zip (can't say I've ever used it before, need to acquaint myself.)

APL, 36
{1+(⍴⊃∪/{{⍵[⍋⍵]}¨,/3 2⍴⍵,⍵}¨⍵)-⍴⍺,⍵}

The function takes L as its left argument and T as its right.
For example:
      L←(0 0)(1 0)(0 1)(1 2)
      T←(0 1 2)(1 2 3)
      L{1+(⍴⊃∪/{{⍵[⍋⍵]}¨,/3 2⍴⍵,⍵}¨⍵)-⍴⍺,⍵}T
0
      L←(0 0)(1 0)(2 0)(2 1)(2 2)(1 2)(0 2)(0 1)(.5 .5)(1.5 .5)(1.5 1.5)(.5 1.5)
      T←(5 6 11)(5 10 11)(4 5 10)(3 8 10)(2 3 9)(2 8 9)(1 2 8)(0 1 8)(0 8 11)(0 7 11)(6 7 11)(3 4 10)
      L{1+(⍴⊃∪/{{⍵[⍋⍵]}¨,/3 2⍴⍵,⍵}¨⍵)-⍴⍺,⍵}T
2

Explanation, going from right to left:

⍴⍺,⍵ concatenates the two input vectors and returns their length (V + F)
Stepping inside the next block:

¨⍵ applies the function on the left to every element of the right argument and returns the result
⍵,⍵ returns the right argument concatenated with itself
3 2⍴ shapes the vector argument into three pairs. In this case it pairs together the first and second, third and first, and second and third items of the vector.
,/ joins the vector argument together
⍵[⍋⍵] sorts the right argument
∪/ filters out any duplicates
⍴⊃ turns a nested scalar into a vector, and it returns the length of it.
The whole function returns the number of edges in the shape (E)

1 is self-explanatory (I hope...)

The whole function then returns 1+E-(V+F), or 1-(F+V-E).

Pretty much exactly what my GolfScript solution does. I'm surprised it's so much longer than GolfScript.

@PeterTaylor I was surprised your GolfScript solution was so much shorter! (But then again, it is GolfScript)

 Mathematica, 93 (not much golfed yet)
f[l_, t_] :=  Max@MorphologicalComponents[Erosion[Graphics[
                                                        GraphicsComplex[l, Polygon[t + 1]]], 1]] - 1

(Spaces added for clarity)
Testing:
f[{{0, 0}, {1, 0}, {0, 1}, {1, 2}}, {{0, 1, 2}, {1, 2, 3}}]
(*
 -> 0
*)

{l, t} = {{{0, 0}, {1,   0}, {2,    0}, {2,     1}, {2,    2}, {1, 2}, {0, 2},
           {0, 1}, {.5, .5}, {1.5, .5}, {1.5, 1.5}, {.5, 1.5}},

           {{5, 6, 11}, {5, 10, 11}, {4, 5, 10}, {3, 8, 10}, {2, 3,  9},
            {2, 8,  9}, {1,  2,  8}, {0, 1,  8}, {0, 8, 11}, {0, 7, 11}, {6, 7, 11}, {3, 4, 10}}};
f[l, t]
 (*
  -> 2
 *)

Doesn't this rely on the triangles or holes having certain minimal size (the argument to Erosion)?

@JanDvorak Perhaps I'm wrong, but I think that unless you use infinite precision arithmetic, any solution will work until you reach a certain minimal size (you'll have to decide if three points are aligned or not). It's just that in this kind of solution the problem is explicitly stated.

if you use the topological approach, you don't have to. If there are three points collinear then you require a zero-area triangle there - otherwise you have a hole.

@belisarius.  Here's the answer I received from Wolfram Technical Support about the discrepancy between our results: "Hello -
Thank you for your email.
I have confirmed that your code gives different results on Mac and Windows.  I do not think that this is intended behavior, so I have filed a report with our developers on the issue.  I will be sure to pass on any useful information that I get from our developers on this issue.
Please let me know if you have any further questions.
...Technical Support
Wolfram Research, Inc."

@DavidCarraher "Yes, I have further questions: Will you send me a check for each bug?"

Mathematica 76 73 72 67 62
After much experimentation, I came to realize that the precise location of the vertices was of no concern, so I represented the problem with graphs.  The essential invariants, the number of triangles, edges and vertices stayed invariant (provided line crossing was avoided).
There were two kinds of internal "triangles" in the graph: those were there was presumably a face, i.e. a "filled" triangle, and those where there were not.  The number of internal faces did not have any relation to the edges or vertices.  That meant that poking holes in fully "filled" graphs only reduced the number of faces.  I played systematically with variations among triangles, keeping track of the faces, vertices and edges.  Eventually I realized that the number of holes always was equal to 1 - #faces -#vertices + #edges. This turned out to be 1 minus the Euler characteristic (which I only had known about in the context of regular polyhedra (although the length of the edges was clearly of no importance.
The function  below returns the number of holes when the vertices and triangles are input.  Unlike my earlier submission, it does not rely on a scan of an image. You can think of it as 1 - Euler's characteristic, i.e. 1 - (F +V -E) whereF= #faces, V=#vertices, E=#edges.
The function returns the number of holes, 1 - (F + V -E), given the actual faces (triangles) and vertices.
It can be easily shown that the removal of any triangle on the outside of the complex has no affect on the Euler characteristic, regardless of whether it shares one or 2 sides with other triangles.
Note: The lower case v will be used in place of the L from the original formulation; that is, it contains the vertices themselves (not V, the number of vertices)
f is used for the T from the original formulation; that is, it contains the triangles, represented as the ordered triple of vertex indices.
Code
z=Length;1-z@#2-z@#+z[Union@@(Sort/@{#|#2,#2|#3,#3|#}&@@@#2)]&

(Thanks to Mr. Wizard for shaving off 5 chars by eliminating the replacement rule.)

Example 1
v = {{0, 0}, {1, 0}, {0, 1}, {1, 2}};
f = {{0, 1, 2}, {1, 2, 3}};
z=Length;1-z@#2-z@#+z[Union@@(Sort/@{#|#2,#2|#3,#3|#}&@@@#2)]&[v, f]

0

Zero holes.

Example 2
v = {{0, 0}, {1, 0}, {2, 0}, {2, 1}, {2, 2}, {1, 2}, {0, 2}, {0,
    1}, {.5, .5}, {1.5, .5}, {1.5, 1.5}, {.5, 1.5}};
f = {{5, 6, 11}, {5, 10, 11}, {4, 5, 10}, {3, 8, 10}, {2, 3, 9}, {2,
    8, 9}, {1, 2, 8}, {0, 1, 8}, {0, 8, 11}, {0, 7, 11}, {6, 7,
    11}, {3, 4, 10}};
z=Length;1-z@#2-z@#+z[Union@@(Sort/@{#|#2,#2|#3,#3|#}&@@@#2)]&[v, f]

2

Thus, 2 holes are in example 2.

are you basically rasterising the triangulation and dumping a graphics library on that image? Doesn't that fail if a hole is too small?

your second example returns 0 here (that's why I haven't used MorphologicalEulerNumber[]). Mma 9.01, Win XP.

I'm using 9.0.1 also, but on a Mac.  Are you're saying Mathematica returns a different answer from mine on Windows?  If so, that sounds like a bug (in the Windows XP version).

@DavidCarraher Yep: http://i.stack.imgur.com/LKcr1.png

@Jan Dvorak.  MorphologicalEulerNumber sometimes requires an image; it refuses to accept a graphics object.  In these cases, the size of the hole and the resolution are critical (see http://codegolf.stackexchange.com/questions/8706/regions-of-regular-polygons/8707#8707). But here it works directly with the Graphics object, which explicitly contains all of the vertices. I imagined (or hoped) that it would use an approach that did not depend on the image.  I wish I knew how it attempted to solve the issue.  Perhaps some spelunking in the source code for the function will clarify things.

@belisarius  That's a mystery.

@JanDvorak I proposed a solution that does not rely on scanning an image.

David, I haven't read your entire post yet (thought I anticipate a good read!) but there doesn't seem to be any point in using UndirectedEdge.  Why not: {a|b,b|c,c|a}?

@Mr.Wizard, I wanted a single binary "operator" that would dispense with the need for list brackets. You are right about the edges being unnecessary, but since I had to use some symbol, I thought, why not use something that conveys that the pairs are edges.  The drawback is that the FullForm is clumsy in SE. I couldn't find a way to past the symbol alone.

@DavidCarraher how about: z=Length;1-z@#2-z@#+z[Union@@(Sort/@{#|#2,#2|#3,#3|#}&@@@#2)]&[v,f]

Thanks! It now fits on one line, and no more \[UndirectedEdge] in the code.

Ruby, 239 characters (227 body)
def f t
e=t.flat_map{|x|x.permutation(2).to_a}.group_by{|x|x}.select{|_,x|x.one?}.keys
n=Hash[e]
(u,n=n,n.dup;e.map{|x|a,b=*x;n[a]=n[n[a]]=n[b]})until n==u
n.values.uniq.size+e.group_by(&:last).map{|_,x|x.size}.reduce(-1){|x,y|x+y/2-1}
end

note that I'm only considering the topology. I'm not using the vertex positions in any way.
caller (expects T in Mathematica or JSON format):
input = gets.chomp
input.gsub! "{", "["
input.gsub! "}", "]"
f eval(input)

Test:
f [[0,1,2],[1,2,3]]
#=> 0
f [[5, 6, 11], [5, 10, 11], [4, 5, 10], [3, 8, 10], [2, 3, 9], [2, 8, 9], [1, 2, 8], [0, 1, 8], [0, 8, 11], [0, 7, 11], [6, 7, 11], [3, 4, 10]]
#=> 2
f [[1,2,3],[3,4,5],[5,6,1],[2,3,4],[4,5,6],[6,1,2]]
#=> 1

Yay, an euler characteristic approach. That's how I did it in python.

@Kaya. (See Egg of Columbus http://en.wikipedia.org/wiki/Egg_of_Columbus) Once someone has given an Eulerian answer to your question, the likelihood that others will follow increases greatly.  I can assure you it's far more challenging and gratifying to discover the approach on one's own, only afterwards making the connection to Euler's work with polyhedra.

Python, 107
I realized that taking the pairs directly was shorter than from itertools import* and typing combinations(). Yet I also noticed that my solution relied on the input triangular faces having their vertices listed in consistent order. Therefore the gains in character count are not that large.
f=lambda l,t:1-len(l+t)+len(set([tuple(sorted(m))for n in[[i[:2],i[1:],[i[0],i[2]]]for i in t]for m in n]))

Python, 115
Euler characteristic approach, the verbosity of itertools seems impossible to avoid. I wonder if it would be cheaper to use a more direct technique for making pairs of vertices.
from itertools import*
f=lambda l,t:1-len(l+t)+len(set([m for n in[list(combinations(i,2)) for i in t]for m in n]))

Usage example:
> f([[0,0],[1,0],[0,1],[1,2]],[[0,1,2],[1,2,3]])
> 0
> f([[0,0],[1,0],[2,0],[2,1],[2,2],[1,2],[0,2],[0,1],[.5,.5],[1.5,.5],[1.5,1.5],[.5,1.5]],[[5,6,11],[5,10,11],[4,5,10],[3,8,10],[2,3,9],[2,8,9],[1,2,8],[0,1,8],[0,8,11],[0,7,11],[6,7,11],[3,4,10]])
> 2

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


text:
Counting ways of scoring k points in n games with half-points for draws
If a game can result in a win, worth one point; a draw, worth half a point; or a loss, worth no points; how many ways are there of scoring k points in n games?
Applicable scenarios include NFL and chess.

Input is via stdin, and consists of n and k on separate lines.
n will be a non-negative integer. (n ≤ 16)
k will be either a non-negative integer or a non-negative integer plus a half. (k ≤ n)
Output is to stdout. It may, but does not have to, include a trailing newline.

Test cases
In each case, the first two lines are user-supplied input and the third line is the program output.
10
4.5
8350

16
8
5196627

16
13.5
13328

12
12
1

http://oeis.org/A027907

This is very insightful.  I have a working solution in c# which compiles to the requirements outlined within the problem.  I'm merely curious if someone can come up with a more compact solution than what I have.  Cheers!

Perl 59 bytes
@0=map"$v"+($v=$u)+($u=$_),@0,0,0for(@0=1)x<>;print@0[<>*2]

Iteratively generates each row of the triangle of trinomial coefficients up to n, and then prints the correct term, 2k.

Ruby 73 bytes
r=*1
gets.to_i.times{r<<0<<u=v=0;r.map!{|t|v+(v=u)+u=t}}
p r[gets.to_f*2]

Largely equivalent to the Perl solution above.

Python 84 bytes
r=[1]
exec"r=map(sum,zip(r+[0],[0]+r,[0,0]+r))+[1];"*input()
print r[int(input()*2)]

Same method as both solutions above.

PHP 91 bytes
<?for($n=+fgets(STDIN);(${$j--}+=$$j+${$j-1})?:$n--*$j=$i+=2;${0}=1);echo${fgets(STDIN)*2};

Despite being the longest, this was actually the most fun to work on.

R - 81
cat(sum(rowSums(do.call(expand.grid,replicate(scan(n=1),0:2,s=F)))==2*scan(n=1)))

A bit longer (106) but I also enjoyed writing it as a recursion:
Z=function(n,k)if(n<1|k<0)0 else if(n<2&k<3)1 else Z(n-1,k)+Z(n-1,k-1)+Z(n-1,k-2);Z(scan(n=1),2*scan(n=1))

C# (189 bytes)
Collaborative results from @glthomas, @recursive, @PeterTaylor and @primo
Best Solution (189 Bytes)
@glthomas and @recursive each found an additional 2 Bytes over the weekend. (We're convinced that this is the optimal solution using .Net 4.0 and compiling in VS 2010)!
using S=System.Console;class C{static void Main(){S.Write(G(G(),2*G()));}
static float G(float L=-1,float T=1){return L<0?float.Parse(S.ReadLine())
:T==0?1:--L<0?0:G(L,T)+G(L,T-1)+G(L,T-2);}}

Improved Solution (193 Bytes)
using System;class C{static void Main(){Func<float,float,float>W=null;W=(n,k)=>n<0?
k*float.Parse(Console.ReadLine()):k==0?1:--n<0?0:W(n,k)+W(n,k-1)+W(n,k-2);
Console.Write(W(W(-1,1),W(-1,2)));}}

The additional Byte was saved by combining the input acquisition and static recursive method into a single multipurpose Func<>.  Input acquisition is triggered when we pass in a negative value of n
Original Solution (195, 194)
using K=System.Console;class C{static void Main(){K.Write(T(int.Parse(K.ReadLine
()),2*float.Parse(K.ReadLine())));}static float T(int n,float k){return k==1?1:--
n<0?0:T(n,k)+T(n,k-1)+T(n,k-2);}}

You can save one more byte by changing k<1?k+1 to k==0?1. It might be possible to save another if --n could somehow be moved to the front of the expression, i.e. return--n...

@primo, unfortunately that alters the output, because k can sometimes be -1 because of the T(n,k-2) method call.  Therefore we must check for k<1.

I don't think it will. The k<0s will be allowed to propagate, true, but they will eventually be quenched when n reaches zero. Because a k that is less than zero cannot produce a k equal to zero in the successive calls, it cannot change the result.

@primo I was incorporating both your second suggestion along with your first suggestion.  The idea to  return--n.. was interfering with my testing.  I agree you can save a byte by converting k<1?k+1 to k==0?1.  It appears the reason it doesn't work to move --n to the front of the expression is due to order of operation.  The condition on k takes precedent over the condition on n.  Wait until you see my post on 193 bytes :)

Nice. Here's 7 bytes more: Func<float,float,float>W=null;W=(n,k) => Func<float,float,float>W=(n,k).

Nice trick with the null. I tried to use a recursive delegate and it didn't compile, so I dropped that line of investigation.

@PeterTaylor Interesting... mono-2.6.7 has no problems, although I see now that VS2010 chokes on it.

@primo check it out, 189 Bytes :)

@glthomas nice improvements!

C# (210 209 chars)
More efficient: iterative approach (209 chars):
using K=System.Console;class C{static void Main(){int
n=int.Parse(K.ReadLine()),k=(int)(2*float.Parse(K.ReadLine())),j;var t=new
int[k+3];for(t[2]=1;n-->0;)for(j=k+2;j>1;)t[j]+=t[--j]+t[j-1];K.Write(t[k+2]);}}

Less efficient: recursive approach (210 chars);
using K=System.Console;class C{static void Main(){int
n=int.Parse(K.ReadLine()),k=(int)(2*float.Parse(K.ReadLine()));K.Write(T(n,k));}static
int T(int n,int k){return k<1?k+1:--n<0?0:T(n,k)+T(n,k-1)+T(n,k-2);}}

Note that if k is non-integral, it should be supplied in a format applicable to the locale. In my case that means that I have to format the input using , as the decimal separator.

209 Bytes, you missed an easy 4 bytes :)
using K=System.Console;class C{static void Main(){int n=int.Parse(K.ReadLine()),k=(int)(2*float.Parse(K.ReadLine())),j;var t=new int[k+3];for(t[2]=1;n-->0;)for(j=k+2;j>1;)t[j]+=t[--j]+t[j-1];K.Write(t[k+2]);}}

@user1177611, it wasn't clear that that was permitted. I've edited the question and, among other changes, made that explicit.

An anonymous user suggested saving a character in the iterative version by defining t=new int[99]. Technically with the current spec one could get away with t=new int[35], but I think that limiting the value of n to no more than 16 is a pointless restriction.

Prior to being reworded, this problem started as an NFL win total combinatorics question. As such, 16 is currently the highest Win Total a team can achieve over one season.  Though there has been a lot of debate regarding the expansion to an 18 game season. So, t=new int[99] is virtually future proof (at least as it pertains to the NFL)

GolfScript (39 chars)
'.'/(~2*@,+[1]@{[0.@0+{@2$2$++@@}/+]}*=

Online demo
Based on my answer to a previous question about binomial coefficients.

APL (22)
+/(2×⎕)=+⌿(N⍴3)⊤⍳3*N←⎕

It's not exactly efficient though (set your workspace size to a couple of gigabytes if you want it to actually work up to N=16).


text:
Chess960 position generator
Context

Chess960 (or Fischer Random Chess) is a variant of chess invented and advocated by former World Chess Champion Bobby Fischer, publicly announced on June 19, 1996 in Buenos Aires, Argentina. It employs the same board and pieces as standard chess; however, the starting position of the pieces on the players' home ranks is randomized

Rules

White pawns are placed on the second rank as in standard chess
All remaining white pieces are placed randomly on the first rank
The bishops must be placed on opposite-color squares
The king must be placed on a square between the rooks.
Black's pieces are placed equal-and-opposite to White's pieces.

From: http://en.wikipedia.org/wiki/Chess960
For all the people that would like to post answers...
you have to make a Chess960 positions generator, capable of randomly generate one of the 960 positions following the rules described above (it has to be capable of outputting any of the 960, hardcoding one position is not accepted!), and you only need to output the white rank one pieces.
Example output:
rkrbnnbq
where:

k king
q queen
b bishop
n knight
r rook

This will be code golf, and the tie breaker will be the upvotes.

When you say that it has to be capable of outputting any of the 960 positions, do they have to be equiprobable?

Interesting, I haven't really thought of that... I mean ideally it should be, I think... The answers so far offer this quality, ...right ?

The two which are written in languages which have builtins that shuffle uniformly do; the two GolfScript ones are close but not quite uniform.

I would say that close is good enough

This question inspired me to ask http://codegolf.stackexchange.com/questions/12322/chess960-position-lookup

GolfScript (49 48 chars, or 47 for upper-case output)
'bbnnrrkq'{{;9rand}$.'b'/1=,1$'r'/1='k'?)!|1&}do

This uses the standard technique of permuting randomly until we meet the criteria. Unlike w0lf's GolfScript solution, this does both checks on the string, so it is likely to run through the loop more times.
Using upper case allows saving one char:
'BBNNRRKQ'{{;9rand}$.'B'/1=,1$'R'/1=75?)!|1&}do

Ruby 1.9, 67 65 characters
Ah, the old "keep randomizing until you generate something valid" technique...
$_=%w(r r n n b b q k).shuffle*''until/r.*k.*r/&&/b(..)*b/
$><<$_

(In Ruby 2.0, %w(r r n n b b q k) could be 'rrnnbbqk'.chars)

In 1.9.3 you can spare the ~ with the cost of a warning, when available. http://pastebin.com/nuE9zWSw

@manatwork that's great, thanks!

the "keep randomizing until you generate something valid" technique is still much faster than the "shuffle the list of possibilities, filter and take first" technique that purely functional languages like APL tend to produce :-)

I think this is quite elegant. Can you explain why until/r.*k.*r/&&/b(..)*b/ actually works? It's easy enough to imagine what it does given the context, but I don't get why you assign to the $_ variable, which is supposed to be The last input line of string by gets or readline. Thread and scope local. - What has that to do with anything? Oh, mysterious Ruby.

@Daniero that's definitely what the $_ variable is.  It works because ruby has some neat methods such as Kernel#chop that work like the equivalent String#chop method but with $_ as their receiver.  This saves a lot of time when (for example) you're writing a read/process/write loop using ruby -n or ruby -p.

Can't /b(..)*b/ be shortened to /^b.*b$/?

@GigaWatt no. The former matches if there's an even number of characters between some two B's. The latter matches only if the B'S are at the ends.

GolfScript 60 49
;'qbbnnxxx'{{9rand*}$.'b'/1=,2%}do'x'/'rkr'1/]zip

(shortened to 49 chars thanks to Peter Taylor's great tips)
Online test here.
An explanation of the code:
;'qbbnnxxx'         # push the string 'qbbnnxxx' on the clean stack
{

    {9rand*}$       # shuffle the string

    .'b'/1=,2%      # count the number of places between the 'b's
                    # (including the 'b's themselves)
                    # if this count is even, the bishops are on
                    # squares of different colors, so place a 0
                    # on the stack to make the do loop stop

}do                 # repeat the procedure above until a
                    # good string is encountered

'x'/                # split the string where the 'x's are

'rkr'1/]zip         # and put 'r', 'k' and then 'r' again
                    # where the 'x's used to be

Your method for checking that there's an even number of letters between the bs seems very long. How about .'b'/1=,2%?

And you can avoid discarding failed attempts by pulling the 'qbbnnxxx' out of the loop and reshuffling the same string.

@PeterTaylor Thank you for the great tips. For the "count between 'b's" issue I felt that there should be a shorter way, but I just couldn't find it.

J, 56 characters
{.(#~'(?=.*b(..)*b).*r.*k.*r.*'&rxeq"1)'kqbbnnrr'A.~?~!8

it takes several seconds on my machine due to the inefficient algorithm. Some speed may be gained by adding ~.(remove duplicates) before 'kqbbnnrr'.
explanation:

?~!8 deals 8! random elements from 0 ... 8!
'kqbbnnrr'A.~ uses them as anagram indexes to the string kqbbnnrr.
(#~'...'&rxeq"1)' filters them by the regex in quotes.
{. means "take the first element"

K,69
(-8?)/[{~*(*/~~':{m=_m:x%2}@&x="b")&(&x="k")within&"r"=x};"rrbbnnkq"]

Python, 105 chars
Basically chron's technique, minus the elegant Ruby stuff.
import re,random
a='rrbbnnkq'
while re.search('b.(..)*b|r[^k]*r',a):a=''.join(random.sample(a,8))
print a

Thanks to Peter Taylor for the shortening of the regex.

not s('b(..)*b',a) seems like a long-winded way of saying s('b.(..)*b',a). Also, sample may be one character shorter than shuffle, but it requires an extra argument.

You're right about the regex, Peter. Thanks! Shuffle returns None though, so it's no good :(

Missed the forest for the trees. You don't need two regexes, because you're checking the same string and or is equivalent to regex alternation (|). Saves 13 chars.

@PeterTaylor Good catch! thanks.

Retina, 36 30 bytes
6 bytes saved thanks to Neil

qbnbnrrr
/b.(..)*b/+V?`
1`r
k

Try it online!
Explanation

qbnbnrrr

Start with the list of pieces except we have three rooks and no king
/b.(..)*b/+V?`

Keep shuffling the list as long as it matches the regex b.(..)*b (odd number of pieces between bishops)
1`r
k

Replace the second rook with a king

Save 2 bytes each removing the .* from the loop condition. (Although I would have written it /b(..)*b/^+ for the same reduced byte count.) And you can just use a limit to replace the second r with a k, saving another 2 bytes.

Thanks @Neil! For some reason I thought the loop condition had to match the full input, I didn't know it could be a partial match. And I just didn't think of this much simpler way of replacing the second r

Perl, 69 chars
$_=rrbbnnkq;/r[^k]*r|b.(..)*b/||say while s/(.{@{[time%8]}})(.)/$2$1/

To test it, add $|=1; at the beginning to see progress and keep tabs by pipeing into another perl process like this:
perl -E'$|=1;$_=rrbbnnkq;/r[^k]*r|b.(..)*b/||say while s/(.{@{[time%7]}})(.)/$2$1/' \
| perl -nlE'$a{$_}++ or say"$_ ".keys%a'

This will e v e n t u a l l y get the 960 valid permutations.
To run the test fast, swap out time%8 with int rand 8 like this:
perl -E'$_=rrbbnnkq;/r[^k]*r|b.(..)*b/||say while s/(.{@{[int rand 8]}})(.)/$2$1/' \
| perl -nlE'$a{$_}++||say"$_ ".keys%a'


text:
Fix unbalanced brackets
Consider the alphabet A ="()[]{}<>". Think of the characters in the alphabet as opening and closing brackets of 4 different types. Let's say that a string over the alphabet A is balanced if

it is empty -or-
it is not empty -and- the number of opening and closing brackets of each type match -and- each opening bracket has a corresponding closing bracket of the same type to the right of it -and- the substring between each pair of corresponding brackets is balanced.

For example, the strings "", "()", "<[]>", "{}{}[[]]" are balanced, but the strings "(", "{>", ")(", "<>>", "[(])" are not balanced.
Task: Given a (possibly unbalanced) input string S over the alphabet A, find all possible ways to insert minimal number of brackets to make the string balanced. More precisely,
Input: any string S over the alphabet A.
Output: all possible balanced strings of the shortest length over the same alphabet containing S as a subsequence.
Some examples (a string to the left of an arrow denotes an input, the list of strings to the right of the arrow denotes the corresponding output):

"" → ""
"()[]" → "()[]"
"[" → "[]"
">" → "<>"
"{}]" → "[{}]", "{}[]"
"<<" → "<><>", "<<>>"

Note that:

The output always contains at least one string.
The output contains only those types of brackets that occur in the input string.
All strings in the output are of the same length.
If an input string is balanced, then the output consists of the same single string.

Implementation requirements:

Your implementation may be in any programming language and should be as short as possible (in terms of character count or byte count - which one is less). You may represent the source in ASCII, Unicode or any other alphabet normally used in your language. If a program in your language has a shorter standard encoding as a sequence of bytes (like x86 assembly), you may choose to claim its length based on byte count, although you may submit the program in a hexadecimal form (e.g. 7E-FF-02-...) and/or a textual form using standard mnemonics. If browsers cannot represent characters that you used in the program, you may submit a graphical image of the source and/or a sequence of keystrokes that can be used to type it, but still may claim its length based on character count.
Any required whitespace or newline characters are included in the character count. If you want, you may submit both an "official", shortest version that is used to claim the length and a "non-official", human-readable version with additional spaces, newlines, formatting, comments, parentheses, meaningful identifier names, etc.
The implementation may be a complete program/script, a function (along with any helper functions or definitions, if needed), a functional expression (e.g. lambda, anonymous function, code block, several built-in functions combined with a function composition operator, etc) or any similar construct available in your language.
You may use any standard library functions that normally available in your language, but any required import, using, open or other similar constructs or fully qualified names must be included in the source unless your language imports them by default.
The program may not communicate with any Internet services to obtain the result, intermediate data, or to download some parts of the algorithm.
If your language supports some form of compressed expressions (like Uncompress["..."] in Mathematica) you may use them to make the program shorter.
If your language does not support strings or you do not want to use them, you may use character or integer arrays (or other collections) instead. If your language does not support integers (e.g. lambda-calculus), you may use a suitable encoding for them (like Church numerals).
For input and output you may use whatever mechanism you prefer: standard input/output streams, user prompt, console output, function parameters and return value, Turing machine tape, reading/writing memory blocks, etc.
You may assume that an input is well-formed (e.g. that it does not include any characters except ()[]{}<>) and do not need to validate it. The program behavior may be undefined if the input is not well-formed.
The output strings may be printed delimited by commas, semicolons, spaces, newlines or other delimiters normally used in your language, with or without surrounding quotation marks, or returned as an array, list, sequence, a single delimited string or any other suitable collection.
The output strings may be returned in any order, but must not contain duplicates.
The program execution time must be polynomial with respect to the length of its output.

"The program execution time must be polynomial with respect to the length of its output." -- which means that my "try every position x char, then every two positions x chars ..." algorithm is provably too slow :-(

is it even possible in polynomial time?

Jan Dvorak: I don't think so: for < there is only 1 solution, for << there are 2 solutions, for <<< there are 5 solutions, for <<<< there are already 14 solutions. This number increases exponential.

@JohannesKuhn That is why it is required to be polynomial w.r.t output (not input) length.

Tcl, 212 characters.
eval [zlib i [encoding convertt unicode 兕櫭ッﰌꞟ膸줙ꎠ？곚ၻ菇몐䞝Ӫ᷇ꌃ齷靤녂閉璓陷ョ䎅汚组䕿䎢犄ﲕⷑ稑䞙⠧赧용㽫硣ꖠᓋ蘊湏뢈鱰蒺䡎ྚ嬣᪢꼍ⴚ벎艚㶼큔㱅麓傧ᶘ쳖岠ꇻ퇇䯺蛼෪ᾜ❂᠗移ﺶ䱔엻똆诖ꙧꈦ屪蘦㝖ᝎﴝ䏐駺鞜䓲䣎娯෺顡瑼曾⛁⩤暪鬙쩘覥喼\ud88eႂ嬲꫺\udfdf쒚쾟⒆鱔壌杗殰킞茶嵊䴪ꥁ⽠濶켖덼㘕拘⛇끓ᛱ㐼\ud927碀꣟禝悕衫瀇辸幇鬫瞽\udf90䵸㿕]]

You count characters, so I use 1 character for 2 bytes. (Except the invalid characters, that I replaced now)
The zlib is pretty self explanatory. i is just the the abbreviation of inflate.
eval. Well. I don't have to explain that?
After decoding it becomes

proc v i {set ::m {};t $i
set r [list [split $i {}]]
lmap c [split $::m {}] {set c [dict get {\{ \} \} \{ {[} \] \] {[} ( ) ) ( < > > <} $c]
lmap a $r[set r {}] {for {set i 0} \$i<=[llength $a] incr\ i {lappend r [linsert $a $i $c]}}}
lsort -u [lmap a [lmap a $r {join $a {}}] {if {![t $a]} continue set\ a}]
}
proc t i {if {{}ne$i} {lmap r {{^(.*){(.*?)}(.*)$} {^(.*)\((.*?)\)(.*)$} {^(.*)<(.*?)>(.*)$} {^(.*)\[(.*?)\](.*)$}} {if {[regexp $r $i - 1 2 3]} {return [expr {[t $1$3]&[t $2]}]}};append ::m $i} {return 1};list 0}

Which will be passed to eval.
It defines 2 commands: v, the main program, and t which checks the input and place unmatched braces in the global variable m. v calls t with the input, insert the corresponding brace at all possible positions and use t again to filter the valid ones out.
Input: 1. Parameter for v
Output: A Tcl list with each possible valid permutation. They have all the same length.
Example:
% v <<
<<>> <><>

Perhaps you should show the unencoded version with those invalid characters replaced (there's plenty of characters outside the ASCII range if you want to) as well as the encoded version

can you please post the source code as it is after inflation?

@JanDvorak Posted a decoded version. It still requires Tcl 8.6 because I use lmap not only as replacement for foreach.

Thanks. I was kinda hoping I would be able to read your code and extract its algorithm, but still nope :-)

@JanDvorak It's simple: The regexp split the string into 3 parts (on a matching brace). The first and last part together (concat) are tested if it is a balanced, the middle part ist tested too. If no regexp match, then the input only contains unmatched characters, append them to m and return false. I put the proc t ungolfed to idone

@JohannesKuhn Could you comment on "I use 1 character for 2 bytes"? Not every pair of bytes is a valid Unicode character.

@VladimirReshetnikov Yeah, you are correct. Just a few more characters. This also solved my inability to post it.


text:
FIBonacci sequence
For this code golf, you will receive an input of a fibonacci sequence, that is, a normal Fibonacci sequence but with one number incorrect. See, the sequence is fibbing! Get it? :D
Your job is to find out which number is incorrect, and print the index (0-based) of that number.
For example:
Input : 1 1 2 9 5 8 13
Output: 3

Input : 8 13 21 34 55 80
Output: 5

Input : 2 3 5 5 13 21
Output: 3

Specifications:

The sequence may start at any number.
The first two numbers of the input will always be correct.
Shortest code (character count) wins.

Does the input have to be space-delimited or can commas be used as well?

@Volatility Input is space-delimited.

The job is to find only the first such number, right? For example, if you started from the right in the first sequence you could think that 8 is incorrect because it doesn't equal 9+5

@LuisMendo There will always be only one such number.

@Doorknob That depends on which criterion you use. In the first sequence, 9 and 8 are both incorrect, as I see it (9 is not 1+2; and 8 is not 9+5)

@LuisMendo Okay, let me reword that: There will always be exactly one way to change a single number that causes the sequence to be correct.

@Doorknob Oh, I understand now. I think your rephrasing implies that the changed element should always be the first that is wrong (and so my answer is valid)

GolfScript (18 chars)
~]:^,,{^>3<~-+}?2+

The key to keeping this short is ? (find).

+1 for the portrait of Fibonacci ~]:^,

J, 30 23
(2+0 i.~2&}.=[:}:}:+}.)

Golfscript, 31 28 26 25 23
~]-1%~1{)\3$3$-=}do])\;

APL (19)
1+1⍳⍨(1↓1⌽k)≠2+/k←⎕

Explanation:

k←⎕: store user input in k
2+/k: sum each pair of elements in k (i.e. 1 1 2 3 -> 1+1 1+2 2+3 -> 2 3 5)
1↓1⌽k: rotate k to the right by 1 and then drop the first element (i.e. 1 1 2 3 -> 2 3 1)
≠: find the place where these lists are not equal
1⍳⍨: find the location of the first 1 in this list (location of the incorrect number)
1+: add 1 to compensate for the dropped element

K, 32
{2+*&~(n@n@x)=x+(n:{1_x,x 0})@x}

dc, 36 32
?zszsasb[lalbdsa+dsb=x]dsxxlzz-p

dc is a reverse-Polish calculator, so obviously you need to input the numbers in reverse order ;)
$ dc fib.dc <<< "999 13 8 5 3 2 1 1"
7
$ dc fib.dc <<< "999 1 1"
2

JavaScript, 70
for(n=prompt().split(' '),i=n.length;i---2;)if(n[i-2]- -n[i-1]!=n[i])i

Javascript (69 68 61 60 55)
for(s=prompt(i=2).split(' ');s[i]-s[i-1]==s[i-2];i++);i

(60)
s=prompt(i=2).split(' ');for(;s[i]==+s[i-1]+ +s[i++-2];);--i

(61)
s=prompt(i=1).split(' ');for(k=+s[1];k+=+s[i-1],k==s[++i];);i

(68)
s=prompt(i=1).split(' ');for(k=+s[1];k+=+s[i-1],k==s[++i];);alert(i)

(69)
s=prompt(i=1).split(' ');k=+s[1];for(;k+=+s[i-1],k==s[++i];);alert(i)

Awk: 55
{for(i=3;i<=NF;i++)if($i+$(i-1)!=$(i+1)){print i;exit}}

Ruby, 66
My first attempt at an (somewhat) complicated Ruby program:
p gets.split.map(&:to_i).each_cons(3).find_index{|a,b,c|a+b!=c}+2

You can save quite a few characters if you replace gets.split with $* (ARGV) to take input as command line arguments instead of on the standard input stream. The space between p and $* can then also be safely removed.

Python, 74
a=map(int,raw_input().split())
i=2
while a[i-2]+a[i-1]==a[i]:i+=1
print i

I had this solution first, but Doorknob answered the question about the format of input right before I had time to post it:
Python, 66
a,b=input(),input()
i=2
while input()==a+b:a,b=b,a+b;i+=1
print i

Assumes newline separated input.

VB.net (77)
Assuming the numbers are already in a IEnumerable(Of Integer).
 Dim p = xs.Skip(2).TakeWhile(Function(c, i) c = xs.Skip(i).Take(2).Sum).Count + 2

Matlab / Octave, 39 bytes
Thanks to Stewie Griffin for saving a byte! (- instread of ~=)
@(x)find(diff(x(2:end))-x(1:end-2),1)+1

This is an anonymous function that inputs an array and outputs a number.
Try it online!

JS, 52B
for(s=prompt(i=2).split` `;s[i]-s[i-1]==s[i++-2];);i

Kotlin, 77 bytes
{val r=it.split(' ').map{it.toInt()}
var i=2
while(r[i]==r[i-1]+r[i-2])i++
i}

Beautified
{
    val r = it.split(' ').map { it.toInt() }
    var i=2
    while(r[i] == r[i-1] + r[i-2]) i++
    i
}

Test
var f:(String)->Int =
{val r=it.split(' ').map{it.toInt()}
var i=2
while(r[i]==r[i-1]+r[i-2])i++
i}

data class Test(val input: String, val output: Int)

val TESTS = listOf(
        Test("1 1 2 9 5 8 13", 3),
        Test("8 13 21 34 55 80", 5),
        Test("2 3 5 5 13 21", 3)
)
fun main(args: Array<String>) {
    val fails = TESTS
        .asSequence()
        .map { it to f(it.input) }
        .filter { (test, res) -> test.output != res }
        .toList()

    if (fails.isEmpty()) {
        println("Test Passed")
    } else {
        fails.forEach{ println(it)}
    }
}

Raku, 45 bytes
{first :k,?*,(@($/=.words)Z-($0,$1,*+*...*))}

Try it online!
$/ = .words stores the words (numbers) of the input string into the pattern-match variable $/.  Conveniently, the elements of that variable can be accessed with $0, $1, etc, so $0, $1, * + * ... * forms the Fibonacci sequence starting with the first two input numbers.  The input numbers and the Fibonacci sequence are then zipped together using the subtraction operator (Z-), forming a new sequence which is nonzero only at the place where the two series are different.  Then first :k, ?*, ... returns the index (thanks to the :k parameter) of that location; ?* is an anonymous predicate function that coerces its argument to a boolean value.

Python (90)
a=map(int,raw_input().split())
print min(i for i in range(2,len(a))if a[i-2]+a[i-1]!=a[i])

Mathematica 59
Because space-delimited input is required, StringSplit needs to be employed.
The following assumes that the input is in the form of a string i.
s = StringSplit@i;
p = 3; While[s[[p - 1]] + s[[p - 2]] == s[[p]], p++]; p - 1

Haskell, 48
f l=length$fst$span id$zipWith(==)l$1:scanl(+)1l

Jelly, 11 bytes
ÆḞ€i$€In1i1

Try it online!

QBIC, 31 bytes
_!_!{_!~a+b=c|a=b┘b=c┘s=s+1\_Xs

Explanation
_!_!           Ask the user for two umbers, assign them to 'a' and 'b'
{              DO
 _!            Ask for a third number (this will be assigned to 'c' on every iteration)
 ~a+b=c        IF the previous two terms add up to the third
 |a=b          THEN shift b into a,
   ┘b=c            and c into b
   ┘s=s+1          increment s (starts as 3 in QBIC)
 \_Xs          ELSE quit, printing the step counter

I'm not quite sure if this is allowed; the sequence is entered one term at a time, and the program aborts on error, not after entering the entire sequence.

Pxem, 0 bytes (content) + 52 bytes (filename).

Filename (escaped): \002._._X.w.c.t.v.m.v.+._.c.t.v.m.v.-\001.r.x.n.d.a\001.+.vX.a

Usage

From stdin
Must be an actual FIBonacci sequence
Each integer are separated with blank characters

With comments
XX.z
# Initial stack: F(i-1), F(i-2), i
# i is initially 2
.a\002._._XX.z
# while :; do
.aX.wXX.z
  # to: (F(i-1)+F(i-2)), i, F(i-1)
  .a.c.t.v.m.v.+XX.z
  # input is F(i)
  # to: F(i), (F(i-1)+F(i-2)), i, F(i-1), F(i)
  .a._.c.t.v.m.vXX.z
  # to 0, abs(F(i)-F(i-1)-F(i-2)), i, F(i-1), F(i)
  # if (pop!=pop); then
  .a.-\001.r.xXX.z
    # print pop; exit; fi
    .a.n.d.aXX.z
  # to F(i), F(i-1), (i+1)
  .a\001.+.vXX.z
# done
.aX.a

Try it online!

Husk, 5 bytes
δV≠İf

Try it online!
You know it's a good day when you get to use decorV in an answer.


text:
Display Scrolling Waves
The challenge is to display and scroll a sine waveform in the least number of characters.
Restrictions:

Total height of wave must be at least seven units (characters, pixels, etc).
The generated wave must scroll in-place.

Additional Rules/Information:

The sine wave must be distinguishable from triangle and square waves.

"distinguishable" indicates sampling at least every π/8

Additional Judgement Criteria:

Appearance/Quality of the wave
Number of periods displayed

Winning entries will have the fewest characters of code and generate a sine wave with the most samples per period.

Could you expand the specification? As it stands, I'm not sure what you're looking for. I'm also not sure what the scoring system is. See the description of on topic questions.

define "distinguishable". Does it suffice that a triangle wave would produce at least one pixel differently under any rounding mode?

@FKunecke: If you're simply searching for a tool to plot functions: http://martin-thoma.com/html5/polynom-interpolation.htm

Does it have to actually be a sine wave, or does a curve that just looks like a sine wave count as good enough?

APL (46)
{∇⍵+1⊣⎕DL÷9⊣⎕SM∘←↑⍵∘{0,⍵,⍨9+⌈9×1○9÷⍨⍺+⍵}¨⍳79}1

It looks like this, and scrolls to the left:

In action: http://frankenstein.d-n-s.org.uk/~marinus/sine.mp4

 Mathematica : 49
Plot[Sin[x+a],{x,0,9},Axes->None]~Animate~{a,0,2Pi}

The flickering is a GIF-produced artifact. Runs smoothly on the screen.

no flickering here, looks great. perhaps a browser-produced artifact?

Why Axes-> None?  I don't see a restriction against the use of axes.

@DavidCarraher To create the illusion of a continuous scrolling (I don't care too much about winning)

@ardnew Probably a poor man's laptop artifact :)

Golfed version: Animate[#&@@@Sin@x~Plot~{x,a,a+9},{a,∞}] (40 characters). Less then APL :)

Machine code x86 16-bit DOS, 40 bytes
░‼═►h áë←☺‼▀♥▐4┘■▐♀▐♦▀←i;@☺&ê◄■├uσBδ╪

Or in a more human readable format (typical hugi conventions followed) :
;  40 byte version
; 00000000:  0A 00 B0 13 CD 10 68 00-A0 07 89 1B 01 13 DF 03   ......h.........
; 00000010:  DE 34 D9 FE DE 0C DE 04-DF 1B 69 3B 40 01 26 88   .4........i;@.&.
; 00000020:  11 FE C3 75 E5 42 EB D8                           ...u.B..

;  42 byte version
; 00000000:  0A 00 B0 13 CD 10 68 00-A0 07 89 1B 01 13 DF 03   ......h.........
; 00000010:  DE 34 D9 FE DE 0C DE 04-DF 1B 69 3B 40 01 26 88   .4........i;@.&.
; 00000020:  11 FE C3 75 E5 42 E2 FE-EB D6                     ...u.B....

[bits 16]

newscreen:
 or al,[bx+si]  ; trade off vertical height for # of periods
 mov al,13h
 int 10h
 push 0a000h
 pop es

iter:
 mov word [bp+di],bx
 add word [bp+di],dx
 fild word [bp+di]
 fidiv word [si]
 fsin
 fimul word [si]
 fiadd word [si]
 fistp word [bp+di]
 imul di,word [bp+di],320
 mov [es:di+bx],dl
 inc bl
 jnz iter
 inc dx

delay:
 loop delay  ; can remove this to get 40 bytes, but wont look as good since it scrolls too fast

 jmp newscreen

Python 2.7 with Pygame (196 178)
import math,pygame as p
D=p.display
x=0
s=D.set_mode((600,400))
while 1:
 i=0;x+=1;D.flip();s.fill([0]*3)
 while i<600:s.set_at((i,int(200*math.sin((i+x)*.01)+200)),[255]*3);i+=1

Draws in pixels. Went for looks rather than characters.

You could save some (4 I think) characters with import math, pygame as p then use D=p.display.

Ruby, 105 characters
d=0
loop{s=(1..9).map{" "*79}
79.times{|i|s[(Math.sin((i+d)*Math::PI/16)*4+4.5)][i]=?x}
puts"^[[H",s
d+=1}

The ^[ is a single escape character. (You can enter it with Ctrl-V,Esc in the terminal and Vim or Ctrl-Q,Esc in MCEdit and Emacs.)
The animation is displayed from the 2nd line of top left corner of the terminal and scrolls from right to left at full speed (add sleep 0.1; before the last } to slow it down).
Sample run:
bash-4.4$ ruby -e 'd=0;loop{s=(1..9).map{" "*79};79.times{|i|s[(Math.sin((i+d)*Math::PI/16)*4+4.5)][i]=?x};puts"^[[H",s;d+=1}'
                      xxxxx                           xxxxx
                    xx     xx                       xx     xx
                  xx         xx                   xx         xx
                 x             x                 x             x
x               x               x               x               x
 x             x                 x             x                 x
  xx         xx                   xx         xx                   xx         xx
    xx     xx                       xx     xx                       xx     xx
      xxxxx                           xxxxx                           xxxxx

Ruby: 115 characters
d=0
while 1
s=(1..9).map{" "*79}
79.times{|i|s[(Math.sin((i+d)*Math::PI/16)*4+4.5)][i]=?x}
$><<"\e[H"+s*$/
d+=1
end

The animation is displayed in the top left corner of the terminal and scrolls from right to left at full speed (add sleep 0.1; before the end keyword to slow it down).
Sample run:
                      xxxxx                           xxxxx
                    xx     xx                       xx     xx
                  xx         xx                   xx         xx
                 x             x                 x             x
x               x               x               x               x
 x             x                 x             x                 x
  xx         xx                   xx         xx                   xx         xx
    xx     xx                       xx     xx                       xx     xx
      xxxxx                           xxxxx                           xxxxx
bash-4.1$ ruby -e 'd=0;while 1;s=(1..9).map{" "*79};79.times{|i|s[(Math.sin((i+d)*Math::PI/16)*4+4.5)][i]=?x};$><<"\e[H"+s*$/;d+=1;end'

(I know, can be shortened by replacing Math::PI/16 with its precalculated value of arbitrary precision. For example to 107 characters by using 0.2 multiplier. But the lower the precision, the uglier the output. May edit it in the future, I just keep it for now.)

q
Quick and very ugly, 119 characters:
o:0;
w:.:["\\c"]1;
.z.ts:{-1@'{@[w#" ";where x=y;:;"0"]}[4-7h$4*sin o rotate(til w)%2*acos -1]'[til 9];o::o+1};
\t 100

Processing, 99
Really just a butchered version of this.
float i,x,t;void draw(){clear();x=t+=0.02;for(i=0;i<75;ellipse(i++*5,50+sin(x+=0.418879)*25,3,3));}

Try it online!
Could've saved some characters at the cost of an uglier animation. Slightly more readable form:
float i,x,t;

void draw() {
    clear();
    x = t+=0.02;
    for(i=0; i<75; ellipse(i++*5, 50+sin(x+=0.418879)*25, 3, 3));
}

Magic numbers:

0.02 kinda affects the scroll speed
75 is the number of dots
5 is the distance on x-axis
50 is the y-position on screen (default window size is 100).
0.418879 ≈ 2π/75*5
25 is the amplitude
3 is the size of the dots

You could save a few chars by replacing the ellipse with a simpler point call (which takes only two args, not 4, and paints a single pixel), and just drawing more of them.

C (65)
main(int x){for(;;)printf("%*c\n",(int)(22+20*sin(x++/5.)),'x');}

Note: plots sine wave with X axis vertical and therefore scrolls vertically.

Doesn't this violate the “The generated wave must scroll in-place.” rule?

I suppose it depends what you mean by "in-place" - on a basic text terminal, where the text doesn't get saved as it scrolls off the top of the screen, I would argue that it is effectively scrolling in-place.

For clarification: this does not count; if you were to clear the screen and redraw it each time it exceeds the window height it would qualify.

OK - you should probably add this additional constraint to your question. I think that leveraging the terminal's scrolling capability is perfectly reasonable but hey, it's your challenge...

Maple, 42 Characters
This is very easy to do with Maple.
plots[animate](plot,[sin(x+a)],a=0..2*Pi);

What it does

TI-BASIC, 22 bytes

Name this prgmA. It eventually overflows the stack by calling itself, throwing an ERR:MEMORY; this can be rectified in exchange for 4 bytes by adding While 1 to the beginning and replacing the prgmA line with End.
It works pretty much perfectly, although I'm afraid not much can be done to improve its speed.
It's currently the winner by far, but can be 'golfed' to 18 bytes by removing the step argument (,.01) from the For( loop, lowering its "Number of periods displayed" score.

For(A,0,6,.01
ClrDraw
DrawF 7sin(X+A
End
prgmA

For(A,0,E9:ClrDraw:DrawF sin(X+sub(A:End, because only seven pixels are required, not seven graph screen units. You also assumed a window that fits the graph.

I counted 24 bytes, by the way.

@ThomasKwa what do you mean by sub(A?

@Wright Try it!

@ThomasKwa What the hell?! That's amazing, how did you find it?

I didn't find it, Weregoose did at least four years ago, and by trial and error, or something.

Interesting. (KermM said that it was "one of [their] OS disassemblers," although I wouldn't be surprised if it was Weregoose) I wonder if there are any other tricks like this (for instance, using a complex list as Circle()'s fourth argument makes it use a 'fast circle' routine) that we don't know of.

Let us continue this discussion in chat.

JavaScript: 265 characters + 59 HTML
<canvas id=c width=99 height=99></canvas>
<script>
var c=document.getElementById("c");var context=c.getContext("2d");context.beginPath();var s=0;setInterval(function(){c.width=c.width;s++;context.moveTo(0+50,50*Math.sin(s+0)+50);for(var e=1;e<99;e++){context.lineTo(e+50,50*Math.sin(s+50*e)+50)}context.stroke()},50)
</script>

JavaScript (ungolfed)
<canvas id="canvas" width="500" height="99"></canvas>
<script>
var c = document.getElementById("canvas");
var context = c.getContext("2d");
context.beginPath();
var s=0;
setInterval(function(){
    c.width = c.width;
    s++;
    context.moveTo(0+50,50*Math.sin(s+0)+50);
    for(var x=1;x<99;x++){
        context.lineTo(x+50, 50*Math.sin(s+50*x)+50);
    }
    context.stroke();
}, 50);
</script>

See it on http://jsfiddle.net/MartinThoma/uv5Xx/

Cool! But as there is an additional “Appearance/Quality of the wave” criteria, I would change the stepping from s++ to s+=.1. Looks much better that way. Regaring the code size, these 182 characters works for me in Firefox: c=document.getElementById("canvas");d=c.getContext("2d");d.beginPath(s=0);l=50;setInterval(function(){c.width=500;s+=.1;for(x=99;x--;)d.lineTo(x+l,l*Math.sin(s+l*x)+l);d.stroke()},l).

I get Unexpected token ILLEGAL in Chrome and SyntaxError: illegal character in Firefox from your code.

Indeed. No idea what happened during copy-pasting it. See here, 174 characters: http://jsfiddle.net/uv5Xx/3/

Processing, 115 chars
This one actually draws a pseudo-sine wave, not an actual sine wave:
int t,i,c;void draw(){clear();beginShape();for(i=-1,c=50;i<6;c=-c)curveVertex(50*i++-t,50+c);endShape();t=t%100+1;}

A more readable version:
int t, i, c;
void draw() {
  clear();
  beginShape();
  for(i=-1, c=50; i<6; c=-c)
    curveVertex(50*i++ - t, 50+c);
  endShape();
  t = t%100 + 1;
}

Mathematica, 38 bytes
Animate[Plot[Sin[x+a],{x,0,10}],{a,5}]

Non-competeting, uses Mathematica 10

Oh, I'm sorry, I just saw how old the challenge is... I will edit my post

SmileBASIC
The rules aren't entirely clear, so I'll post a few different answers:
34 bytes (vertical text):
LOCATE SIN(MILLISEC/9)*9+9,?.EXEC.

(It never specifically says this isn't allowed, but none of the other answers are vertical, so I'm not sure)
43 bytes (horizontal text):
LOCATE,SIN(MILLISEC/9)*9+9?0SCROLL-1,.EXEC.

53 bytes (horizontal graphics):
GPSET 1,SIN(MILLISEC/9)*9+9GCOPY.,0,#R,30,1,0,1
EXEC.


text:
Printing all numbers from N to M in one single expression
Given the integers N and M, can you print all numbers from N to M comma-seperated? The hitch is to use one single expression.
The output for N=23 and M=42 should look like this:
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42

I'll start with Ruby:
puts (23..42).to_a.join(', ')

related: http://codegolf.stackexchange.com/questions/8588/return-each-number-from-a-group-of-numbers/

@ardnew The special catch of my task is that the solution has to be achieved using only one expression, which is way harder and probably not possible in every language. I don't consider your link as related.

@YMMD what do you consider a single expression in golfscript?

I thought of a nested expression which still could be a code gold issue, but indeed I get your point. I deleted the code-golf-tag.

so now that the code golf tag has been removed, is there even an objective or winning criteria anymore?

Quite poorly worded task. As you can see the answers, there are too many variations: n..m vs 23..42, “,” vs “, ”, quoted vs unquoted output, maybe with or without trailing separator. I know, it is not [tag:code-golf] anymore, but I think the answer still should be somehow comparable.

@manatwork, that's the least of its problems. The biggest problem is that, as Jan pointed out, "expression" is not well defined.

@JanDvorak Single expression in golfscript? "#{(23..42).to_a.join(', ')}" ;-)

k
17 chars. Expression returns 1 but prints output to stdout
1@", "/:$23_!1+42

To return a string with the comma seperated values, simply use:
", "/:$23_!1+42

Sage CLI, 14
Edit: Sage has a range shorthand.
`[n..m]`[1:-1]

Tcl, 63 bytes
puts "$n,[join [lmap a [lrepeat [expr {$m-$n}] 0] {incr n}] ,]"

My answer has the problem of putting new lines: while {$n<$m} {puts $n,;incr n};puts $m

Fixed: while {$n<$m} {lappend l $n,;incr n};lappend l $m;puts $l

OK I forgot there is the requirement of 1 single expression; my answers are not acceptable!

Bash, 21 bytes
echo {23..42}|tr \  ,

what about seq -s, 23 42

@marcosm seq is distribution specific and not available everywhere.

Ruby: 18 characters
$><<[*23..42]*", "

Sample run:
bash-4.1$ ruby -e '$><<[*23..42]*", "'
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42

Forcing the rules: 10 characters
As seen in the other answers:

variables instead of numeric literals
comma only instead of comma and space
no output, just generated value

[*n..m]*?,

Sample run:
irb(main):001:0> n=23
=> 23

irb(main):002:0> m=42
=> 42

irb(main):003:0> [*n..m]*?,
=> "23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42"

Python: 39
print(",".join(map(str,range(23,42))))

J, 28 characters
echo(,', ',])&":/[23}.i.>:42

i.43 creates an array of 43 values 0..42. Unfortunately, we have to compute 43.
23}. drops first 23 of them, leaving 23..42. If precomputation is allowed, 23+i.20 fares better byte-wise (-3 characters)
,', ',] concatenates both arguments with ', ' between them
...&": does that after converting both arguments to strings
.../ does that as a reduction step.
echo is a built-in to perform standard output. If simply returning is enough, you can drop this (-4 characters)

R: 17 characters
cat(n:m,sep=", ")

Example:
> n=23
> m=42
> cat(n:m,sep=", ")
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42