text:
Arranging Fenceposts
If you want to build a fence and have different length boards available, there are many different ways to set up your posts. So, given a minimum and maximum board length, a number of boards, and the total length, count how many ways you can arrange them.
Input
Input is four positive integers:

min: The smallest board usable. Will be >0.
max: The largest board available. Will be >min.
count: Number of boards to use. Will be >0.
length: Total length of the fence. For a valid fence, this should be >=min*count and <=max*count

Individual boards can be any integer length between min and max (inclusive).
Output
Output a single number representing the number of ways you can arrange the fence.
Examples
For input (in order listed above) 2 3 4 10, you can arrange the boards six ways:
2233
2323
2332
3223
3232
3322

So the output is 6. If your input was 1 3 4 6, the output is 10, since there are ten ways to do it:
1113   1212
1131   1221
1311   2112
3111   2121
1122   2211

Input          Output
5 10 6 45      4332
1 100 6 302    1204782674
27 53 8 315    4899086560
1 10 11 70     2570003777
1 6 15 47      20114111295
4 8 150 600    1              // all boards length 4
1 10 100 80    0              // invalid, you can't put 100 boards in 80 length

Of course, there's a naive method to do this:
long f(int min, int max, int count, int length){
    if(count==1)
        return 1;
    long num = 0;
    for(int i=min;i<=max;i++){
        int goal = length - i;
        if(goal <= max*(count-1) && goal >= min*(count-1)){
            num += f(min,max,count-1,goal);
        }
    }
    return num;
}

Rules
The algorithm given above works fine for small inputs, but it can easily overflow the long with larger inputs. Even with arbitrary-length numbers, it's incredibly inefficient. I believe it's O((max-min+1)^count).
To be considered valid for this challenge, you should be able to compute input 1 10 100 700 in under one hour on my i7. Given a more efficient algorithm than the one above, this should not be a problem. I will test any entries I believe may come close to the limit. If your algorithm takes more than a few minutes to run, you should use a freely available language (on linux) to facilitate testing.
Code may take the form of a complete program or function, with input/output as any of the standard methods. Shortest code in bytes wins.

Ruby: 106 98 93 bytes
Update: Changed cache key type from strings to arrays. (-5)
Update:  Storing the initial condition in the cache payed out quite well. (-8)
However, it increases the runtime for the test case to roughly 2 seconds.
I simply use memoization. I guess it can be further golfed as my Ruby skills are far from perfect.
@m={[0,0]=>1}
def f(l,u,c,s)
  @m[[c,s]]||=s<0?0:(l..u).map{|x|f(l,u,c-1,s-x)}.reduce(:+)
end

Note that it runs for only one test case at a time, since I don't cache the min and max values (l and u, respectively). Here is my output for 1 10 100 700:
121130639107583774681451741625922964085713989291260198434849317132762403014516376282321342995

real    0m0.316s
user    0m0.312s
sys     0m0.004s

Yes, that's the correct output.

APL (Dyalog Unicode), 55 bytes
⎕CY'dfns'
{0::0⋄⍺⊃⍵{+big⌿↑(⍳1+¯1⊥⍺)⌽¨⊂0,⍣(⊢/⍺)⊢⍵}⍣⍺⍺⊢1}

Try it online! (without big, so fast but inaccurate)
The time complexity of the algorithm is \$O(m(m-n)c^2)\$, where \$m\$ and \$n\$ are max and min, and \$c\$ is the count, ignoring the cost of bigint addition (which is not a language built-in, and therefore horribly inefficient). It is nowhere close to the fastest, but it's still much faster than brute-force, as it returns the correct result for 1 10 100 700 in 3 minutes on my PC.
To use, assign the inline operator to f and call it in the form of length (count f) min max.
⎕CY'dfns'  ⍝ Load dfns library, so we can use `+big`

{0::0⋄...}  ⍝ If any error occurs, return 0
⍺⊃⍵{...}⍣⍺⍺⊢1  ⍝ Build the vector of all possible combinations by
               ⍝ taking the polynomial represented by ⍵ raised to the power of ⍺⍺,
               ⍝ then fetch the ⍺-th coefficient (might error if ⍺ is out of range)
0,⍣(⊢/⍺)⊢⍵    ⍝ Prepend "max" copies of 0s to the current polynomial
(⍳1+¯1⊥⍺)⌽¨⊂  ⍝ Generate the list of ^ rotated 0..(max-min) times
+big⌿↑        ⍝ Promote to matrix and sum the numbers vertically

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

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


text:
Generate Recamán's sequence
Recamán's sequence (A005132) is a mathematical sequence, defined as such:
A(0) = 0
A(n) = A(n-1) - n if A(n-1) - n > 0 and is new, else
A(n) = A(n-1) + n

A pretty LaTex version of the above (might be more readable):
$$A(n) = \begin{cases}0 & \textrm{if } n = 0 \\
A(n-1) - n & \textrm{if } A(n-1) - n \textrm{ is positive and not already in the sequence} \\
% Seems more readable than
%A(n-1) - n & \textrm{if } A(n-1) > n \wedge \not\exists m < n: A(m) = A(n-1)-n \\
A(n-1) + n & \textrm{otherwise}
\end{cases}$$
The first few terms are 0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11
To clarify, is new means whether the number is already in the sequence.
Given an integer n, via function argument or STDIN, return the first n terms of the Recamán sequence.

This is a code-golf challenge, so shortest code wins.

What does 'is new' mean?

If a number is new, it means it is not yet in the sequence. Just realized I have typed out the sequence wrong, give me a min to correct it.

Corrected the sequence.

Can you add the first values of the sequence?

Added the first few numbers! (And a link to its OEIS page)

CJam, 34 33 bytes
0ali{_W=_I-__0<4$@#)|@I+@?+}fI1>`

Try it online.
Example run
$ cjam <(echo '0ali{_W=_I-__0<4$@#)|@I+@?+}fI1>`') <<< 33
[0 1 3 6 2 7 13 20 12 21 11 22 10 23 9 24 8 25 43 62 42 63 41 18 42 17 43 16 44 15 45 14 46]

How it works
0ali                               " Push S := [ 0 ] and read an integer N from STDIN.    ";
    {                      }fI     " For each I in [ 0 ... (N - 1) ]:                     ";
     _W=                           "   X := S[-1].                                        ";
        _I-                        "   Y := X - I                                         ";
            _0<                    "   A := (Y < 0)                                       ";
           _   4$@#)               "   B := (Y ∊ S)                                       ";
                     @I+           "   Z := X + I                                         ";
                    |   @?         "   C := (A || B) ? Z : Y                              ";
                          +        "   S += [C]                                           ";
                              1>`  " Push str(S[1:]).                                     ";

What change did you make?

My first approach prepended negative numbers to the sequence, so I didn't have to explicitly check if A(i) - i > 0. However, I didn't prepend enough numbers for small values of n. Now, I just do exactly what the spec says.

33 vs. 45. So close and yet so far. :)

Wow, comment without e# in Cjam... tasty cherry.

Hexagony, 212 bytes
?\..$@.=.'">'_<>}/..&\_.._!\.\].\"&"&=(<_...>\[.+.<_$|_...{.|.....}'.../<..|&.....'/..".>$/{.<\.\$\>\._?...><?$$.\[._\_}$&..~.|"$\./..{&_$....$'.|_...$}|_.-..;_....'}".'...2.....$?&....3..=.<_.....?.-+{......}\</$.}

Try it online!
Input: a single, positive integer \$n\$ on stdin.
Output: all terms of Recaman's sequence up to and including \$A(n)\$, separated by spaces (note that this means the program will print a total of \$n + 1\$ terms).
Expanded

Explanation
Apologies if this is confusing, but it's my first time with Hexagony, so rest assured that it confuses me too.
Let \$n = 6\$.
The instruction pointer (IP) starts out in the NW corner, moving along the black path.
? reads \$n\$ from stdin and stores it in the current memory edge.
Next, we copy \$n\$ three times while backing up the memory pointer.
We also flip the memory pointer and decrement the edge it points to.
"&"&"&=(

The IP eventually wraps around to the upper left corner again, jumping over \ and looping through the rest of the black path.
This loop continues until the current edge is 0, at which point the graph looks like so:

This forms the skeleton of our memory layout.
Each vertical edge now stores a value \$i\$ from 0 to 6; later, these same edges will store the terms \$A(i)\$ of the sequence as they are computed.
Each vertical edge also has 4 contiguous edges that are used for later computations.  Let's explain them now:

head is used for several purposes, but never to store anything permanently because it is frequently overwritten by other operations.
tail is generally used as a temporary variable, but it remains 0 for the last \$i\$ in the sequence, telling the program when to stop.
prev stores the value of \$A(i - 1)\$
copy straightforwardly stores a copy of \$i\$ or, later, \$A(i)\$

Once the program is done initializing its memory graph, it branches off the black path and onto the red path near the NE corner.
First, ! prints the decimal representation of vertical to stdout.
Next, we move the memory pointer to tail and test for zero:
'<

If it is zero, @ terminates the program immediately; otherwise, we move to head and set it to 32 (an ASCII space):
}=}?32

; then prints this space to stdout.
Finally, we copy vertical to the next prev:
"?&"&

Now that the memory pointer is on the next term, we copy this term's vertical to its copy before moving to its vertical:
'&{=

- computes prev - copy, which is really \$A(i - 1) - i\$, and stores it in vertical:

If vertical is not positive, < deflects the IP onto the green path, where + instead computes prev + copy (\$A(i - 1) + i\$) and stores it in vertical:

The IP then wraps around to the SW corner, eventually returning to the beginning of the red path and starting the cycle over again.
However, if vertical is positive, we have to make sure it doesn't already exist in the sequence before printing it.
In this case, the < in the SE corner branches to the SE, wrapping around and staying on the red path.
First, we copy vertical to head:
"?&

This puts the memory pointer in a position so that successive loops can enter at the next | mirror.
Next, we copy head to the previous term's tail and move to its head.
"?&'

- computes vertical - tail (\$A(i - 1) - A(i)\$) and stores it in head.
Hexagony treats zero as a negative number, so we have to do some convoluted branching to test if head is exactly zero.
All that's necessary to know is that if head is zero, we've found a duplicate term, and the program will branch onto the yellow path.
Otherwise, it will return to the red path at the { instruction.
If head is zero, we return to the latest term of the sequence with [, which executes the subroutine along the pink and blue paths, before + computes \$A(i - 1) + i\$) like above.
We then return to the red path.
If head is not zero, we check if the current term is zero:
{<

If it is, we call the subroutine and go back to the red path through a convoluted series of mirrors.
If it isn't, we move to compare the next term, returning to the aforementioned | mirror.

Images created using Timwi's Hexagony Colorer and Esoteric IDE.

For what its worth, your image with colored paths seems to show  that the curly bracket at the end doesn't do anything, you should be able to remove it and the preceding space for an easy -2.

thanks, just nice

Ruby, 71 70 bytes
f=->n{a=[0];(n-1).times{|i|a+=[[b=a[-1]-i-1]-a!=[]&&b>0?b:b+2*i+2]};a}

A very "word-for-word" implementation of the definition.

Haskell, 74
l=0:0#1
a§v|a<0||a`elem`r v=v|1<2=0-v
a#b=a+(a-b)§b:l!!b#(b+1)
r=(`take`l)

Example usage:
λ> r 20
[0,1,3,6,2,7,13,20,12,21,11,22,10,23,9,24,8,25,43,62]

Python 2, 78 75 73 69 Bytes
Kudos to xnor and flornquake
Now almost 10 bytes shorter than the initial answer
m=p,=0,
exec"p+=1;k=m[-1]-p;m+=k+2*p*(k*(k>0)in m),;"*input()
print m

You can shorten [k,k+2*p][bool] to
k+2*p*(bool).

Also, k in m or k<0 can be k*(k>=0)in m since if k<0, the product is 0, which is in m.

You can write -1 instead of p-1.  Edit: You can also make m a tuple and write m=0, and m+=k+2*p*(k*(k>0)in m),.

You can then change the first line to m=p,=0, and increment p at the start of the loop to save another character.

@flornquake Thank you. I did not know that [-1] returns the last element. I learned something today.

"m+=k+2p(k*(k>0)in m" < that is very interesting trick!

Golfscript (41 45)
Try it online here:
(,1,\{:~1$=~)-:^1<\.^?)!!@|^\{~)2*+}*+}/

Explanation
This is for the original 45 bytes solution, but it's still pretty much the same:
(,              # push array [0 .. n-1]
[0]\            # push sequence elements as [0] and reverse stack
{               # foreach element in [0 .. n-1] do:
  :m;           # store current element in m and discard
  .m=           # get the previous sequence element
  m)-:^         # subtract the current index from it and store in ^
  0>            # is that number greater than 0?
  \.^?)!        # is that number new to our sequence?
  @&            # logically and both checks
  {^}           # if true, push ^
  {^m)2*+}      # otherwise, add the index twice and push
  if
  +             # add new element to our sequence
}/
`               # make output pretty

Edit #1: Thanks to Dennis for shaving off 4 bytes.

dc, 46 bytes
sn[z+z+d0r:a]sF0[pz-d1>Fd;a0<Fddd:azln!<M]dsMx

Try it online!
This program takes input from an otherwise empty stack and outputs to stdout (newline delimited).
I'm really proud of this one - it's beating everything that isn't a dedicated golfing language, and showcases three of my favorite dc golfing tricks:

Stack size used as an index variable
Refactoring "if A then B else C" into "unconditionally C, and if A then D" where C and D combine to make B
the little-used random access array feature to solve a uniqueness constraint

Explanation
sn             Stores the input in register n
[z+z+0r:a]sF   Defines the macro F, which:
    z+z+         adds twice the stack size/index variable
    0r:a         resets the "uniqueness" flag to 0 in the array a
               In context, F is the "D" in my description above,
               changing A(z-1)-z to A(z-1)+z
0              The main loop starts with the previous sequence member on top of
               the stack and total stack depth equal to the next index.
               Pushing a zero accomplishes both of these things.
[              Start of the main loop M
  p               Print the previous sequence member, with newline (no pop)
  z-             Calculate A(z-1)-z
  d1>F           If that's nonpositive, (F)ix it to be A(z-1)+z
  d;a            a is my array of flags to see if we've hit this value before
  0<F            If we have, (F)ix it! (nonzero = flag, since ;a is zero by
                 default, and also zero if we just (F)ixed and therefore
                 don't care about uniqueness right now)
  ddd            Make one copy to keep and two to eat
  :a             Flag this entry as "used" in the uniqueness array a
  zln!<M         If our "index variable" is n or less, repeat!
]dsMx          End of main loop - store it and execute

that's wild, i had no idea dc even existed

really very nice. thanks.

JavaScript -  81 80 79 70
Kudos to edc65 for helping me save 9 bytes
f=n=>{for(a=[x=i=0];++i<n;)a[i]=x+=x>i&a.indexOf(x-i)<0?-i:i;return a}

-9 :g=n=>{for(a=[x=i=0];++i<n;)a[i]=x+=x>i&a.indexOf(x-i)<0?-i:i;return a}

@edc65 Grazie mille :)

JavaScript, ES6, 74 69 characters
Run the below code in latest Firefox's Web Console.
G=n=>(i=>{for(r=[t=0];++i<n;)r[i]=t+=i>t|~r.indexOf(t-i)?i:-i})(0)||r

Will try to golf it more later.
Example usage:
G(11) -> 0,1,3,6,2,7,13,20,12,21,11

MATLAB, 83 78 Bytes
Save the below as f.m (73 Bytes)
A=0;for i=1:n-1 b=A(i)-i;A(i+1)=b+2*i;if b>0&&~any(A==b) A(i+1)=b;end;end

Run from command window (5 bytes)
n=9;f

If the above is not legal, then it requires 90 bytes.
function A=f(n)
A=0;for i=1:n-1 b=A(i)-i;A(i+1)=b+2*i;if b>0&&~any(A==b) A(i+1)=b;end;end

R: 96 characters
Golfed:
A=function(s,n,m,i){if(m==n){return(s)}else{t=i-m;if(t%in%s||t<0){t=i+m};s=c(s,t);A(s,n,m+1,t)}}

Ungolfed:
A = function(s,n,m,i) {
    if(m==n){return(s)}
    else{
        t=i-m
        if(t%in%s||t<0){t=i+m}
        s=c(s,t)
        A(s,n,m+1,t)
    }
}

Sample Run:
> An(0,34,1)
[1]   0   1   3   6   2   7  13  20  12  21  11  22  10  23   9  24   8
[18]  25  43  62  42  63  41  18  42  17  43  16  44  15  45  14  46  79

JavaScript, 63 bytes
n=>(g=y=>n-x?g(a[++x]=a.includes(z=y-x)|z<0?+y+x:z):a)(a=[x=0])

Try it online

05AB1E, 19 bytes
¾ˆG¯¤N-DŠD0›*åN·*+ˆ

Try it online!
Explanation
¾ˆ                    # Initialize the global list with 0
  G                   # for N in [1, input-1] do:
   ¯                  # push the global list
    ¤N-               # subtract N from the last item in the list
       D              # duplicate
        Š             # move the copy down 2 spots on the stack
         D            # duplicate again
          0›          # check if it is positive
            *         # multiply, turning negative results to zero
             å        # is the result already present in the list?
              N·*     # multiply by N*2
                 +    # add to the result
                  ˆ   # add this to the list

Perl 6, 62 57 bytes
{(0,{$-@+@*2*($!>@||$-@∈@)given @[*-1]}...*)[^$]}
{(0,{($!=@_[*-1])+@_-@_*2*($!>@_&&$!-@_∉@_)}...*)[^$_]}

-5 bytes thanks to Jo King
Try it online!

that's amazing... that literally looks like my cat walked across my keyboard.

K (oK), 53 bytes
Solution:
{$[y>c:#x;o[x,(r;*|x+c)(r in x)|0>r:*|x-c;y];x]}[,0;]

Try it online!
Explanation:
Recursive solution.
{$[y>c:#x;o[x,(r;*|x+c)(r in x)|0>r:*|x-c;y];x]}[,0;] / the solution
{                                              }[,0;] / lambda with first arg set as list containing 0
 $[      ;                                  ; ]       / if[condition;true;false]
       #x                                             / length of x
     c:                                               / save as c
   y>                                                 / y greater than? (ie have we produced enough results?)
                                             x        / return x if we are done
          o[                             ;y]          / recurse with new x and existing y
                                      x-c             / subtract c from x
                                    *|                / reverse first, aka last
                                  r:                  / save result as r
                                0>                    / 0 greater than?
                               |                      / or
                       (      )                       / do together
                        r in x                        / r in x?
              ( ;     )                               / use result to index into this 2-item list
                   x+c                                / add c to x
                 *|                                   / reverse first, aka last
               r                                      / result
            x,                                        / append to x

J, 36 bytes
(,][`(+2*#)@.(e.+.0>[)~{:-#)^:(]`0:)

Try it online!

Python 2, 65 bytes
n=a=0
v=[]
exec'a+=[n,-n][a+n in v];print a;n-=1;v+=a,n;'*input()

Try it online!
Avoids negative numbers by adding them to the list of already visited numbers.

Clojure : 174 chars
Golfed:
(defn f[m a](let[n(count a)b(last a)x(- b n)y(if(and(> x 0)(not(.contains a x)))x(+ b n))](if(= m n)a(f m(conj a y)))))(println(f(read-string(first *command-line-args*))[0]))

Ungolfed:
(defn f[m a]
  (let [n (count a)
        b (last a)
        x (- b n)
        y (if (and (> x 0) (not (.contains a x))) x (+ b n)) ]
    (if (= m n) a (f m (conj a y))) ) )

(println (f (read-string (first *command-line-args*)) [0]) )

Sample run:
bash$ java -jar clojure-1.6.0.jar rec.clj 14
[0 1 3 6 2 7 13 20 12 21 11 22 10 23]

I suggest you not to read from STDIN but instead just take an integer argument to the function :) Also you don't get any benefits from defining y on the let form, you can use the expression directly where the value is needed.

Java, 144
int[]f(int n){int[]a=new int[n];a[0]=0;int i,j,k,m;for(i=0;i<n-1;){k=a[i++]-i;m=0;for(j=0;j<i;)if(k==a[j++])m=1;a[i]=m<1&k>0?k:k+2*i;}return a;}

Lua - 141 135 139 135
function s(n)a,b={1},{[0]=0}for i=1,n do k=b[i-1]-i c=k+i+i if(k>0)and(a[k]==nil)then b[i],a[k]=k,1 else b[i],a[c]=c,1 end end return b end

readable version:
function s(n)
a,b={1},{[0]=0}
for i=1,n do
   k=b[i-1]-i
   c=k+i+i
   if (k>0) and (a[k]==nil) then
      b[i],a[k]=k,1
   else
      b[i],a[c]=c,1
   end
end
return b
end

I use 2 tables, the first one is called a and it is built so that a[i]=1 iff i has already appeared in the sequence, nil otherwise, while the second table actually holds the sequence

Your sequence should start with 0, though

You're right, I didn't look at the question very carefully and assumed it had the same definition at mathworld (starting with 1), I think that won't cost any more character, I'll test and correct it later, I'm writing from my phone now!

Powershell (103)
$n=Read-Host;$a=@(0);$n-=1;1..$n|%{$x=$a[-1]-$_;if($x-gt0-and!($a-like$x)){$a+=$x}else{$a+=$x+2*$_}};$a

Another 'word-for-word' implementation down here as well. Surprisingly readable for PowerShell, too.
Sequence is stored in the array $a, and printed out one term per line.
For $n=20 if we run the statement $a-join"," we get
0,1,3,6,2,7,13,20,12,21,11,22,10,23,9,24,8,25,43,62

Python, 73
def f(x,t=0):
 if x:t=f(x-1);t+=2*x*(t*(t>0)in map(f,range(x)))
 return t

Edit 1: Thanks to @xnor's tips on the other Python answer!
(I just realised that both look very similar.)
Edit 2: Thanks again, @xnor.

This gives an infinite loop. You need some sort of control flow so that f(x) doesn't always immediately call f(x-1).

@xnor fixed the code.

This seems to return the nth term, not the first n terms.

Some minor saves: t=0 can go as an optional parameter to f, and t=t+ can be t+=.

Groovy : 122 118 111 chars
Golfed:
m=args[0] as int
a=[0]
(1..m-1).each{n->b=a[n-1];x=b-n;(x>0&!(x in a))?a[n]=x:(a[n]=b+n)}
a.each{print "$it "}

Ungolfed:
m = args[0] as int
a = [0]
(1..m-1).each { n->
    b = a[n-1]
    x = b-n
    ( x>0 & !(x in a) ) ? a[n] = x : (a[n] = b+n)
}
a.each{print "$it "}

Sample Run:
bash$ groovy Rec.groovy 14
0 1 3 6 2 7 13 20 12 21 11 22 10 23

Mathcad, 54 "bytes"

From user perspective, Mathcad is effectively a 2D whiteboard, with expressions evaluated from left-to-right,top-to-bottom. Mathcad does not support a conventional "text" input, but instead makes use of a combination of text and special keys / toolbar / menu items to insert an expression, text, plot or component. For example, type ":" to enter the definition operator (shown on screen as ":=") or "ctl-shft-#" to enter the for loop operator (inclusive of placeholders for the iteration variable, iteration values and one body expression). What you see in the image above is exactly what appears on the user interface and as "typed" in.
For golfing purposes, the "byte" count is the equivalent number of keyboard operations required to enter an expression.

That's all well and good, but what are the actual keystrokes?

C (gcc), 116 111 109 bytes
*f(n){int*a=calloc(4,n),i=0,j,k,m;for(;~i+n;a[i]=k+(m|k<1)*2*i)for(k=a[i++]-i,m=0,j=i;j--;)m=k-a[j]?m:1;n=a;}

Try it online!

PHP, 89 bytes
$f=function($n){for(;$i<$n;$s[$r[$i++]=$p=$m]=1)if($s[$m=$p-$i]|0>$m)$m=$p+$i;return$r;};

Try it online!
Ungolfed:
$f = function ($n) {
    for (; $i < $n; $s[$r[$i++] = $p = $m] = 1) {
        if ($s[$m = $p - $i] | 0 > $m) {
            $m = $p + $i;
        }
    }

    return $r;
};

$r for my result
$s for tracking seens
$p previous value
$m mext value

Stax, 19 bytes
É╖C8½ΔL▄░▬L+≡ΩSa⌂¼╧

Run and debug it
Unpacked, ungolfed, and commented, it looks like this.  It keeps the sequence so far on the stack, and remembers A(n - 1) in the X register.  The iteration index is used for n.  The first time through, it's 0, but in that iteration it generates the 0 without any special cases, so there's no need to adjust for the off-by-1 index.
0X      push 0 to main stack and store it in X register, which will store A(n - 1)
z       push an empty array that will be used to store the sequence
,D      pop input from input stack, execute the rest of the program that many times
  xi-Y  push (x-register - iteration-index) and store it in the Y register
        this is (A(n - 1) - n)
  0>    test if (A(n - 1) - n) is greater than 0 (a)
  ny#   count number of times (A(n - 1) - n) occurs in the sequence so far (b)
  >     test if (a) > (b)
    y   (A(n - 1) - n)
    xi+ A(n - 1) + n
  ?     if/else;  choose between the two values based on the condition
  X     store the result in the X register
  Q     print without popping
  +     append to sequence array

Run and debug this one

Pyth, 31 bytes
VQ=+Y?Y?|>NeYhxY-eYN+eYN-eYNZ)Y

Welcome to the site!

Welcome. Code-only answers are discouraged because they tend to be automatically flagged as low-quality. Add an explanation, and consider adding a link to an online interpreter, like this: https://tio.run/##K6gsyfj/PyzQVjvSPtK@xs4vNTKjIlI3NdJPG4hBdJRm5P//hoYA

Ruby, 56 52 bytes
-2 bytes thanks to Jo King!
-2 bytes thanks to dingledooper!
->n{v,*d=0;n.times{|i|d<<v+=v<i||d!=d-[v-i]?i:-i};d}

Try it online!
Commented:
->n{ ... }                         # lambda function taking an integer
  v,*d=0                           # initialize list of sequence values d and previous value v
  n.times{|i| ... }                # run the following code for i = 0,1,...,n-1:
          v<i||d!=d-[v-i]?i:-i     #   i IF (v < i OR d != (d without v-i)) ELSE -i
       v+=                         #   add this to v
    d<<                            #   and append the new value of v to d
  d                                # return d

x86 machine code, 29 bytes
00000034: 89 fe 31 c0 99 eb 11 29 d0 78 0a 60 89 f7 89 d1  ..1....).x.`....
00000044: f2 af 61 75 03 8d 04 50 ab 42 e2 eb c3           ..au...P.B...

Commented assembly:
        .intel_syntax noprefix
        .globl recaman
        // input: ECX: n, EDI: u32[n]
        // output: stored to EDI
recaman:
        // Save the array pointer to ESI
        mov     esi, edi
        // EAX (A(n)) = 0
        xor     eax, eax
        // EDX (n) = 0
        cdq
        // Store first word
        jmp     .Lstore
.Lloop:
        // A(n - 1) - n
        sub     eax, edx
        // if negative, do A(n - 1) + n
        js      .Lneg_or_dup
.Lnot_neg_or_dup:
        // We need to save both EDI and ECX, so we do a lazy PUSHA/POPA.
        pusha
        // EDI = start of array
        mov     edi, esi
        // ECX = current output length
        mov     ecx, edx
        // Search for A(n - 1) - n
        repnz   scasd
        // restore registers
        popa
        // If the zero flag is set, we found a match.
        // If not, go directly to store
        jnz     .Lstore
.Lneg_or_dup:
        // Convert A(n - 1) - n to A(n - 1) + n by adding n * 2
        // EAX = EAX + EDX * 2
        lea     eax, [eax + 2 * edx]
.Lstore:
        // Store a u32 to EDI and autoincrement
        stosd
        // Increment length
        inc     edx
        // Decrement counter and loop if non zero
        loop    .Lloop
        // Return
        ret

Try it online!
The input is a pointer to an int32_t array of n elements in edi, with n being in ecx.
The output will be stored into edi.

C#: 140 characters
int i,w,t,y;int[]F(int n){var r=new int[n--];for(;i<n;y=0){w=r[i++]-i;for(t=0;y<i&&t<1;)t=w==r[y++]?1:0;r[i]=w>0&&t<1?w:r[i-1]+i;}return r;}

C++: 180 characters (158 without cin and cout statements)
int a[5000000][2]={0},i,k,l;a[0][0]=0;a[0][1]=1;cin>>k;for(i=1;i<=k;i++){l=a[i-1][0];if(l-i>0&&a[l-i][1]!=1){ a[i][0]=l-i;a[l-i][1]=1;}else{ a[i][0]=l+i;a[l+i][1]=1;}cout<<a[i][0]<<endl;

Welcome to Programming Puzzles & Code Golf Stack Exchange! Please edit the character/byte count of your solution into your header, as shown in the other answers here. Also, please golf your code (ex. remove whitespace to reduce the character count) as much as possible. Thanks!

Sure thing, I'll do that.

Mathematica - 81 bytes
Fold[#~Append~(#[[-1]]+If[#[[-1]]>#2&&FreeQ[#,#[[-1]]-#2],-#2,#2])&,{0},Range@#]&

Usage
Fold[#~Append~(#[[-1]]+If[#[[-1]]>#2&&FreeQ[#,#[[-1]]-#2],-#2,#2])&,{0},Range@#]&[30]
{0,1,3,6,2,7,13,20,12,21,11,22,10,23,9,24,8,25,43,62,42,63,41,18,42,17,43,16,44,15,45}

Tcl, 103 bytes
proc A n {lappend L [expr {$n?[set x [lindex [set L [A [expr $n-1]]] e]]>$n&$x-$n ni$L?$x-$n:$x+$n:0}]}

Try it online!

Common LISP (139 bytes)
(defun r(n)(do*(s(i 0(1+ i))(a 0(car s))(b 0(- a i)))((> i n)(nreverse s))(push(cond((= 0 i)0)((and(> b 0)(not(find b s)))b)(t(+ a i)))s)))

Ungolfed:
(defun recaman (n)
  (do*
   (series               ; starts as empty list
    (i 0 (1+ i))         ; index variable
    (last 0 (car s))     ; last number in the series
    (low 0 (- last i)))

   ((> i n)              ; exit condition
    (nreverse series))   ; return value

    (push                ; loop body
     (cond
       ((= 0 i) 0)       ; first pass
       ((and
         (> low 0) (not (find low s)))
        low)
       (t (+ last i)))
     series)))

Rust, 154 139 bytes
This is pretty big, but I like that it only uses one comparison per iteration instead of the 2 given, thanks to Saturating Subtraction generating a 0 if a[n-1]-n would be less than 0; and since 0 is already the first element, every would-be negative is saturated to 0 and is detected instead by the 'A already contains' comparison. Also... the size is not bad compared to Clojure, C#, C++, Common Lisp, lua..
fn r(n:usize)->Vec<usize>{let mut a=vec![0usize;n];for i in 1..n{a[i]=if a.contains(&(a[i-1].saturating_sub(i))){a[i-1]+i}else{a[i-1]-i}}a}

ungolfed
fn r(n:usize)->Vec<usize>{
  let mut a=vec![0usize;n];
  for i in 1..n {
     a[i] = if a.contains(&(a[i-1].saturating_sub(i)))
            {a[i-1]+i} else {a[i-1]-i}
 }a}

Try it on the rust playground

Common Lisp, 122 bytes
(setf h(make-hash-table)n(read)j 0)(dotimes(i n)(when(or(<(decf j i)0)#1=(gethash j h))(incf j(+ i i)))(print(setf #1#j)))

Try it online!
The sequence is generated by from 0, the values are stored in a hash table. Here is the ungolfed version:
(setf h (make-hash-table)         ; create a hash table to store the results
      n (read)                    ; read the input in n
      j 0)                        ; initial value of the sequence
(dotimes (i n)                    ; loop for i from 0 below n
  (when (or (< (decf j i) 0)      ; the new value is the old - i; if negative
            (gethash j h))        ; or if the value has been already generated
    (incf j (+ i i)))             ; set j to A(n-1) + i (third case)
  (print (setf (gethash j h) j))) ; store the result in the table and print it

F#, 117 116 bytes
fun n->Seq.fold(fun(l:'a list)h->let a=l.[h-1]in if a-h>0&&not(Seq.contains(a-h)l)then l@[a-h]else l@[a+h])[0][1..n]

Perl 5, 65 bytes
push@a,($t=$a[-1]-$_)+($t<0||grep$t==$_,@a)*$_*2for 0..<>;say"@a"

Try it online!

Pyth, 24 bytes
tu+G-eG_W|g0J-eGH}JGHQ]0

Try it online!
tu+G-eG_W|g0J-eGH}JGHQ]0   Implicit: Q=eval(input())
 u                   Q     Reduce [0-Q)...
                      ]0   ... with initial value G=[0], next value as H:
              eG             Last value of G (sequence so far)
             -  H            Take H from the above
            J                Store in J
          g0J                0 >= J
                 }JG         Is J in G?
         |                   Logical OR of two previous results
       _W           H        If the above is true, negate H, otherwise leave as positive
    -eG                      Subtract the above from last value in G
  +G                         Append the above to G
                           The result of the reduction is the sequence with an extra leading 0
t                          Remove a leading 0, implicit print

Haskell, 77 73 bytes
f 0=[0]
f n|x<-g n,y<-last x=x++[last$y-n:[y+n|y<n||y-n`elem`x]]
g=f.pred

Try it online!

Jelly, 15 bytes
_Ṫ»0ḟ⁸ȯ+Ṫ⁸;
Ḷç/

A monadic Link that accepts a positive integer, \$n\$, and yields a list of non-negative integers, the first \$n\$ terms of \$A\$.
Try it online!
How?
_Ṫ»0ḟ⁸ȯ+Ṫ⁸; - Link 1, next prefix of Recamán: list, current_prefix; integer, next_n
                                  (1st call is actually made with current_prefix=0)
_           - (current_prefix) subtract (next_n)  -> [A(0)-n...,A(n-1)-n] (or A(0)-n when current_prefix=0)
 Ṫ          - tail                                -> A(n-1)-n
  »0        - maximum of that and zero            -> 0 or A(n-1)-n
    ḟ⁸      - filter discard if in current_prefix -> [] or [A(n-1)-n]
       +    - (current_prefix) add (next_n)       -> [A(0)+n...,A(n-1)+n] (or A(0)+n when current_prefix=0)
      ȯ     - (filtered) logical OR (added)       -> [A(n-1)-n] or [...,A(n-1)+n] (or A(0)+n when current_prefix=0)
        Ṫ   - tail                                -> A(n-1)-n or A(n-1)+n
         ⁸; - concatenate this to the current_prefix

Ḷç/ - Main Link: positive integer, n
Ḷ   - lowered range -> [0,1,2,...,n-1]
  / - reduce using:
 ç  -   last Link (Link 1) as a dyad

05AB1E, 16 bytes
0λ£Nλ₁N-Dd*åi+ë-

Try it online.
Explanation:
 λ              # Create a recursive environment
0               # which starts at a(0)=0
  £             # to output the first (implicit) input amount of values
                # (which will be output implicitly in the end)
                # and in each iteration, we calculate the next `a(n)` with:
     ₁          #  Push `a(n-1)`
      N-        #  Subtract the current `n`
        D       #  Duplicate this `a(n-1)-n`
         d      #  Check that it's non-negative (>= 0)
          *     #  Multiply it to `a(n-1)-n` (so it'll become 0 if it's negative)
    λ      åi   #  If it's in the list of previous [a(0), ..., a(n-1)] values:
   N         +  #   Add `n` to the implicit `a(n-1)`
            ë   #  Else:
   N         -  #   Subtract `n` from the implicit `a(n-1)` instead

JavaScript (ES6), 57 bytes
n=>(g=k=>n--?[p+=p<k|g[p-k]?k:-k,...g(g[p]=k+1)]:[])(p=0)

Try it online!

Japt, 20 bytes
@TwXµY *!ZøX ªX+YÑ}h

Try it

Julia 1.0, 110 81 bytes
[]|>v->0|>a->0:parse(Int,readline()).|>i->(println(a+=2(a-i in v)i-i);v=[v;a;~i])

Try it online!
-29 thx to Steffan!

81 bytes. Recursion is probably even shorter.

D, 108 bytes
T[]r(T)(T n){T[]a=[0];T[T]b;foreach(i;1..n+1){T x=a[$-1];x+=(x>i)&&!((x-i)in b)?-i:i;a~=x;b[x]=1;}return a;}

Uses a function template shortcut syntax.
Try it online by pasting the following snippet to https://run.dlang.io/
T[]r(T)(T n){T[]a=[0];T[T]b;foreach(i;1..n+1){T x=a[$-1];x+=(x>i)&&!((x-i)in b)?-i:i;a~=x;b[x]=1;}return a;}
void main(){import std.stdio;writeln(r(10));}

Size reduced from 117 to 108 bytes by using a function template shortcut syntax.

Clojure, 107 bytes
#(loop[s[0]i 1](if(= i %)s(recur(conj s(let[l(last s)N(- l i)](if(or(< N 0)((set s)N))(+ l i)N)))(inc i))))

Not many tricks here, ((set s)N) evaluates to N if it is in the set and nil otherwise :)

APL (Dyalog Unicode), 40 bytesSBCS
{⌽{⍵,⍨(((∊∘⍵∨≤∘0)r)×2×≢⍵)+r←(⊃-≢)⍵}⍣⍵⊢0}

Try it online! I will be back for some more golfing and to write an explanation, just give me some hours. Ok I need some more time, in golfing this I managed to make it longer.

34 bytes (Changed 0 to ⍬ to match the challenge more closely)

source: Stack Exchange

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

sort: votes


text:
Tips for golfing in Applescript
What tips do you have for golfing in Applescript? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Applescript (e.g. "remove comments" is not an answer).

This question is Too Broad. It can't possibly be answered with a one complete, well-written answer (and the question even explicitly forbids that).

Still, it's just a funny question :)

Flagged for conversion to CW (per our convention for 'tips for golfing in x' questions).

@MadTux Yep, Applescript is not usually the 1st choice in golfing languages ;-).  But there are occasions, particularly in the [tag:restricted-source] category where it becomes marginally useful.

@Rainbolt Just to be clear, is your comment aimed at this question in particular, or all [tag:tips] for golfing in x questions in general?

@DigitalTrauma This question in particular.

@Rainbolt How is this different in nature to other [tag:tips] for golfing in x questions?

@DigitalTrauma I never said it was. If you wish to continue this interrogation, please open separate chat room and invite me.

The of operator is used to get a property from an object:
log words of "Hello World"

But in many cases you can use 's as a shortcut to save 1 character:
log "Hello World"'s words

It seems somewhat ridiculous, but also somewhat awesome, that Applescript parses apostrophes as possessive. I can just imagine one of the language designers pitching that idea to the group.

@Geobits Those are great adjectives for describing Applescript in general.  I just haven't decided if Applescript is ridiculously awesome or awesomely ridiculous ;-)

Some words have shorter synonyms. For example, application can be written as app*, and string can be written as text.
Also, every <noun> can be written as simply the plural, as in characters of "hello world" (or "foo"'s characters).
*Although Script Editor's compiler will change it back.

The Applescript Editor is a handy little IDE which syntax-highlights and beautifies your code.  However, for the purposes of golfing, it is counterproductive as it adds indentation and superfluous keywords, e.g. after end statements.  For example:
repeat with w in "Hello World"'s words
log w
end

becomes the following when pasted into the Applescript Editor and compiled/run:
repeat with w in "Hello World"'s words
    log w
end repeat

Obviously the first snippet is better for the purposes of golfing.

IMO this can be seen as a general tip, not specific to AS. Many modern IDEs do this if you let them.

@Geobits Agreed.  Though I think the addition of specific keywords after end is fairly Applescript specific.

Yea, that's just baffling to me. The indentation/spacing thing is very common, though, along with unnecessary brackets, etc.

@Geobits Applescript is all about readability.  I guess the idea is to make it clear which end belongs to which block start statement when you have multiple nested blocks

tell blocks are common in Applescript:
tell application "TextEdit"
    activate
end tell

However to save space the following is equivalent, when the inside of the tell block is just one line:
tell application "TextEdit" to activate

Which itself is tell app "TextEdit" to activate.

@WChargin Yes.  Add it as another answer if you like.

Quotation Required Operation
For any operation that requires a quote to do something, i.e.
log "Hello World!"
You can shorten to
log"Hello World!"
Repeating
In repeat loops, one can entirely remove the word "times".
repeat x times
end
versus
repeat x
end
<= and >=
Any time these operators are called, you can replace them with ≤ and ≥, respectively. While this may not reduce byte count (unless special byte counting conventions are implemented, which I suggest), it does reduce character count.
Grabbing from STDIN
You can grab from STDIN in with the following characters:
on run argv
end
Exiting quickly
If you need to exit a code quickly (for whatever reason, i.e. preventing excessive ifs)...
quit

Haha wow, you must have done some trawling to find this ;)

I use it a lot.

The question or the tips?

The tips. And AppleScript in general.

Oh I was talking about the question :)

Oh! No, it was one of the things suggested for me in the sidebar.

Lots of good tips here - generally you can add one answer per tip.

Applescript allows some extra keywords to be inserted to help readability:
log the words of "Hello World"

But the the here is completely superfluous and may be omitted for a 4 character saving:
log words of "Hello World"

You can have even shorter variants: log"Hello World"'s words, because you 1) don't need the space between any expression and quoted item, and 2) because 's can be used in replacement of of.

@VTCAKAVSMoACE yes, 's is addressed in this answer http://codegolf.stackexchange.com/a/37643/11259.  Good to know about log" though.

Bracket Shortening
Similar to the post about quotations, I realized later that you can also shorten things like this:
if "a"=character 1 of (x as string) then return {true, true}
to
if"a"=character 1 of(x as string)then return{true,true}
It'll space out brackets for you too. In this example, I save 5 bytes.

Considering...
In questions that require case sensitivity, it can be difficult to actually deal with cases.
UNTIL NOW:
considering case
    (something to do with case sensitive stuff)
end considering
I didn't actually know this keyword until I really needed it. Using the other tips in this tips page, we can reduce this down to:
considering case
(something to do with case sensitive stuff)
end
It does require a full statement, as far as I know. (I've tried a lot of things.) See this page for more details.

In a few exceptional cases, the «double angle brackets» or «double chevrons» might be shorter than the English name of a command, parameter, or constant.
The chevron-encoded form would shrink the AppleScript to delete the clipboard from 20 to 16 characters:
set the clipboard to  -- 20
«event JonspClp»      -- 16

It would drop 2 characters when fetching text from a dialog (as happens in metronome and Pi Day):
(display dialog""default answer"")'s text returned  -- 46
(display dialog""default answer"")'s«class ttxt»    -- 44

(You might prefer to avoid the dialog and use the command-line arguments of osascript(1), if you have at least Mac OS X 10.4.)
With a US keyboard, « is option-\ and » is option-shift-\. A command «event abcdefgh» has 16 characters. A parameter or constant «class abcd» has 12 characters.
The chevron-encoded form is almost always too long for golf. Here is an example without double angle brackets:
set x to open for access"output"write permission 1
write"One line of text
"to x
close access x

And the same with them:
set x to«event rdwropen»"output"given«class perm»:1
«event rdwrwrit»"One line of text
"given«class refn»:x
«event rdwrclos»x

Changing _open for access (16) to «event rdwropen» (16) was neutral. Changing write permission_ (17) to given«class perm»: (18) cost 1 character. The other double angle brackets cost more.
To use double angle brackets, you need to know the magic 4-letter or 8-letter code. I found some codes by saving a script file from Script Editor, then opening it in a hex editor. I ran emacs in a terminal and used M-x hexl-find-file. I found and edited some codes, like JonspClp into JanspClp, and ttxt into atxt. I then saved the file and reopened it in Script Editor. «event JanspClp» and «class atxt» appeared in the script.
A document titled AppleScript Terminology and Apple Event Codes Reference lists some codes. I found a copy of it at https://applescriptlibrary.wordpress.com/
Script Editor will translate double angle brackets to English before saving your script. For chevron deference, you must write your script in another text editor, like TextEdit. Save the script as a plain text file in the Mac OS Roman (or MacRoman) encoding. Mac OS X prefers that you name the file with an .applescript suffix.
If you count bytes, MacRoman has 1 byte per character, so each « or » counts as 1 byte.

Careful though, « and » are 0xc2ab and 0xc2bb in UTF-8 - i.e. 2 bytes each.

An especially useful variant is replacing text item delimiters with «class txdl».

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


text:
Drive a hexadecimal 7-segment display using NAND logic gates
The ubiquitous 7-segment numerical display can unambiguously display all 16 hexadecimal digits as show in this wikipedia .gif
Entries for this challenge will create a circuit diagram using NAND logic gates which transforms the four bits of a hex digit to the inputs for the seven segments.  The inputs for the 7 segment display are typically labelled as follows: (DP (decimal point) is ignored for this challenge)

Thus your circuit will need to conform to the following truth table:
Hex   | Hex Input Bit | Output to Segment line:
digit |  3  2  1  0   |  A  B  C  D  E  F  G
------+---------------+-----------------------
   0  |  0  0  0  0   |  1  1  1  1  1  1  0
   1  |  0  0  0  1   |  0  1  1  0  0  0  0
   2  |  0  0  1  0   |  1  1  0  1  1  0  1
   3  |  0  0  1  1   |  1  1  1  1  0  0  1
   4  |  0  1  0  0   |  0  1  1  0  0  1  1
   5  |  0  1  0  1   |  1  0  1  1  0  1  1
   6  |  0  1  1  0   |  1  0  1  1  1  1  1
   7  |  0  1  1  1   |  1  1  1  0  0  0  0
   8  |  1  0  0  0   |  1  1  1  1  1  1  1
   9  |  1  0  0  1   |  1  1  1  1  0  1  1
   A  |  1  0  1  0   |  1  1  1  0  1  1  1
   b  |  1  0  1  1   |  0  0  1  1  1  1  1
   C  |  1  1  0  0   |  1  0  0  1  1  1  0
   d  |  1  1  0  1   |  0  1  1  1  1  0  1
   E  |  1  1  1  0   |  1  0  0  1  1  1  1
   F  |  1  1  1  1   |  1  0  0  0  1  1  1

I think this table is accurate, but please let me know if you spot any errors.
Your score is determined by the number of 2-input NAND gates you use (1 point per gate).  To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores:

NOT: 1
AND: 2
OR: 3
XOR: 4

this challenge seems to be about drawing a circuit diagram, and not about coding. Also, the point values per gate seem arbitrary (maybe intentionally), and using AND+NOT is 3 points, when you state NAND is only 1.

@stokastic There are plenty of other [tag:logic-gates] challenges on this site, so I am assuming this category of challenge acceptable to the community.  Many use the same scoring system.  NAND logic I think explains this scoring system quite well.

Fair enough. I hadn't seen those tags before. It just doesn't seem to really fit in 'programming puzzles' or 'code golf'.

Can the circuit split? In other words, can you save values to variables and recall them later?

@xnor Are you talking about this sort of thing: http://codegolf.stackexchange.com/a/26235/11259? If so, the answer is yes.

I assume they have to be 2-input NAND gates (you can't cheat by using NAND gates with more than 2 inputs each.) If you search for previous questions about NAND gates, most of them state this explicitly.

We had to do this in my second year of undergrad engineering. No way am I doing it again for fun. :D :P  My answer is: use an FPGA. :D

@steveverrill That is correct.  I will clarify that.

30 NANDs
I am quite sure there are no simpler solutions to this problem,
except perhaps by changing the symbols on the display,
but that would be another and different problem.
Since this is actually something useful to do, for instance when
programming an FPGA to show output, I provide Verilog code.
As for the minimalism: Of course it was tricky to make.
It is not comprehensible, since a 7-segment display is
just a fairly random way that humans show numbers, resulting
in a circuit that is fairly random too.
And as is typical for these minimal circuits, its logical depth
is somewhat higher than for close solutions. I guess this is because serial is simpler than parallel.
Transmission delay is indicated by downward position of each NAND gate on the sheet.

Verilog code:
// Hexadecimal 7-segment display driver
// Minimal at 30 NANDs
//
// By Kim Øyhus 2018 (c) into (CC BY-SA 3.0)
// This work is licensed under the Creative Commons Attribution 3.0
// Unported License. To view a copy of this license, visit
// https://creativecommons.org/licenses/by-sa/3.0/
//
// This is my entry to win this Programming Puzzle & Code Golf
// at Stack Exchange:
// https://codegolf.stackexchange.com/questions/37648/drive-a-hexadecimal-7-segment-display-using-nand-logic-gates
//
// I am quite sure there are no simpler solutions to this problem,
// except perhaps by changing the symbols on the display,
// but that would be another and different problem.
//
// Since this is actually something useful to do, for instance when
// programming an FPGA to show output, I provide this Verilog code.
//
// As for the minimalism: Of course it was tricky to make.
// It is not comprehensible, since a 7-segment display is
// just a fairly random way of showing numbers, resulting
// in a circuit that is fairly random too.
// And as is typical for these minimal circuits, its logical depth
// is somewhat higher than for close solutions. I guess this is because
// serial is simpler than parallel.
//
// 4 bits of input "in_00?", and 7 bits of output,
// one bit per LED in the segment.
//   A
// F   B
//   G
// E   C
//   D

module display7 ( in_000, in_001, in_002, in_003,  G, F, E, D, C, B, A );
  input in_000, in_001, in_002, in_003;
  output G, F, E, D, C, B, A;
  wire wir000, wir001, wir002, wir003, wir004, wir005, wir006, wir007, wir008, wir009, wir010, wir011, wir012, wir013, wir014, wir015, wir016, wir017, wir018, wir019, wir020, wir021, wir022 ;

  nand gate000 ( wir000, in_000, in_002 );
  nand gate001 ( wir001, in_000, in_000 );
  nand gate002 ( wir002, wir000, in_001 );
  nand gate003 ( wir003, in_001, wir002 );
  nand gate004 ( wir004, wir000, wir002 );
  nand gate005 ( wir005, in_002, wir003 );
  nand gate006 ( wir006, in_003, wir001 );
  nand gate007 ( wir007, wir006, wir004 );
  nand gate008 ( wir008, in_003, wir005 );
  nand gate009 ( wir009, wir005, wir008 );
  nand gate010 ( wir010, in_003, wir008 );
  nand gate011 ( wir011, wir010, wir009 );
  nand gate012 ( wir012, wir010, wir007 );
  nand gate013 ( wir013, wir001, wir011 );
  nand gate014 ( wir014, wir003, wir004 );
  nand gate015 (      G, wir011, wir014 );
  nand gate016 ( wir015, in_003, wir014 );
  nand gate017 ( wir016, wir015, wir013 );
  nand gate018 (      C, wir016, wir012 );
  nand gate019 ( wir017, wir016, wir007 );
  nand gate020 ( wir018, wir003, wir012 );
  nand gate021 ( wir019, wir017, in_003 );
  nand gate022 (      F, wir011, wir017 );
  nand gate023 (      D, wir018, wir017 );
  nand gate024 (      B, wir012,      F );
  nand gate025 ( wir020, wir004, wir018 );
  nand gate026 ( wir021, wir001,      D );
  nand gate027 (      E, wir019, wir021 );
  nand gate028 ( wir022,      D, wir019 );
  nand gate029 (      A, wir020, wir022 );
endmodule

Kim Øyhus

I (@Digital Trauma) recently reviewed this answer and was so impressed with it, I drew it out in Logic.ly and captured this GIF - it really does work!

This is a really impressive solution! Why are you so confident that one can't do better than 30? 37 already looked "pretty reduced", imo.

Thanks. I searched beyond this solution, using much more time for that than for finding the solution itself, and there was nothing there. The probability that I missed something better is very small. It is a statistical argument.

This is amazing! What techniques did you use to get the solution, may I ask?

This I verified to work, thank you

Dominoes - Total Score: 243 NANDs

ORs used: 61 (3 NANDs each -> 183 NANDs)
NOTs used: 60 (1 NANDs each -> 60 NANDs)

This solution is in dominoes and required a collection of pieces of software I wrote in the course of answering Martin Büttner's two Domino related questions to produce (Golfing for Domino Day and Domino Circuits).
By modifying my Domino Circuit solver, I was able to produce a domino circuit (this file also contains the solver output and circuit skeleton) consisting of ORs, and IFNOTs where the first input is always TRUE (so it's essentially a NOT). Because there isn't much that will fit in this answer, I present the OR and NOT solutions to the truth table:
A: 1011011111101011
((-1 ifnot (2 or (1 or (-1 ifnot 0)))) or ((-1 ifnot ((-1 ifnot 1) or (-1 ifnot 2))) or ((-1 ifnot (3 or (-1 ifnot (0 or (-1 ifnot 1))))) or (-1 ifnot (0 or ((-1 ifnot 3) or (-1 ifnot (2 or 1))))))))
B: 1111100111100100
((-1 ifnot (3 or 1)) or ((-1 ifnot (3 or (2 or 0))) or (-1 ifnot ((-1 ifnot 3) or ((-1 ifnot (2 or (0 or (-1 ifnot 1)))) or (-1 ifnot ((-1 ifnot 0) or (-1 ifnot 2))))))))
C: 1101111111110100
((-1 ifnot (2 or (-1 ifnot 3))) or ((-1 ifnot (1 or (-1 ifnot 0))) or (-1 ifnot (0 or (-1 ifnot (3 or (1 or (-1 ifnot 2))))))))
D: 1011011011011110
((-1 ifnot (3 or (1 or 0))) or ((-1 ifnot (2 or ((-1 ifnot (3 or 0)) or (-1 ifnot (1 or 0))))) or (-1 ifnot ((-1 ifnot 2) or ((-1 ifnot (3 or 1)) or (-1 ifnot ((-1 ifnot 1) or (-1 ifnot 3))))))))
E: 1010001010111111
((-1 ifnot (3 or (-1 ifnot (2 or (-1 ifnot 1))))) or (-1 ifnot ((-1 ifnot 0) or (-1 ifnot (2 or 1)))))
F: 1000111011111011
((-1 ifnot (3 or (-1 ifnot 1))) or ((-1 ifnot (2 or (0 or (-1 ifnot (1 or (-1 ifnot 3)))))) or (-1 ifnot ((-1 ifnot 0) or (-1 ifnot (2 or (-1 ifnot 1)))))))
G: 0011111011110111
((-1 ifnot (2 or (0 or (-1 ifnot 1)))) or ((-1 ifnot (1 or (-1 ifnot (2 or 0)))) or (-1 ifnot ((-1 ifnot (3 or 2)) or (-1 ifnot (0 or (-1 ifnot 3)))))))

Note that the only binary operations used are OR and IFNOT, where I count each IFNOT as a NOT for scoring purposes
I added a 7-segment display to the end of the circuit and fed it into a domino simulator/gif generator. The resulting gif (which shows 'A' being displayed) took about 2 hours to generate. Because the final circuit is 1141 * 517 in size each "cell" is represented by a single pixel. A black cell is empty, a grey cell has a standing domino in it, and a white cell has a fallen domino in it. This means that you can't really tell what is going on, and it won't help if it's being squashed at all. Sparr kindly provided a much smaller version of my original gif (650kB), so here it is!

Below is the last frame of the animation for input 1010 ('A') as above. You can see the inputs on the far left, powerline at the top, the switchboard taking up most of the space, the 7 individual pieces of logic (these are domino representations of the functions above) to the left of the switch board, and to the far right is the 7-segment display itself. When this runs, the individual segments light up roughly at the same time, so you can't be looking at it for too long with some segments lit up waiting for others to light up.

See the animation in it's full glory here (36MB) or here (650kB, courtesy of Sparr) (the smaller copy is much smaller, but my browser seemed to like skipping frames marring the beauty so I've left the original thusly)
The detail of the 7-segment display can be seen here ('1' is shown)

+1 for the sheer surreality of driving a 7-segment display with dominoes!

That is amazing... Someone should try this in real life

Using ~ for NOT and N for NAND, a computer search (without sharing terms between outputs) finds a solution with 82 NANDs without sharing.  Manually looking for sharing terms reduces it to 54 NANDs,  and a computer search that includes sharing further reduces it to 37 NANDs.  The minimum might be even lower, as the method is certainly not exhaustive.
Here's the program that recreates the above table.  Each line is labeled with the NANDS for that output.
#include <stdio.h>

int N(int x, int y) { return 1 & ~(x & y); }

void main(void)
{
    int i0, i1, i2, i3;
    for (i3 = 0; i3 <= 1; i3++) {
    for (i2 = 0; i2 <= 1; i2++) {
    for (i1 = 0; i1 <= 1; i1++) {
    for (i0 = 0; i0 <= 1; i0++) {
            printf("%d %d %d %d : %d %d %d %d %d %d %d\n", i3, i2, i1, i0,
    /* 14 */        N(N(N(i3, N(i2, i1)), N(N(i2, i0), ~i1)), N(N(i2, N(i3, N(i3, i0))), N(i0, N(i3, N(i3, i1))))),
    /* 12 */        N(N(N(i3, i0), N(i2, N(i1, i0))), N(~i1, N(N(i3, i0), N(~i3, N(i2, i0))))),
    /* 10 */        N(N(i0, N(i3, i1)), N(N(i3, i2), N(i1, N(i1, N(~i3, ~i2))))),
    /* 16 */        N(N(N(i2, i1), N(N(i3, i0), N(i2, i0))), N(N(i0, N(i1, ~i2)), N(N(i3, i2), N(N(i3, i1), N(i2, N(i2, i1)))))),
    /*  7 */        N(N(i3, i2), N(N(i2, N(i2, i1)), N(i0, N(i3, i1)))),
    /* 11 */        N(N(i3, N(i2, N(i3, i1))), N(N(i1, N(i2, N(i2, i0))), N(i0, N(i2, ~i3)))),
    /* 12 */        N(N(i3, i0), ~N(N(i1, N(i2, i0)), N(N(i3, i2), N(~i3, N(i2, N(i2, i1)))))) );
    } } } }
}

And here's the output:
0 0 0 0 : 1 1 1 1 1 1 0
0 0 0 1 : 0 1 1 0 0 0 0
0 0 1 0 : 1 1 0 1 1 0 1
0 0 1 1 : 1 1 1 1 0 0 1
0 1 0 0 : 0 1 1 0 0 1 1
0 1 0 1 : 1 0 1 1 0 1 1
0 1 1 0 : 1 0 1 1 1 1 1
0 1 1 1 : 1 1 1 0 0 0 0
1 0 0 0 : 1 1 1 1 1 1 1
1 0 0 1 : 1 1 1 1 0 1 1
1 0 1 0 : 1 1 1 0 1 1 1
1 0 1 1 : 0 0 1 1 1 1 1
1 1 0 0 : 1 0 0 1 1 1 0
1 1 0 1 : 0 1 1 1 1 0 1
1 1 1 0 : 1 0 0 1 1 1 1
1 1 1 1 : 1 0 0 0 1 1 1

And here are the equivalent equations, sharing terms that get it down to 54 NANDs:
    /* 1 */ int z1 = 1 - i1;
    /* 1 */ int z2 = 1 - i2;
    /* 1 */ int z3 = 1 - i3;

    /* 1 */ int n_i2_i0 = N(i2, i0);
    /* 1 */ int n_i2_i1 = N(i2, i1);
    /* 1 */ int n_i3_i0 = N(i3, i0);
    /* 1 */ int n_i3_i1 = N(i3, i1);
    /* 1 */ int n_i3_i2 = N(i3, i2);

    /* 1 */ int n_i0_n_i3_i1 = N(i0, n_i3_i1);
    /* 1 */ int n_i2_n_i2_i1 = N(i2, n_i2_i1);

            printf("%d %d %d %d : %d %d %d %d %d %d %d\n", i3, i2, i1, i0,
    /* 9 */ N(N(N(i3, n_i2_i1), N(n_i2_i0, z1)), N(N(i2, N(i3, n_i3_i0)), N(i0, N(i3, n_i3_i1)))),
    /* 7 */ N(N(n_i3_i0, N(i2, N(i1, i0))), N(z1, N(n_i3_i0, N(z3, n_i2_i0)))),
    /* 5 */ N(n_i0_n_i3_i1, N(n_i3_i2, N(i1, N(i1, N(z3, z2))))),
    /* 8 */ N(N(n_i2_i1, N(n_i3_i0, n_i2_i0)), N(N(i0, N(i1, z2)), N(n_i3_i2, N(n_i3_i1, n_i2_n_i2_i1)))),
    /* 2 */ N(n_i3_i2, N(n_i2_n_i2_i1, n_i0_n_i3_i1)),
    /* 8 */ N(N(i3, N(i2, n_i3_i1)), N(N(i1, N(i2, n_i2_i0)), N(i0, N(i2, z3)))),
    /* 6 */ N(n_i3_i0, ~N(N(i1, n_i2_i0), N(n_i3_i2, N(z3, n_i2_n_i2_i1)))) );

And here's the 37 NAND solution:
    x0fff =  N(i3, i2);
    x33ff =  N(i3, i1);
    x55ff =  N(i3, i0);
    x0f0f =  not(i2);
    x3f3f =  N(i2, i1);
    x5f5f =  N(i2, i0);
    xcfcf =  N(i2, x3f3f);
    xf3f3 =  N(i1, x0f0f);
    x5d5d =  N(i0, xf3f3);
    xaaa0 =  N(x55ff, x5f5f);
    xfc30 =  N(x33ff, xcfcf);
    xd5df =  N(x3f3f, xaaa0);
    xf3cf =  N(x0fff, xfc30);
    xaeb2 =  N(x5d5d, xf3cf);
    x7b6d =  N(xd5df, xaeb2);
    xb7b3 =  N(i1, x7b6d);
    xf55f =  N(x0fff, xaaa0);
    xcea0 =  N(x33ff, xf55f);
    x795f =  N(xb7b3, xcea0);
    xd7ed =  N(xaeb2, x795f);
    xfaf0 =  N(x55ff, x0f0f);
    xae92 =  N(x55ff, x7b6d);
    xdd6d =  N(x33ff, xae92);
    x279f =  N(xfaf0, xdd6d);
    xaf0f =  N(i2, x55ff);
    x50ff =  N(i3, xaf0f);
    xef4c =  N(xb7b3, x50ff);
    x1cb3 =  N(xf3cf, xef4c);
    xef7c =  N(xf3cf, x1cb3);
    xfb73 =  N(i1, x279f);
    x2c9e =  N(xd7ed, xfb73);
    xdf71 =  N(xf3cf, x2c9e);
    xdd55 =  N(i0, x33ff);
    xf08e =  N(x0fff, xdf71);
    x2ffb =  N(xdd55, xf08e);
    x32ba =  N(xcfcf, xdd55);
    xfd45 =  N(x0fff, x32ba);

    printf("%d %d %d %d : %d %d %d %d %d %d %d\n", i3, i2, i1, i0,
            xd7ed, x279f, x2ffb, x7b6d, xfd45, xdf71, xef7c);
    } } } }

You should have a proud header with "37 NANDs".
Your post is too modest without that.

197 NANDs
Since this is my first logic gates challenge. it is not golfed much, and may not be the smallest solution. I'm not using circuit split here.
A = OR(AND(d, NOT(AND(a, XOR(c, b)))), AND(NOT(d), NOT(AND(NOT(b), XOR(a, c)))))
B = AND(OR(OR(NOT(c), AND(NOT(d), NOT(XOR(b, a)))), AND(d, a)), NOT(AND(AND(d, b), a)))
C = OR(AND(NOT(c), NOT(AND(AND(NOT(d), b), NOT(a)))), AND(c, OR(NOT(d), AND(AND(d, NOT(b)), a))))
D = AND(OR(OR(OR(a, c), AND(AND(NOT(d), NOT(c)), NOT(a))), AND(AND(d, NOT(c)), NOT(b))), NOT(OR(AND(AND(NOT(d), NOT(b)), XOR(c, a)), AND(AND(c, b), a))))
E = OR(AND(NOT(a), NOT(AND(AND(NOT(d), c), NOT(b)))), AND(d, NOT(AND(AND(NOT(c), NOT(b)), a))))
F = AND(OR(OR(d, c), AND(NOT(b), NOT(a))), NOT(AND(AND(c, a), XOR(d, b))))
G = AND(OR(OR(d, c), b), NOT(OR(AND(AND(NOT(d), c), AND(b, a)), AND(AND(d, c), AND(NOT(b), NOT(a))))))

36 NOTs used, 36 NANDs
41 ANDs used, 84 NANDs
19 ORs used, 57 NANDs
5 XORs used, 20 NANDs

If I'm right, my score is 197.

During this challenge, I made a simple JavaScript code to test my gate.
function NOT(a){return !a}function AND(a,b){return a&b}function OR(a,b){return a|b}function XOR(a,b){return a^b}
for(d=0;d<=1;d++){for(c=0;c<=1;c++){for(b=0;b<=1;b++){for(a=0;a<=1;a++){console.log(""+d+c+b+a,
    // Enter your gate here
    // OR(AND(d, NOT(AND(a, XOR(c, b)))), AND(NOT(d), NOT(AND(NOT(b), XOR(a, c)))))
)}}}}

Copy and modify gate, and paste it to your browser's console, or Node.js REPL.


text:
Generating a single string with an Oxford comma from a list
What are some clever (brief and idiomatic) approaches to taking a list of strings and returning a single properly punctuated string built from the list, with each element quoted.
This came up for me while experimenting with Groovy, for which my too-literal, but illustrative solution is
def temp = things.collect({"\'${it}\'"})
switch (things.size()) {
    case 1:
        result = temp[0]
        break
    case 2:
        result = temp.join(" and ")
        break
    default:
        result = temp.take(temp.size()-1).join(", ") + ", and " + temp[-1]
        break
}

That is, ['1'] should yield '1', ['1','2'] should yield '1 and 2', [see what I did there?] and ['1','2','3'] should yield '1, 2, and 3'.
I have some good answers for Groovy, but I'd like to see what other languages can do.
What are some compact clever approaches in various languages that take advantage of the features and idioms of those languages?

Input is an Array of characters or a single string. i.e. ['1','2'] or "['1', '2']"

Welcome to PPCG.  Generally questions posted here are challenges to the community.  As such they need an objective winning criteria.  I believe this question maps reasonably well to being a [tag:code-golf] challenge.  Can you tag it as such?  If so, I think you should tighten up the input and output specifications a bit.

@DigitalTrauma: Good suggestion. Thanks. I'd like it to focus on producing the most idiomatic code; that is, the code that takes best advantage of the capabilities of the language. Is that a fair challenge (and of so, how should I tag it)?

@Optimizer: An array of characters (of of strings).

@MartinBüttner: For here, I'll go with length ([tag:code-golf]) then.

This would be more interesting with real sentences: ['we invited the stripper','JFK','Stalin']

Can we assume that the strings themselves don't contain commas already?

@MartinBüttner: Good question. Assume not: no commas or "and"s to mess things up.

Do we need to make it a complete CLI-executable solution? Must it be wrapped in a function declaration, or just the relevant code with setup instructions? Is the setup included in the scoring size?

Challenge should have been titled "Who gives a ---- about an Oxford comma?"

My old English teacher would be horrified to see a comma before an "and". The last result should read '1, 2 and 3' to be proper English English rather than the Americanised rubbish spoken in the colonies. :)

@OldCurmudgeon I think you mean "Americanized rubbish" ;)

CSS, 132 116 115 bytes

a:not(:last-child):nth-child(n+2):after,a:nth-last-child(n+3):after{content:","}a+:last-child:before{content:"and "

  one

  one
  two

  one
  two
  three

  one
  two
  three
  four

a:not(:last-child):nth-child(n+2):after,a:nth-last-child(n+3):after{content:","}a+:last-child:before{content:"and "

CSS is not seen too often in code golf because it can only format text, but it actually works for this challenge and I thought it would be fun to do. See it in action using the snippet above (click "Show code snippet").
List should be in a linked HTML file with each element surrounded by  tags and separated by line breaks. The list items should be the only elements in their parent element, e.g.
one
two
three

Explanation
a:not(:last-child):nth-child(n+2)::after,
a:nth-last-child(n+3)::after {
    content: ",";
}

a + :last-child::before {
    content: "and ";
}

Let's consider the ungolfed version above. If you're not familiar with how CSS works, everything outside the curly braces is a selector that determines the set of HTML elements to which the declarations inside the braces apply. Each selector-declaration pair is called a rule. (It's more complicated than that but will suffice for this explanation.) Before any styling is applied, the list appears separated by only spaces.
We want to add commas after every word except the last, except for two-word lists, which get no commas. The first selector, a:not(:last-child):nth-child(n+2):after, selects all elements except the first and the last. :nth-child(n+2) is a shorter way of saying :not(:first-child), and it basically works by selecting elements whose index (starting at 1) is greater than or equal to 2. (Yes, it still confuses me a little. The MDN docs might help.)
Now we just need to select the first element to get a comma if there are three or more elements total. a:nth-last-child(n+3):after works like :nth-child, but counting from the back, so it selects all elements except the last two. The comma takes the union of the two sets, and we use the :after pseudo-element to add content immediately after each selected element.
The second rule is easier. We need to add "and" before the last element in the list, unless it is a single element. In other words, we need to select the last element that is preceded by another element. + is the adjacent sibling selector in CSS.

Brilliant! I love it. :D

If only you'd use
.

 would be ideal, but that would add two extra characters to the selectors. I chose  because it is one letter and doesn't apply its own formatting.

Wow... this is very impressive. Cleverness award.

CSS as the top answer? Nice.

89b => http://codegolf.stackexchange.com/questions/37653/generating-a-single-string-with-an-oxford-comma-from-a-list/37796#37796

Why do you need line breaks? HTML is supposed to just treat them like a space.

@trlkly The line breaks eliminate the need for adding spaces to the CSS code because they are automatically converted to spaces.

Haskell: 81, 77 74 chars
f[x]=x
f[x,y]=x++" and "++y
f[x,y,z]=x++", "++f[y++",",z]
f(x:y)=x++", "++f y

Haskell features: Pattern matching

You can remove some spaces

You could just remove f[x,y,z]

And now, it is pretty much standard recursion. :)

you forgot the oxford comma and spaces after the commas - f["a","b","c"] is supposed to be "a, b, and c" but it is "a,b and c"

also you could golf a bit by replacing " "++f y by ' ':f y

@proudhaskeller Is it still possible with the version including whitespace?

you still need to add the actual oxford comma :). also, you better cut out the old incorrect version (it is still visible in the edit history). about the ',': optimization, unfortunately not.

Currently it gives 1, 2, 3,  and 4

@Sieg not on my computer, and not as simulated by my mind

@proudhaskeller Now the correct version is there again.

how about golfing by replacing y++", and "++z by f[y++",",z] :)

Ruby, 47 bytes
q=" and ";p$*[2]?(a=$*.pop;$**", "+?,+q+a):$**q

Explanation

The input are the command line arguments ($*).
When $* has a third element ($*[2] does not return nil), take all elements minus the last one and turn them into a comma-separated String using Array#*. Finally add an extra comma, the string " and " and the last command line argument.
When $* has no third element, two, one, or zero arguments were given. The arguments can safely be joined with the string " and " and produce the correct result.

Perl (v 5.10+) - 37 35 34 28
@F>2&&s/ /, /g;s/.* \K/and /

to be run with perl -ape, with the list supplied space separated on STDIN.
Output for various inputs:
$ perl -ape '@F>2&&s/ /, /g;s/.* \K/and /'
oxford
oxford
oxford cambridge
oxford and cambridge
oxford cambridge comma
oxford, cambridge, and comma
oxford cambridge comma space
oxford, cambridge, comma, and space

You can reduce this by 3 bytes by changing your last substitution to s/(\S+)$/and $1/

@ThisSuitIsBlackNot You can drop the '\n' (thanks), but you can't drop the spaces, or an input of "x" becomes "and x"

Oops, should have tested with more inputs. Anyway, you forgot the $ anchor in your edit, so an input of foo bar baz becomes foo, and bar, baz. Also, you can remove one of the spaces by doing s/( \S+)$/ and$1/

My last comment still leaves you at 35, but you can write $#F>1 as @F>2 to shave off one more. Sorry for all the suggestions for micro improvements, I just really like this answer :)

@ThisSuitIsBlackNot not at all - microedits welcome. I am secretly competing with 28 bytes of CJam and 30 bytes of Golfscript. However I did get to 34 without doing the translation of your comment before last (tested with echo -n ... | wc -c). If you miss the space before (\S+) you'd get to 33 characters, but if you put in test this you will get test  and this (two spaces after test), so without more I think that's wrong.

Okay, two more: replacing the second regex with s/.* \K/and / drops you down by 4 (requires Perl 5.10), and replacing the conditional operator with && shaves off one, for a grand total of 29! Take that, Golfscript! @F>2&&s/ /, /g;s/.* \K/and /

@ThisSuitIsBlackNot: you have excelled yourself. That's actually 28 not 29. I thought I tried && earlier and had operator precedence issues, but I obviously failed. Didn't think of \K. And WOAH! Tied with CJam! Thanks!

Oops, I guess I can't count. I knew Perl could hold its own in golf, though. I tried a lot of different approaches and yours was better than all of them, so kudos. All I did was tidy up a bit :P

CSS, 62 chars 112 chars
Inspired by the other entries, even shorter. Note that it requires that A elements are not separated by white spaces:
a+a:before{content:", "}a+a:last-child:before{content:", and "

http://jsfiddle.net/olvlvl/1Ls79ocb/
Fix for the "one and two", as pointed at by Dennis:
a+a:before{content:", "}a+a:last-child:before{content:", and "}a:first-child+a:last-child:before{content:" and "

http://jsfiddle.net/olvlvl/1Ls79ocb/3/

Python 2 (61)
s=input()
d=s.pop()
print", ".join(s)+", and "[8-7*len(s):]+d

The main trick is to cut off part of the final joiner ", and " for one and two elements. For one, all of it is cut out, and for two, the comma is removed. This is done by slicing out [8-7*len(s):] (noting that s is one shorter after the pop).
Unfortunately, d cannot just be replaced with its expression or the pop would happen too late.

You could replace the first s with s=input() and remove the first line, if I'm not mistaken. Saves 2 chars.

@tomsmeding I don't understand what you're suggesting. The code is referring to s multiple times.

Wait, I do weird stuff this morning. Forget that. :)

GNU sed -  69 chars including 1 for -r flag
s/ /, /g
s/( [^ ]+)( [^ ]+)$/\1 and\2/
s/^([^,]+),([^,]+)$/\1 and\2/

Takes a space-separated list (fairly idiomatic for shell scripts).
Example
$ sed -r -f oxfordcomma.sed <<< "1"
1
$ sed -r -f oxfordcomma.sed <<< "1 2"
1 and 2
$ sed -r -f oxfordcomma.sed <<< "1 2 3"
1, 2, and 3
$

Yes, let's go with [tag:code-golf].

The second output should be 1 and 2 instead of 1, 2

@Optimizer - quite right.  Fixed.

Javascript (63)
l=a.length;l>2&&(a[l-1]='and '+a[l-1]);a.join(l>2?', ':' and ')
Cases:

a = [1] => 1
a = [1, 2] => 1 and 2
a = [1, 2, 3] => 1, 2, and 3

Caveat: this will modify the last element in an array with length > 2.

Nice use of &&

Groovy, 47 43 57 characters , JavaScript ES6 56 characters
Groovy:
(a[1]?a[0..-2].join(", ")+(a[2]?",":"")+" and ":"")+a[-1]

Since the array is filled with characters, we can replace a.size>1 by a[1]
JavaScript, ES6:
a.join(', ').replace(/,([^,]+)$/,`${a[2]?',':''} and$1`)

Both cases assume that variable a has the array in question.

The Oxford comma is the comma before the conjunction.

Python 2 - 71, 70 68
s=input()
l=len(s)-1
print', '.join(s[:l])+', and '[l<2:]*(l>0)+s[l]

Character count including both, input and print.

CJam, 35 30 28 27 bytes
q~)\_"and "L?@+a+_,2=", ">*

This is a program that reads from STDIN and prints to STDOUT. Try it online.
How it works
q~                                     " Q := eval(input())                               ";
  )                                    " P := Q.pop()                                     ";
   \_"and "L?@+                        " P := (Q ? 'and ' : '') + P                       ";
                a+                     " Q += [P]                                         ";
                  _,2=", ">            " J := ', '[(len(Q) == 2):]                        ";
                           *           " R := J.join(Q)                                   ";
                                       " print R (implicit)                               ";

Example run
$ cjam <(echo 'q~)\_"and "L?@+a+_,2=", ">*') <<< '["1"]'; echo
1
$ cjam <(echo 'q~)\_"and "L?@+a+_,2=", ">*') <<< '["1""2"]'; echo
1 and 2
$ cjam <(echo 'q~)\_"and "L?@+a+_,2=", ">*') <<< '["1""2""3"]'; echo
1, 2, and 3
$ cjam <(echo 'q~)\_"and "L?@+a+_,2=", ">*') <<< '["1""2""3""4"]'; echo
1, 2, 3, and 4

I am on your tail - see below :-)

Ruby, 57 bytes
f=->l{s=l*', ';s.sub(/,(?!.*,)/,(l.size<3?'':?,)+' and')}

I'm joining the string with , and then I'm replacing the last comma in the string with an and (and optional comma depending on list length).

Cobra - 60
do(l as String[])=l.join(', ',if(l.length<3,'',',')+' and ')

Cobra's List<of T>.join function lets you specify a different separator for the final two elements of the list, which is what makes this so short.

Batch - 151 Bytes
@echo off&set f=for %%a in (%~1)do
%f% set/aa+=1
%f% set/ac+=1&if !c!==1 (set o=%%a)else if !c!==!a! (set o=!o!, and %%a)else set o=!o!, %%a
echo !o!

Note; you have to call the script from cmd with the /v switch set as on, this is so I don't have to include the lengthy setLocal enableDelayedExpansion in the script. Otherwise add 30 to the byte count, and call the script normally.
h:\uprof>cmd /von /c test.bat "1 2 3"
1, 2, and 3

h:\uprof>cmd /von /c test.bat "1 2 3 4 5"
1, 2, 3, 4, and 5

PHP, 192 167 146 136 characters:
$n=' and ';$s=count($a);echo ($s<3)?join($n,$a):join(', ',array_merge(array_slice($a,0,$s-2),Array(join(",$n",array_slice($a,-2,2)))));

Based on a function I wrote years ago at http://www.christopherbloom.com/2011/05/21/join-implode-an-array-of-string-values-with-formatting/

Can you please put your code (with Oxford commas) into the answer text?

Yes, sorry. I was on my phone and it wouldn't paste the code properly. I'll update from my desktop

@Chrisbloom7 even if it is trivial to add, the answer should include a working code, not one that can be made to be one. also, because the objective is to make the code as smaller as possible, not posting working code makes your score non existing.

Apologies again. First time poster at CG. I've fixed my answer

Perl - 59
sub f{$a=join', ',@_;$#_&&substr$a,(@_>2)-3,@_<3,' and';$a}

Joins the list with commas, then if the list has more than one element, either adds ' and' after the last comma (if length >= 3), or replaces the last comma with it (if length == 2).

PHP, 86 84 chars
$a = ['one', 'two', 'three', 'four', 'five'];

With the array initialized, we start counting:
$L=count($a)-1;$S=', ';$L<2?($S=' and '):($a[$L]='and '.$a[$L]);echo implode($S,$a);

Prettified:
$last_index = count($a) - 1;
$separator = ', ';
if ($last_index < 2) {
    $separator = ' and ';
} else {
    $a[$last_index] = 'and '.$a[$last_index];
}
echo implode($separator, $a);

The last item in the list is modified. This should be OK because in PHP, array assignment and function calls perform copies.

Google Sheets, 67 68 67 92 bytes
=SUBSTITUTE(JOIN(", ",FILTER(A:A,A:A<>"")),",",IF(COUNTA(A:A)>2,",","")&" and",COUNTA(A:A)-1

The input starts at cell A1 and continuing down for however many entries exist.
JOIN merges them all into a string with a comma-space between each.
FILTER removes any non-blanks so you don't end up with infinite commas at the end.
SUBSTITUTE replaces the last comma (found by COUNTA counting the non-blank inputs).
It's not very exciting but it's doable in a single cell.

This leaves out the oxford comma.

@Umbrella Well, that was stupid of me, wasn't it? +1 bytes

You should be able to drop the terminal ) off of this formula for -1 Byte; Well dang, that was the quickest edit I've ever seen +1

Two notes after testing this - A:A>"" should be converted to A:A<>"" and this does not implement omitting the oxford comma on cases of only 2 objects

@TaylorScott I guess I only ever tested with text and missed the issue with >"". The quickie correction I made earlier clearly wasn't tested. I don't like the direction that went...

I get what you mean - if you take a look at my solution's edits you can see where I realized I forgot the case of only 2 objects and ended up having to add some 40 bytes just to correct for it

Vyxal, 27 bytes
ṫ$:[`λ¬ `pJ:Ḣ₃[÷ð$Ṡ|‛, j]|_

Try it Online!
ṫ                           # Tail extract (x[:-1], x[-1] )
 $:[                        # If length > 1
    `λ¬ `p                  # Prepend a 'and '
          J                 # Merge
           :Ḣ₃[             # If length = 2
               ÷ð$Ṡ         # Add in a space and join
                   |    ]   # Else...
                    ‛, j    # Join by ', '
                         |_ # Else pop

Golfscript - 31 39 34 30
Hello, World! I am a long time lurker, first time poster. Here is my 30 byte solution in Golfscript (given the array such as [1 2 3] is already on the stack).
.,3<" and ":A{~A(;\+]", "}if*

The results are proper for all test cases.
EDIT: Take that, CJam!

Edited to account for the length 1 array.

Edited for a more efficient algorithm.

The battle continues. :P

Ah, but now we're even. :P

Xojo, 52 71 83 chars
dim i as int8=ubound(L)
L(i)=if(i=0,"","and ")+L(i)
Return L.Join(if(i=1," ",", ")

Note that UBound is one less than the array length.

This seems to add the comma when there are 2 items - should not

Good catch. Edited to fix.

JavaScript (ES6) 60
Assuming no empty strings in input array
f=(a,b=a.pop())=>a[0]?a.join(', ')+(a[1]?',':'')+' and '+b:b

Test In FireFox/Firebug console
console.log(f(['We invited the stripper','JFK','Stalin']))

Output
 We invited the stripper, JFK, and Stalin

How do I run this? I tried it in node --harmony with an array of strings var a = 'abcdefgh'.split('');, but it just sits there with a ... and appears to do nothing. Also +1 for using unique ES6 feature ()=>.

@Adrian the function returns a string, without any output. I'll add a test in the answer.

I think f=(a,b=a.pop())=>a[0]?a.join(', ')+', and '+b:b is also correct and 13 bytes shorter.

@IngoBürk that cuts the part that handles the comma having 2 items. Guess what? With 2 items the output is wrong.

@edc65 Ah, d'oh. May bad.

@edc65 Thanks -- I simultaneously knew and forgot that ()=> was a function definition, so simply pasting it in would have no effect. :/

JavaScript - 60 56 71 67 63
Not exactly an idiomatic approach, but I had fun writing it and I like regex.
Assuming the array is stored in var a:
a.join((a.length>2?',':'')+' ').replace(/([^,\s])$/,"and $1")

Shortened by simply checking for index [2]: (yay boolean coercion)
a.join((!!a[2]?',':'')+' ').replace(/([^,\s])$/,'and $1')

Apparently I suck at testing and skipped a single-entry test. Here's the fixed version:
a.join((!!a[2]?',':'')+' ').replace(/([^,\s])$/,(!!a[1]?'and ':'')+'$1')

Shaved off 2 chars by inverting my booleans and 3 more by moving the space from the concatenation into the then/else of the first ternary:
a.join((!a[2]?' ':', ')).replace(/([^,\s])$/,(!a[1]?'':'and ')+'$1')

Thanks to @tomsmeding for reminding me that I don't have to coerce my booleans because JS does that for me. I also realised I forgot to remove the parentheses separating the first ternary from the concatenation inside the join():
a.join(a[2]?', ':' ').replace(/([^,\s])$/,(a[1]?'and ':'')+'$1')

Did I do that right? Obligatory new golfer apology.

Liking regex is known as masochism.

Actually you didn't need the !! at all; a[2]?A:B works already. Might have to invert your booleans again.

@tomsmeding -- you are correct. I am always wary of JavaScript's default boolean coercion behaviour, so I have the borne-in habit of manually coercing my booleans...

@Adrian Correction: for any value but an empty string, a[i] equates to true. Well, almost. I'm assuming that if you get 2 inputs, your array has length two. Then a[2]===undefined and undefined evaluates to false. EDIT: your edit is what I meant :)

Excel VBA, 108 Bytes
Anonymous VBE immediate window function that takes input as space delimited array from range A1 and outputs to the VBE immediate window.
x=Split([A1]):y=UBound(x):For i=0To y-2:?x(i)", ";:Next:If y>0Then?x(i)IIf(y>1,",","")" and "x(i+1)Else?[A1]

Python 62 chars
Assuming that i is the list of strings:
(" and", ", and")[len(i) < 2].join(", ".join(i).rsplit(",",1))

C# 102 Chars
var i=m.Count(),l=i;if(l>2)l--;var r=string.Join(", ",m.Take(l));if(l!=i)r+=" and "+m.Last();return r;

Julia (53)
print(join(ARGS,", ",(endof(ARGS)>2?",":"")" and "))

Takes args from STDIN and outputs to STDOUT
Solution using Base.join(items, delim[, last])
Edit:
Test cases
julia oxfordComma.jl 1

1
julia oxfordComma.jl 1 2

1 and 2
julia oxfordComma.jl 1 2 3

1, 2, and 3

I don't know Julia, but this looks like it doesn't generate the Oxford comma.

@flornquake it does print with the Oxford comma, due to the optional "last" argument

It should be 1, 2, and 3, not 1, 2 and 3.

Racket 87
(define(f x)(string-join(map ~a x)", "#:before-last(if(= 2(length x))" and "", and ")))

I still find the function names in lisps to be way too long for golfing.

Rant (108)
[$[l:@b]:[r:each][s:[cmp:[rc];2;[is:different;,]]\s][before:[last:[notfirst:and\s]]][sync:;ordered][arg:b]]

Ungolfed:
[$[l:@b]:
    [r:each]                            # Repeat for each item
    [s:[cmp:[rc];2;[is:different;,]]\s] # Separate by comma if n > 2
    [before:[last:[notfirst:and\s]]]    # Insert "and" before last item
    [sync:;ordered]                     # Force forward order
    [arg:b]                             # Read list
]

Usage:
[$l:{A|B|C|D|E}]

Try it online

Pyth, 28
j>", "qlQ2+_t_Q+?"and "tQkeQ

Examples:
$ pyth programs/oxford.pyth <<< "['1']"
1

$ pyth programs/oxford.pyth <<< "['1','2']"
1 and 2

$ pyth programs/oxford.pyth <<< "['1','2','3']"
1, 2, and 3

I can't seem to figure out how the input should be formatted.

@Dennis I'll add some test cases.

I had actually tried that, but it didn't work with my version of Pyth (TypeError: can only concatenate list (not "str") to list). It works fine with the latest version.

@Dennis Yeah, the adding to list rule was added quite recently.

Haskell, 67 bytes
f[n]=n
f[m,n]=m++" and "++n
f n=(init n>>=(++", "))++"and "++last n

Abuses the list monad a bit
Explanation
Doing this later

Perl 5 + Moose, 70 bytes
sub english_list{@_<3?join" and ",@_:do{$_="and ".pop;join", ",@_,$_}}

Not many people seem to know it, but Moose, the popular OO framework for Perl 5, has a function to do this built in. (Moose uses it internally in its error messages, but exposes it as a documented, public function.)
my @l = (1 .. 3);
use Moose;
print Moose::Util::english_list(@l);

Excluding the definition of the list @l, that can be easily golfed down to 41 characters. If you allow the use of the say function which was introduced in Perl 5.10, you can knock off two more characters. (I'll leave it as an exercise for the reader.)
Now, looking at the definition of the english_list function itself, the best I've been able to golf it down to is 70 characters:
sub english_list{@_<3?join" and ",@_:do{$_="and ".pop;join", ",@_,$_}}

... though obviously by choosing a shorter function name, that could be reduced further. (59 characters if you choose a one-letter function name.)

Use perl -ane and use Moose;say Moose::Util::english_list(@F) but that is still 44 characters. You can use the same @F trick for your function.

You're missing a couple of tricks... say Moose'Util'english_list@F

Perl has anonymous functions, and those are acceptable answers here. You can just start with sub{, and not give it a name at all.

Groovy - 221 chars
This is not a compact implementation, but the usage is tight: it overrides toString() for ArrayList via meta-class functionality (and maps - no conditionals here!).
This is powerful stuff, but idiomatic when writing a framework. That is, the change is transparent to the client.
Golfed (assumes variable a is defined):
q={s->"'$s'"}
r={q a[it]}
f={"${it[0..-2].join ", "}, and ${it[-1]}"}
m=[:].withDefault{f}
m[0]={""}
m[1]={r 0}
m[2]={"${r 0} and ${r 1}"}
ArrayList.metaClass.toString={->m[delegate.size()].call(delegate.collect{q(it)})}

Sample assertions:
a=['oxford','cambridge','comma','space']
assert "'oxford', 'cambridge', 'comma', and 'space'" == a.toString()

a=['oxford','cambridge']
assert "'oxford' and 'cambridge'" == a.toString()

a=['oxford']
assert "'oxford'" == a.toString()

a=[]
assert "" == a.toString()

Ungolfed:
q = {s->"'$s'"}
r = {q a[it]}

f = {"${it[0..-2].join ", "}, and ${it[-1]}"}
m = [:].withDefault{f}
m[0] = {""}
m[1] = {r 0}
m[2] = {"${r 0} and ${r 1}"}

ArrayList.metaClass.toString = { ->
    m[ delegate.size() ].call( delegate.collect{q(it)} )
}

Python, 79 chars
Note: the char count does not include the list declaration.
l=['1','2','3']
print l[0] if len(l)<2 else (', '.join(l[:-1])+(',' if len(l)>2 else '')+' and '+l[-1])

Output for various inputs:
1
1 and 2
1, 2, and 3
...

i understand why you don't count the declaration (though that is the reason i'm personally against hardcoding input when op doesn't specifically say it's okay) but i'm interested in your justification for not counting print

@undergroundmonorail The title reads 'generating a string' and the specification reads 'should yield' with nothing said about printing said string.

Golfscript (61)
The fact that Javascript and others score better pretty much shows that this is probably not done very efficiently in terms of golfing.
.,.2={;' and '*}{(\{\(.{.)', '''if}{', and '}if@\+print}/;}if

Examples with link to try it out:

["1"] -> "1"
["1" "2"] -> "1 and 2"
["1" "2" "3"] -> "1, 2, and 3"

bash (79)
(($#<3))&&echo $1 ${2/#/and }||{ Y=${@/%/,};L=${@: -1};echo ${Y/%$L,/and $L}; }

Explaination
For 1 or 2 parameters

echo $1 and, if $2 exists, prefix $2 with "and ".

Otherwise

suffix all parameters with a comma and join together
get last parameter
replace "$L," with "and $L"

PHP, 67
if($c=count($a)-1)$a[$c]='and '.$a[$c];echo join($c-1?', ':' ',$a);

If there's more than one item, prepend the last with 'and '.  (store the count minus one in $c).
Next, join on space or comma space, depending on whether the count is two.
if ($c = count($a) - 1) {
    $a[$c] = 'and '.$a[$c];
}
echo join($c - 1 ? ', ' : ' ', $a);

SmileBASIC, 80 bytes
DEF L A
L=LEN(A)WHILE LEN(A)>1?SHIFT(A);","*(L>2);" ";
WEND?"and "*(L>1);A[0]END

Ruby, 44 bytes
->*f,l{f[0]?f*', '+(f[1]??,:'')+' and '+l:l}

Try it online!

authors: เสาวลักษณ์ พิมพ์เหลา