问:
Wolves and Chickens
There's a river and there are wolves and chickens on one side of the river. They have a raft and they all need to get to the other side. However, the raft cannot travel on its own. The raft will sink if more than two animals are on it. None of the animals want to get wet because the river's cold and dirty. None of the animals can jump or fly over the river. Also, if there are chickens on one side, there cannot be more wolves on that side than there are chickens on that side -- the wolves will then decide to eat the chickens. This means that you cannot take two wolves on the raft to a side with one chicken.

Your task is to make a program/function that takes a number of wolves and a number of chickens (greater than or equal to the number of wolves) as input and finds the smallest number of times the raft has to move across the river. If the task is not possible, the program/function should output/return an empty string. It will then print/return one method as to how this is done in the following way:

```<code>W if a wolf crosses the river on its own
C if a chicken crosses the river on its own
CW if a chicken and a wolf cross the river -- WC is also fine
CC if two chickens cross the river
WW if two wolves cross the river
</code>```

As you can deduce, the raft will automatically move in alternating directions (left and right, starting from left to right as the first one or two animals cross the river). This doesn't need to be outputted/returned. 'W', 'C', 'CW', 'CC' or 'WW' in the output may be separated by at least one of the following:

```<code>spaces (' ')
commas (',')
newlines
</code>```

Alternatively, you may store the directions as items in a list (an empty list means no solution).

Test cases (output separated by commas -- input takes the form wolves,chickens):

```<code>1,1 -> CW

2,2 -> CW,C,CC,C,CW

1,2 -> CW,W,CW

0,10 -> CC,C,CC,C,CC,C,CC,C,CC,C,CC,C,CC,C,CC,C,CC

3,2 -> no solution
</code>```

Try to make your code as short in bytes as possible.

答:
JavaScript (ES6), <s>251</s> <s>264</s> ... <s>244</s> 240 bytes

Takes the number of wolves and chickens (w, c) and returns one of the optimal solutions, or undefined if there's no solution.

(w,c,v={},B=1/0,S)=>(r=(s,w,c,W=0,C=0,d=1,N=0,k=w+'|'+c+d)=>v[k]|c*w>c*c|C*W>C*C|w<0|c<0|W<0|C<0?0:w|c?[v[k]=1,2,4,8,5].map(n=>r(s+'C'.repeat(b=n>>2)+'W'.repeat(a=n&3)+' ',w-d*a,c-d*b,W+d*a,C+d*b,-d,N+1))&(v[k]=0):N<B&&(B=N,S=s))('',w,c)||S
```

<h3>Formatted and commented</h3>

<p>Wrapper function:</p>

<pre class="lang-js prettyprint-override"><code>(                                    // given:
  w,                                 // - w : # of wolves
  c,                                 // - c : # of chickens
  v = {},                            // - v : object keeping track of visited nodes
  B = 1 / 0,                         // - B : length of best solution
  S                                  // - S : best solution
) => (                               //
r = (...) => ...                     // process recursive calls (see below)
)('', w, c) || S                     // return the best solution
</code>```

Main recursive function:

r = (                                // given:
  s,                                 // - s : current solution (as text)
  w, c,                              // - w/c : # of chickens/wolves on the left side
  W = 0, C = 0,                      // - W/C : # of chickens/wolves on the right side
  d = 1,                             // - d : direction (1:left to right, -1:right to left)
  N = 0,                             // - N : length of current solution
  k = w + '|' + c + d                // - k : key identifying the current node
) =>                                 //
v[k] |                               // abort if this node was already visited
c * w > c * c | C * W > C * C |      // or there are more wolves than chickens somewhere
w < 0 | c < 0 | W < 0 | C < 0 ?      // or we have created antimatter animals
  0                                  //
:                                    // else:
  w | c ?                            //   if there are still animals on the left side:
    [v[k] = 1, 2, 4, 8, 5].map(n =>  //     set node as visited and do a recursive call
      r(                             //     for each combination: W, WW, C, CC and CW
        s + 'C'.repeat(b = n >> 2) + //     append used combination to current solution
        'W'.repeat(a = n & 3) + ' ', //     wolves = bits 0-1 of n / chickens = bits 2-3
        w - d * a,                   //     update wolves on the left side
        c - d * b,                   //     update chickens on the left side
        W + d * a,                   //     update wolves on the right side
        C + d * b,                   //     update chickens on the right side
        -d,                          //     use opposite direction for the next turn
        N + 1                        //     increment length of current solution
      )                              //
    ) &                              //     once we're done,
    (v[k] = 0)                       //     set this node back to 'not visited'
  :                                  //   else:
    N < B &&                         //     save this solution if it's shorter than the
    (B = N, S = s)                   //     best solution encountered so far
```

<h3>Test cases</h3>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let f =

(w,c,v={},B=1/0,S)=>(r=(s,w,c,W=0,C=0,d=1,N=0,k=w+'|'+c+d)=>v[k]|c*w>c*c|C*W>C*C|w<0|c<0|W<0|C<0?0:w|c?[v[k]=1,2,4,8,5].map(n=>r(s+'C'.repeat(b=n>>2)+'W'.repeat(a=n&3)+' ',w-d*a,c-d*b,W+d*a,C+d*b,-d,N+1))&(v[k]=0):N<B&&(B=N,S=s))('',w,c)||S

console.log(f(1, 1));
console.log(f(2, 2));
console.log(f(1, 2));
console.log(f(0, 10));
console.log(f(3, 2));</code>```

Title: Wolves and Chickens

Body:
JavaScript (ES6), <s>251</s> <s>264</s> ... <s>244</s> 240 bytes

Takes the number of wolves and chickens (w, c) and returns one of the optimal solutions, or undefined if there's no solution.

(w,c,v={},B=1/0,S)=>(r=(s,w,c,W=0,C=0,d=1,N=0,k=w+'|'+c+d)=>v[k]|c*w>c*c|C*W>C*C|w<0|c<0|W<0|C<0?0:w|c?[v[k]=1,2,4,8,5].map(n=>r(s+'C'.repeat(b=n>>2)+'W'.repeat(a=n&3)+' ',w-d*a,c-d*b,W+d*a,C+d*b,-d,N+1))&(v[k]=0):N<B&&(B=N,S=s))('',w,c)||S

Formatted and commented

Wrapper function:

(                                    // given:
  w,                                 // - w : # of wolves
  c,                                 // - c : # of chickens
  v = {},                            // - v : object keeping track of visited nodes
  B = 1 / 0,                         // - B : length of best solution
  S                                  // - S : best solution
) => (                               //
r = (...) => ...                     // process recursive calls (see below)
)('', w, c) || S                     // return the best solution

Main recursive function:

r = (                                // given:
  s,                                 // - s : current solution (as text)
  w, c,                              // - w/c : # of chickens/wolves on the left side
  W = 0, C = 0,                      // - W/C : # of chickens/wolves on the right side
  d = 1,                             // - d : direction (1:left to right, -1:right to left)
  N = 0,                             // - N : length of current solution
  k = w + '|' + c + d                // - k : key identifying the current node
) =>                                 //
v[k] |                               // abort if this node was already visited
c * w > c * c | C * W > C * C |      // or there are more wolves than chickens somewhere
w < 0 | c < 0 | W < 0 | C < 0 ?      // or we have created antimatter animals
  0                                  //
:                                    // else:
  w | c ?                            //   if there are still animals on the left side:
    [v[k] = 1, 2, 4, 8, 5].map(n =>  //     set node as visited and do a recursive call
      r(                             //     for each combination: W, WW, C, CC and CW
        s + 'C'.repeat(b = n >> 2) + //     append used combination to current solution
        'W'.repeat(a = n & 3) + ' ', //     wolves = bits 0-1 of n / chickens = bits 2-3
        w - d * a,                   //     update wolves on the left side
        c - d * b,                   //     update chickens on the left side
        W + d * a,                   //     update wolves on the right side
        C + d * b,                   //     update chickens on the right side
        -d,                          //     use opposite direction for the next turn
        N + 1                        //     increment length of current solution
      )                              //
    ) &                              //     once we're done,
    (v[k] = 0)                       //     set this node back to 'not visited'
  :                                  //   else:
    N < B &&                         //     save this solution if it's shorter than the
    (B = N, S = s)                   //     best solution encountered so far

Test cases

let f =

(w,c,v={},B=1/0,S)=>(r=(s,w,c,W=0,C=0,d=1,N=0,k=w+'|'+c+d)=>v[k]|c*w>c*c|C*W>C*C|w<0|c<0|W<0|C<0?0:w|c?[v[k]=1,2,4,8,5].map(n=>r(s+'C'.repeat(b=n>>2)+'W'.repeat(a=n&3)+' ',w-d*a,c-d*b,W+d*a,C+d*b,-d,N+1))&(v[k]=0):N<B&&(B=N,S=s))('',w,c)||S

console.log(f(1, 1));
console.log(f(2, 2));
console.log(f(1, 2));
console.log(f(0, 10));
console.log(f(3, 2));


问:
Tips for golfing in Ruby
What general tips can you give for golfing in Ruby?

I'm looking for ideas that can be applied to code golf problems in general that are specific to Ruby. (For example, "Remove comments" would not be an answer.)

Please post one tip per answer.

答:
Save some bytes when removing repeated elements of an array

a.uniq # before
a|[]   # after
    ^^
```

<p>If you will be using an empty array <code>[]</code> in a variable, you can save even more bytes:</p>

<pre class="lang-rb prettyprint-override"><code>a.uniq;b=[] # before
a|b=[]      # after
      ^^^^^
</code>```

ContentLicense: CC BY-SA 3.0

Title: Tips for golfing in Ruby

Body:
Save some bytes when removing repeated elements of an array

a.uniq # before
a|[]   # after
    ^^

If you will be using an empty array [] in a variable, you can save even more bytes:

a.uniq;b=[] # before
a|b=[]      # after
      ^^^^^


答:
Save a byte when printing a word with symbols

This is a bit situational, but every byte counts!

```<code>puts"thing" # before
puts:thing  # after
          ^
</code>```

Title: Tips for golfing in Ruby

Body:
What general tips can you give for golfing in Ruby?

I'm looking for ideas that can be applied to code golf problems in general that are specific to Ruby. (For example, "Remove comments" would not be an answer.)

Please post one tip per answer.

Body:
Save a byte when printing a word with symbols

This is a bit situational, but every byte counts!

puts"thing" # before
puts:thing  # after
          ^


问:
Sieve of Eratosthenes, Step by Step
Given a number N, draw a left aligned NxN board of numbers, leaving 1 blank (as a space) (I will show diagrams with N=5)

```<code>   2  3  4  5
6  7  8  9  10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
</code>```

Your job is to construct the Sieve of Eratosthenes, step by step. First, start with 2. It's prime, so leave it there, and replace all other numbers divisible by 2 with the proper number of spaces.

```<code>   2  3     5
   7     9
11    13    15
   17    19
21    23    25
</code>```

Next, go to the next unprinted number (3 in this case) and do the same.

```<code>   2  3     5
   7
11    13
   17    19
      23    25
</code>```

And so on, until you reach N.

You need to first print the complete grid, and every time you go to a new number, print the board with the multiples removed. Make sure you print a blank line in between!

Examples

Text in parenthesis () are just for reference, you don't need to print it

N = 2:

```<code>  2 (complete grid)
3 4

  2 (remove multiples of 2)
3
</code>```

N = 3:

```<code>  2 3 (complete grid)
4 5 6
7 8 9

  2 3 (remove multiples of 2)
  5
7   9

  2 3 (remove multiples of 3)
  5
7
</code>```

Remember, this is code-golf, so the code with the smallest number of bytes wins.

Title: Sieve of Eratosthenes, Step by Step

Body:
PHP, <s>155</s> <s>150</s> <s>147</s> <s>145</s> <s>142</s> 140 bytes

for(;$k++<$n=$argv[1];)if($k<2||$a[$k]){for($i=0;$i++<$n*$n;)echo$a[$i]=$k>1?$i>$k&$i%$k<1?"":$a[$i]:($i<2?"":$i),"\t\n"[$i%$n<1];echo"\n";}

breakdown

for(;$k++<$n=$argv[1];)
    if($k<2||$a[$k])    // if first iteration or number unprinted ...
{
    for($i=0;$i++<$n*$n;)
        echo
            $a[$i]=$k>1
                ?$i>$k&$i%$k<1
                    ?""         // sieve
                    :$a[$i]     // or copy value
                :($i<2?"":$i)   // first iteration: init grid
            ,
            // append tab, linebreak every $n columns
            "\t\n"[$i%$n<1]
        ;
    // blank line after each iteration
    echo"\n";
}


问:
A penny saved is a penny

...counted!

You will pass your program a variable which represents a quantity of money in dollars and/or cents and an array of coin values.  Your challenge is to output the number of possible combinations of the given array of coin values that would add up to the amount passed to the code.  If it is not possible with the coins named, the program should return 0.

Note on American numismatic terminology:

1-cent coin: penny

5-cent coin: nickel

10-cent coin: dime

25-cent coin: quarter (quarter dollar)

Example 1:

Program is passed:

```<code>12, [1, 5, 10]
</code>```

(12 cents)

Output:

```<code>4
</code>```

There are 4 possible ways of combining the coins named to produce 12 cents:

12 pennies

1 nickel and 7 pennies

2 nickels and 2 pennies

1 dime and 2 pennies

Example 2:

Program is passed:

```<code>26, [1, 5, 10, 25]
</code>```

(26 cents)

Output:

```<code>13
</code>```

There are 13 possible ways of combining the coins named to produce 26 cents:

26 pennies

21 pennies and 1 nickel

16 pennies and 2 nickels

11 pennies and 3 nickels

6 pennies and 4 nickels

1 penny and 5 nickels

16 pennies and 1 dime

6 pennies and 2 dimes

11 pennies, 1 dime, and 1 nickel

6 pennies, 1 dime, and 2 nickels

1 penny, 1 dime, and 3 nickels

1 penny, 2 dimes, and 1 nickel

1 quarter and 1 penny

Example 3:

Program is passed:

```<code>19, [2, 7, 12]
</code>```

Output:

```<code>2
</code>```

There are 2 possible ways of combining the coins named to produce 19 cents:

1 12-cent coin and 1 7-cent coin

1 7-cent coin and 6 2-cent coins

Example 4:

Program is passed:

```<code>13, [2, 8, 25]
</code>```

Output:

```<code>0
</code>```

There are no possible ways of combining the coins named to produce 13 cents.

This has been through the Sandbox.  Standard loopholes apply.  This is code golf, so the answer with the fewest bytes wins.

答:
R, <s>81</s> <s>76</s> 63 bytes

Thanks to @rturnbull for golfing away 13 bytes!

```<code>function(u,v)sum(t(t(expand.grid(lapply(u/v,seq,f=0))))%*%v==u)
</code>```

Example (note that c(...) is how you pass vectors of values to R):

```<code>f(12,c(1,5,10))
[1] 4
</code>```

Explanation:

u is the desired value, v is the vector of coin values.

```<code>expand.grid(lapply(u/v,seq,from=0))
</code>```

creates a data frame with every possible combination of 0 to k coins (k depends on the denomination), where k is the lowest such that k times the value of that coin is at least u (the value to achieve).

Normally we would use as.matrix to turns that into a matrix, but that is many characters. Instead we take the transpose of the transpose (!) which automatically coerces it, but takes fewer characters.

%*% v then calculates the monetary value of each row. The last step is to count how many of those values are equal to the desired value u.

Note that the computational complexity and memory requirements of this are horrific but hey, it's code golf.

Title: A penny saved is a penny

Body:
R, <s>81</s> <s>76</s> 63 bytes

Thanks to @rturnbull for golfing away 13 bytes!

function(u,v)sum(t(t(expand.grid(lapply(u/v,seq,f=0))))%*%v==u)

Example (note that c(...) is how you pass vectors of values to R):

f(12,c(1,5,10))
[1] 4

Explanation:

u is the desired value, v is the vector of coin values.

expand.grid(lapply(u/v,seq,from=0))

creates a data frame with every possible combination of 0 to k coins (k depends on the denomination), where k is the lowest such that k times the value of that coin is at least u (the value to achieve).

Normally we would use as.matrix to turns that into a matrix, but that is many characters. Instead we take the transpose of the transpose (!) which automatically coerces it, but takes fewer characters.

%*% v then calculates the monetary value of each row. The last step is to count how many of those values are equal to the desired value u.

Note that the computational complexity and memory requirements of this are horrific but hey, it's code golf.


问:
Tips for golfing in R
I'm looking for tips for golfing in the R statistical language.  R is perhaps an unconventional choice for Golf.  However, it does certain things very compactly (sequences, randomness, vectors, and lists), many of the built-in functions have very short names, and it has an optional line terminator (;).  What tips and tricks can you give to help solve code golf problems in R?</p>

答:
Some very specific golfing tips:

if you need to extract the length of a vector, sum(x|1) is shorter than length(x) as long as x is numeric, integer, complex or logical.

if you need to extract the last element of a vector, it may be cheaper (if possible) to initialise the vector backwards using rev() and then calling x[1] rather than x[length(x)] (or using the above tip, x[sum(x|1)]) (or tail(x,1) --- thanks Giuseppe!). A slight variation on this (where the second-last element was desired) can be seen here. Even if you can't initialise the vector backwards, rev(x)[1] is still shorter than x[sum(x|1)] (and it works for character vectors too). Sometimes you don't even need rev, for example using n:1 instead of 1:n.

(As seen here). If you want to coerce a data frame to a matrix, don't use as.matrix(x). Take the transpose of the transpose, t(t(x)).

if is a formal function. For example, "if"(x<y,2,3) is shorter than if(x<y)2 else 3 (though of course, 3-(x<y) is shorter than either). This only saves characters if you don't need an extra pair of braces to formulate it this way, which you often do.

For testing non-equality of numeric objects, if(x-y) is shorter than if(x!=y). Any nonzero numeric is regarded as TRUE. If you are testing equality, say, if(x==y)a else b then try if(x-y)b else a instead. Also see the previous point.

The function el is useful when you need to extract an item from a list. The most common example is probably strsplit: el(strsplit(x,"")) is one fewer byte than strsplit(x,"")[[1]].

(As used here) Vector extension can save you characters: if vector v has length n you can assign into v[n+1] without error. For example, if you wanted to print the first ten factorials you could do: v=1;for(i in 2:10)v[i]=v[i-1]*i rather than v=1:10:for(...) (though as always, there is another, better, way: cumprod(1:10))

Sometimes, for text based challenges (particularly 2-D ones), it's easier to plot the text rather than cat it. the argument pch= to plot controls which characters are plotted. This can be shortened to pc= (which will also give a warning) to save a byte. Example here.

To take the floor of a number, don't use floor(x). Use x%/%1 instead.

To test if the elements of a numeric or integer vector are all equal, you can often use sd rather than something verbose such as all.equal. If all the elements are the same, their standard deviation is zero (FALSE) else the standard deviation is positive (TRUE). Example here.

Some functions which you would expect to require integer input actually don't. For example, seq(3.5) will return 1 2 3 (the same is true for the : operator). This can avoid calls to floor and sometimes means you can use / instead of %/%.

The most common function for text output is cat. But if you needed to use print for some reason, then you might be able to save a character by using show instead (which in most circumstances just calls print anyway though you forego any extra arguments like digits)

don't forget about complex numbers! The functions to operate on them (Re, Im, Mod, Arg) have quite short names which can occasionally be useful, and complex numbers as a concept can sometimes yield simple solutions to some calculations.

for functions with very long names (>13–15 characters), you can use get to get at the function. For example, in R 3.4.4 with no packages loaded other than the default, get(ls(9)[501]) is more economical than getDLLRegisteredRoutines. This can also get around source code restrictions such as this answer. Note that using this trick makes your code R-version-dependent (and perhaps platform dependent), so make sure you include the version in your header so it can be reproduced if necessary.

Title: Tips for golfing in R

ContentLicense: CC BY-SA 4.0


答:
Some basic concepts but should be somewhat useful:

In control flow statements you can abuse that any number not equal to zero will be evaluated as TRUE, e.g.: if(x) is equivalent to if(x!=0). Conversely, if(!x) is equivalent to if(x==0).

When generating sequences using : (e.g. 1:5) one can abuse the fact that the exponentiation operator ^ is the only operator that has precedence over the :-operator (as opposed to +-*/).

```<code>1:2^2 => 1 2 3 4
</code>```

which saves you two bytes on the parentheses that you would normally have to use in case you wanted to e.g. loop over the elements of an n x n matrix (1:n^2) or any other integer that can be expressed in a shorter manner using exponential notation (1:10^6).

A related trick can of course be used on the vectorized operations as well +-*/, although most commonly applicaple to +-:

```<code>for(i in 1:(n+1)) can instead be written as for(i in 0:n+1)
</code>```

This works because +1is vectorized and adds 1 to each element of 0:n resulting in the vector 1 2 ... n+1. Similarly 0:(n+1) == -1:n+1 saves you one byte as well.

When writing short functions (that can be expressed on one line), one can abuse variable assignment to save two bytes on the enclosing curly brackets {...}:

```<code>f=function(n,l=length(n))for(i in 1:l)cat(i*l,"\n")
f=function(n){l=length(n);for(i in 1:l)cat(i*l,"\n")}
</code>```

Note that this might not always comply to rules of certain challenges.

Title: Tips for golfing in R

Body: I'm looking for tips for golfing in the R statistical language.  R is perhaps an unconventional choice for Golf.  However, it does certain things very compactly (sequences, randomness, vectors, and lists), many of the built-in functions have very short names, and it has an optional line terminator (;).  What tips and tricks can you give to help solve code golf problems in R?</p>

Body:
Some basic concepts but should be somewhat useful:

In control flow statements you can abuse that any number not equal to zero will be evaluated as TRUE, e.g.: if(x) is equivalent to if(x!=0). Conversely, if(!x) is equivalent to if(x==0).

When generating sequences using : (e.g. 1:5) one can abuse the fact that the exponentiation operator ^ is the only operator that has precedence over the :-operator (as opposed to +-*/).

1:2^2 => 1 2 3 4

which saves you two bytes on the parentheses that you would normally have to use in case you wanted to e.g. loop over the elements of an n x n matrix (1:n^2) or any other integer that can be expressed in a shorter manner using exponential notation (1:10^6).

A related trick can of course be used on the vectorized operations as well +-*/, although most commonly applicaple to +-:

for(i in 1:(n+1)) can instead be written as for(i in 0:n+1)

This works because +1is vectorized and adds 1 to each element of 0:n resulting in the vector 1 2 ... n+1. Similarly 0:(n+1) == -1:n+1 saves you one byte as well.

When writing short functions (that can be expressed on one line), one can abuse variable assignment to save two bytes on the enclosing curly brackets {...}:

f=function(n,l=length(n))for(i in 1:l)cat(i*l,"\n")
f=function(n){l=length(n);for(i in 1:l)cat(i*l,"\n")}

Note that this might not always comply to rules of certain challenges.


问:
Maximal number of regions obtained by joining n points around a circle by straight lines
Let's define f(n) as the maximal number of regions obtained by joining n points around a circle by straight lines. For example, two points would split the circle into two pieces, three into four, like this:

Make sure when you are drawing the lines, you don't have an intersection of more than two lines.

Your task

Given a number n, print f(n).

Test cases:

```<code> n | f(n)
---+-----
 1 |   1
 2 |   2
 3 |   4
 4 |   8
 5 |  16
 6 |  31
 7 |  57
 8 |  99
 9 | 163
</code>```

You can see more here.

Using built-in sequence generators is not allowed.

Remember, this is code-golf, so the code with the smallest number of bytes wins.

If you guys want the formula, here it is:

答:
R, 25 bytes

```<code>sum(choose(scan(),0:2*2))
</code>```

scan() takes the input n from stdin, which is passed to choose along with 0:2*2. This latter term is 0 to 2 (i.e. [0, 1, 2]) multiplied by 2, which is [0, 2, 4]. Since choose is vectorized, this calculates n choose 0, n choose 2, n choose 4, and returns them in a list. Finally, sum returns the sum of these numbers, surprisingly enough.

I don't think that this can be golfed further but I would be very happy to be proven wrong!

Body:
R, 25 bytes

sum(choose(scan(),0:2*2))

scan() takes the input n from stdin, which is passed to choose along with 0:2*2. This latter term is 0 to 2 (i.e. [0, 1, 2]) multiplied by 2, which is [0, 2, 4]. Since choose is vectorized, this calculates n choose 0, n choose 2, n choose 4, and returns them in a list. Finally, sum returns the sum of these numbers, surprisingly enough.

I don't think that this can be golfed further but I would be very happy to be proven wrong!


答:
TSQL, 105 bytes

This can only handle up to one dollar with these 4 coin types. The ungolfed version can handle up to around 4 dollars, but very slow - on my box this takes 27 seconds. Result is 10045 combinations b.t.w.

Golfed:

```<code>DECLARE @ INT = 100
DECLARE @t table(z int)
INSERT @t values(1),(5),(10),(25)
;WITH c as(SELECT 0l,0s UNION ALL SELECT z,s+z FROM c,@t WHERE l<=z and s<@)SELECT SUM(1)FROM c WHERE s=@
</code>```

Ungolfed:

```<code>-- input variables
DECLARE @ INT = 100
DECLARE @t table(z int)
INSERT @t values(1),(5),(10),(25)

-- query
;WITH c as
(
  SELECT 0l,0s
  UNION ALL
  SELECT z,s+z
  FROM c,@t
  WHERE l<=z and s<@
)
SELECT SUM(1)
FROM c
WHERE s=@
-- to allow more than 100 recursions(amounts higher than 1 dollar in this example)
OPTION(MAXRECURSION 0)
</code>```

Fiddle

Title: A penny saved is a penny

Body:
...counted!

You will pass your program a variable which represents a quantity of money in dollars and/or cents and an array of coin values.  Your challenge is to output the number of possible combinations of the given array of coin values that would add up to the amount passed to the code.  If it is not possible with the coins named, the program should return 0.

Note on American numismatic terminology:

1-cent coin: penny

5-cent coin: nickel

10-cent coin: dime

25-cent coin: quarter (quarter dollar)

Example 1:

Program is passed:

```<code>12, [1, 5, 10]
</code>```

(12 cents)

Output:

```<code>4
</code>```

There are 4 possible ways of combining the coins named to produce 12 cents:

12 pennies

1 nickel and 7 pennies

2 nickels and 2 pennies

1 dime and 2 pennies

Example 2:

Program is passed:

```<code>26, [1, 5, 10, 25]
</code>```

(26 cents)

Output:

```<code>13
</code>```

There are 13 possible ways of combining the coins named to produce 26 cents:

26 pennies

21 pennies and 1 nickel

16 pennies and 2 nickels

11 pennies and 3 nickels

6 pennies and 4 nickels

1 penny and 5 nickels

16 pennies and 1 dime

6 pennies and 2 dimes

11 pennies, 1 dime, and 1 nickel

6 pennies, 1 dime, and 2 nickels

1 penny, 1 dime, and 3 nickels

1 penny, 2 dimes, and 1 nickel

1 quarter and 1 penny

Example 3:

Program is passed:

```<code>19, [2, 7, 12]
</code>```

Output:

```<code>2
</code>```

There are 2 possible ways of combining the coins named to produce 19 cents:

1 12-cent coin and 1 7-cent coin

1 7-cent coin and 6 2-cent coins

Example 4:

Program is passed:

```<code>13, [2, 8, 25]
</code>```

Output:

```<code>0
</code>```

There are no possible ways of combining the coins named to produce 13 cents.

This has been through the Sandbox.  Standard loopholes apply.  This is code golf, so the answer with the fewest bytes wins.

Body:
TSQL, 105 bytes

This can only handle up to one dollar with these 4 coin types. The ungolfed version can handle up to around 4 dollars, but very slow - on my box this takes 27 seconds. Result is 10045 combinations b.t.w.

Golfed:

DECLARE @ INT = 100
DECLARE @t table(z int)
INSERT @t values(1),(5),(10),(25)
;WITH c as(SELECT 0l,0s UNION ALL SELECT z,s+z FROM c,@t WHERE l<=z and s<@)SELECT SUM(1)FROM c WHERE s=@

Ungolfed:

-- input variables
DECLARE @ INT = 100
DECLARE @t table(z int)
INSERT @t values(1),(5),(10),(25)

-- query
;WITH c as
(
  SELECT 0l,0s
  UNION ALL
  SELECT z,s+z
  FROM c,@t
  WHERE l<=z and s<@
)
SELECT SUM(1)
FROM c
WHERE s=@
-- to allow more than 100 recursions(amounts higher than 1 dollar in this example)
OPTION(MAXRECURSION 0)

Fiddle


问:
N(e(s(t))) a string
To "function nest" a string, you must:

Treat the first character as a function, and the following characters as the arguments to that function. For example, if the input string was Hello, then the first step would be:

```<code>H(ello)
</code>```

Then, repeat this same step for every substring. So we get:

```<code>H(ello)
H(e(llo))
H(e(l(lo)))
H(e(l(l(o))))
</code>```

Your task is to write a program or function that "function nests" a string. For example, if the input string was Hello world!, then you should output:

```<code>H(e(l(l(o( (w(o(r(l(d(!)))))))))))
</code>```

The input will only ever contain printable ASCII, and you may take the input and the output in any reasonable format. For example, STDIN/STDOUT, function arguments and return value, reading and writing to a file, etc.

For simplicity's sake, you may also assume the input will not contain parentheses, and will not be empty.

```<code>Input:
Nest a string
Output:
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))

Input:
foobar
Output:
f(o(o(b(a(r)))))

Input:
1234567890
Output:
1(2(3(4(5(6(7(8(9(0)))))))))

Input:
code-golf
Output:
c(o(d(e(-(g(o(l(f))))))))

Input:
a
Output:
a

Input:
42
Output:
4(2)
</code>```

As usual, all of our default rules and loopholes apply, and the shortest answer scored in bytes wins!

答:
Python 50 49 bytes

saved 1 byte (actually 3) thanks to @ETHproductions

This is my recursive version written in Python. Would probably be shorter the iterative aproach.. but I simply like recursion :)

```<code>F=lambda s:s[0]+'('+F(s[1:])+')'if len(s)>1else s
</code>```

Title: N(e(s(t))) a string

Body:
Python 50 49 bytes

saved 1 byte (actually 3) thanks to @ETHproductions

This is my recursive version written in Python. Would probably be shorter the iterative aproach.. but I simply like recursion :)

F=lambda s:s[0]+'('+F(s[1:])+')'if len(s)>1else s


答:
Scala, 35 bytes

```<code>(n:Int)=>(n*n*(n-6)+23*n-18)*n/24+1
</code>```

Uses the same formula as numberknot's java answer.

Title: Maximal number of regions obtained by joining n points around a circle by straight lines

Body:
Let's define f(n) as the maximal number of regions obtained by joining n points around a circle by straight lines. For example, two points would split the circle into two pieces, three into four, like this:

Make sure when you are drawing the lines, you don't have an intersection of more than two lines.

Your task

Given a number n, print f(n).

Test cases:

```<code> n | f(n)
---+-----
 1 |   1
 2 |   2
 3 |   4
 4 |   8
 5 |  16
 6 |  31
 7 |  57
 8 |  99
 9 | 163
</code>```

You can see more here.

Using built-in sequence generators is not allowed.

Remember, this is code-golf, so the code with the smallest number of bytes wins.

If you guys want the formula, here it is:

Body:
Scala, 35 bytes

(n:Int)=>(n*n*(n-6)+23*n-18)*n/24+1

Uses the same formula as numberknot's java answer.


问:
Find the follow sets
The challenge below requires you to be familiar with formal parser theory. If you don't know what the question is asking because you don't know what the terms mean, context-free grammars and first/follow sets are covered in a lot of university courses.

I can recommend this Stanford course, in particular handouts 08 and 09 (from page 7). I've extracted also extracted a cheat sheet from these handouts  - I recommend anyone attempting this challenge to read it.

Write a program or function that given a context-free grammar finds the follow set of every nonterminal. Informally, the follow set of a nonterminal is a set of terminals and $ (meaning end-of-input) that you can possibly find after that terminal in a valid sentence.

The input is given as a single printable ASCII string or array of printable ASCII lines. You may output the sets in any reasonable format, using $ (either as literal output, or string inside a set, etc) to indicate the end of input. You may assume that the input is always valid according to the format below.

The context free grammar is given in a very simplified manner. Every line contains a single production. Every production is a space separated list of symbols. A terminal is a string of characters surrounded by apostrophes (e.g. '**'). For simplicity you may assume that terminals do not contain spaces, but it would be nice if your program allows it. A nonterminal may be any string not containing spaces or $. The empty production (normally indicated with ε) is simply a line containing only the left hand side nonterminal. The first line is the production defining the start symbol.

As an example, the following grammar:

S → aSa | bSb | ε

Will be given as:

```<code>S 'a' S 'a'
S 'b' S 'b'
S
</code>```

Example input / outputs:

```<code>In:
S 'a' S 'a'
S 'b' S 'b'
S

Out:
S {'a', 'b', $}

In:
S A B C
A 'a'
A C 'b'
A
B C
B 'd' A
B
C 'e'
C 'f'

Out:
S {$}
A {'d', 'e', 'f'}
B {'e', 'f'}
C {'b', 'e', 'f', $}

In:
Start Alice Bob
Alice Charlie 'a'
Alice
Bob Bob 'a' Alice Charlie
Bob '!!!'
Charlie 'b'
Charlie

Out:
Start {$}
Alice {'a', '!!!', 'b', $}
Bob {'a', $}
Charlie {'a', $}
</code>```

Shortest code in bytes wins.

答:
Perl, 257 bytes

Includes +4 for -0p

Give grammar on STDIN (without trailing spaces. Make sure to remove the extra space in the second example). Assumes non-terminal names only contain letters, digits and _. Uses # instead of $ to indicate end of input. Can handle literals containing spaces

```<code>perl -M5.010 follow.pl
E T e
e '+' T e
e
T F t
t '*' F t
t
F '(' E ')'
F 'id'
^D
</code>```

Outputs the follow sets as a list of non-terminal literal in no particular order. For the example above it outputs:

```<code>F ')'
F #
t ')'
t #
T ')'
T #
F '+'
t '+'
T '+'
F '*'
e ')'
e #
E ')'
E #
</code>```

follow.pl:

```<code>#!/usr/bin/perl -0n
s/'.*?'/~$&/eg;s% (?=(\w.*\n))%$_.=">$1"%reg;/\s/;$_.=">$` #\n";s%^((\w+)\K ?\S*).*%$s{$1}++||"\$a.=s/ $2\\b/$&/rg"%eemgr,s%^(\w+ ).*?(\w+)$%"\$a.=s/>$1/>$2 /rg"%eermg,$_.=$a,s%>.*\xd8\K .*%%g,s%.+\n%$&x!/\n$&/g%eg until$$_++;s/\xd8.*?\xd8/~$&/eg;say/>(\w+ \W\S*\n)/g
</code>```

Works as shown, but replace \xd8 and \n by their literal versions to get the claimed score.

It should be possible to improve this since converting the first sets to the follow sets is currently very awkward.

Title: Find the follow sets

Body:
Perl, 257 bytes

Includes +4 for -0p

Give grammar on STDIN (without trailing spaces. Make sure to remove the extra space in the second example). Assumes non-terminal names only contain letters, digits and _. Uses # instead of $ to indicate end of input. Can handle literals containing spaces

perl -M5.010 follow.pl
E T e
e '+' T e
e
T F t
t '*' F t
t
F '(' E ')'
F 'id'
^D

Outputs the follow sets as a list of non-terminal literal in no particular order. For the example above it outputs:

F ')'
F #
t ')'
t #
T ')'
T #
F '+'
t '+'
T '+'
F '*'
e ')'
e #
E ')'
E #

follow.pl:

#!/usr/bin/perl -0n
s/'.*?'/~$&/eg;s% (?=(\w.*\n))%$_.=">$1"%reg;/\s/;$_.=">$` #\n";s%^((\w+)\K ?\S*).*%$s{$1}++||"\$a.=s/ $2\\b/$&/rg"%eemgr,s%^(\w+ ).*?(\w+)$%"\$a.=s/>$1/>$2 /rg"%eermg,$_.=$a,s%>.*\xd8\K .*%%g,s%.+\n%$&x!/\n$&/g%eg until$$_++;s/\xd8.*?\xd8/~$&/eg;say/>(\w+ \W\S*\n)/g

Works as shown, but replace \xd8 and \n by their literal versions to get the claimed score.

It should be possible to improve this since converting the first sets to the follow sets is currently very awkward.


问:
Find the maximum deviation
This problem is "inspired" from a question that was originally asked on Quora (not for code golfing). I just want to make it a challenge for you guys (and my first problem submission here).

Given an array of integer elements v and an integer d (we assume that d is lower or equal to the array's length), consider all the sequences of d consecutive elements in the array. For each sequence, compute the difference between the maximum and minimum value of the elements in that sequence and name it the deviation.

Your task is to write a program or function that computes the maximum value among all deviations of all the sequences considered above, and return or output that value.

Worked-through Example:

```<code>v: (6,9,4,7,4,1)
d: 3

The sequences of length 3 are:
6,9,4 with deviation 5
9,4,7 with deviation 5
4,7,4 with deviation 3
7,4,1 with deviation 6

Thus the maximal deviation is 6, so the output is 6.
</code>```

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

答:
Python, 60 bytes

Saving 5 bytes thanks to Neil

f=lambda v,d:v and max(max(v[:d])-min(v[:d]),f(v[1:],d))or 0
```
<p>My first recursive lambda!</p>
<p>Usage:</p>
<pre class="lang-python prettyprint-override"><code>print f([6,9,4,7,4,1], 3)
</code>```

Title: Find the maximum deviation

Body:
Python, 60 bytes

Saving 5 bytes thanks to Neil

f=lambda v,d:v and max(max(v[:d])-min(v[:d]),f(v[1:],d))or 0

My first recursive lambda!

Usage:

print f([6,9,4,7,4,1], 3)


答:
05AB1E, <s>12</s> 10 bytes

Uses CP-1252 encoding.

```<code>Œù€{øÀ`-ÄZ
</code>```

Try it online!

Explanation

```<code>Œ              # sublists of v
 ù             # of length d
  €{           # sort each
    ø          # zip
     À         # rotate left (last 2 lists will be largest and smallest)
      `        # flatten (lists with smallest and largest item will be on top)
       -       # subtract largest from smallest
        Ä      # take absolute value (as we will have negatives after the previous step)
         Z     # take the largest
</code>```

Title: Find the maximum deviation

Body:
This problem is "inspired" from a question that was originally asked on Quora (not for code golfing). I just want to make it a challenge for you guys (and my first problem submission here).

Given an array of integer elements v and an integer d (we assume that d is lower or equal to the array's length), consider all the sequences of d consecutive elements in the array. For each sequence, compute the difference between the maximum and minimum value of the elements in that sequence and name it the deviation.

Your task is to write a program or function that computes the maximum value among all deviations of all the sequences considered above, and return or output that value.

Worked-through Example:

```<code>v: (6,9,4,7,4,1)
d: 3

The sequences of length 3 are:
6,9,4 with deviation 5
9,4,7 with deviation 5
4,7,4 with deviation 3
7,4,1 with deviation 6

Thus the maximal deviation is 6, so the output is 6.
</code>```

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

Body:
05AB1E, <s>12</s> 10 bytes

Uses CP-1252 encoding.

Œù€{øÀ`-ÄZ

Try it online!

Explanation

Œ              # sublists of v
 ù             # of length d
  €{           # sort each
    ø          # zip
     À         # rotate left (last 2 lists will be largest and smallest)
      `        # flatten (lists with smallest and largest item will be on top)
       -       # subtract largest from smallest
        Ä      # take absolute value (as we will have negatives after the previous step)
         Z     # take the largest


答:
R, 80  77 bytes bytes

Edit: Saved 3 bytes thanks to @rturnbull

```<code>function(s,d)max(sapply(d:sum(1|s)-d+1,function(i)diff(range(s[i:(i+d-1)]))))
</code>```

Title: Find the maximum deviation

Body:
R, 80  77 bytes bytes

Edit: Saved 3 bytes thanks to @rturnbull

function(s,d)max(sapply(d:sum(1|s)-d+1,function(i)diff(range(s[i:(i+d-1)]))))


答:
PowerShell v2+, 68 bytes

```<code>param($v,$d)($v|%{($x=$v[$i..($i+++$d-1)]|sort)[-1]-$x[0]}|sort)[-1]
</code>```

Iterative solution. Loops through $v, but really we're just using that as a counter rather than actually going through the values. Each iteration, we're slicing $v by $i..($i+++$d-1), where $i defaults to 0. We |sort those elements, and store the result into $x. Then we take the biggest [-1] and subtract the smallest [0]. We then |sort those results and take the biggest [-1] of that. That number is left on the pipeline and output is implicit.

Examples

```<code>PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(6,9,4,7,4,1) 3
6

PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(1,2,3,4,5,6) 3
2

PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(7,2,3,4,5,6) 3
5
</code>```

Title: Find the maximum deviation

Body:
PowerShell v2+, 68 bytes

param($v,$d)($v|%{($x=$v[$i..($i+++$d-1)]|sort)[-1]-$x[0]}|sort)[-1]

Iterative solution. Loops through $v, but really we're just using that as a counter rather than actually going through the values. Each iteration, we're slicing $v by $i..($i+++$d-1), where $i defaults to 0. We |sort those elements, and store the result into $x. Then we take the biggest [-1] and subtract the smallest [0]. We then |sort those results and take the biggest [-1] of that. That number is left on the pipeline and output is implicit.

Examples

PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(6,9,4,7,4,1) 3
6

PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(1,2,3,4,5,6) 3
2

PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(7,2,3,4,5,6) 3
5


答:
Dyalog APL, 7 bytes

```<code>⌈/⌈/-⌊/
</code>```

Test it on TryAPL.

How it works

```<code>⌈/⌈/-⌊/  Dyadic chain. Left argument: d. Right argument: v

     ⌊/  Reduce v by d-wise minimum, yielding the minima of all slices of length d.
  ⌈/     Reduce v by d-wise maximum, yielding the maxima of all slices of length d.
    -    Subtract, yielding the ranges of all slices of length d.
⌈/       Take the maximum.
</code>```

Title: Find the maximum deviation

Body:
Dyalog APL, 7 bytes

⌈/⌈/-⌊/

Test it on TryAPL.

How it works

⌈/⌈/-⌊/  Dyadic chain. Left argument: d. Right argument: v

     ⌊/  Reduce v by d-wise minimum, yielding the minima of all slices of length d.
  ⌈/     Reduce v by d-wise maximum, yielding the maxima of all slices of length d.
    -    Subtract, yielding the ranges of all slices of length d.
⌈/       Take the maximum.


答:
JavaScript (ES6), 73 bytes

```<code>with(Math)(v,d)=>max(...v.map((a,i)=>max(...a=v.slice(i,i+d))-min(...a)))
</code>```

Title: Find the maximum deviation

Body:
JavaScript (ES6), 73 bytes

with(Math)(v,d)=>max(...v.map((a,i)=>max(...a=v.slice(i,i+d))-min(...a)))


答:
Ruby, 45 bytes

```<code>->a,d{a.each_cons(d).map{|b|b.max-b.min}.max}
</code>```

I feel like this could be a lot better.

Title: Find the maximum deviation

Body:
Ruby, 45 bytes

->a,d{a.each_cons(d).map{|b|b.max-b.min}.max}

I feel like this could be a lot better.


答:
R, <s>63</s> <s>62</s> 56 bytes

Billywob has already provided a great R answer using only the base functions. However, I wanted to see if an alternative approach was possible, perhaps using some of R's extensive packages. There's a nice function rollapply in the zoo package designed to apply a function to a rolling window of an array, so that fits our purposes well. We use rollapply to find the max of each window, and we use it again to find the min of each window. Then we take the difference between the maxes and mins, which gives us the deviation for each window, and then return the max of those.

```<code>function(v,d)max((r=zoo::rollapply)(v,d,max)-r(v,d,min))
</code>```

Title: Find the maximum deviation

Body:
R, <s>63</s> <s>62</s> 56 bytes

Billywob has already provided a great R answer using only the base functions. However, I wanted to see if an alternative approach was possible, perhaps using some of R's extensive packages. There's a nice function rollapply in the zoo package designed to apply a function to a rolling window of an array, so that fits our purposes well. We use rollapply to find the max of each window, and we use it again to find the min of each window. Then we take the difference between the maxes and mins, which gives us the deviation for each window, and then return the max of those.

function(v,d)max((r=zoo::rollapply)(v,d,max)-r(v,d,min))


问:
No strings (or numbers) attached
If you like this, consider participating in:

The Official Dyalog APL 2016 Year Game

The monthly Dyalog APL 2017 Code Golf Challenge

Make 12 snippets/expressions, in the same language, that result in the numbers 0 through 10, and 42 respectively, but without writing any literal numeric, string, or character data.

Build-in data, like PI() and ALPHABET(), are fine, and so are e.g. CJam's U, X, Y, Z, and A constants, and Processing's BLEND, CHORD, CENTER, BREAK, and  LINES.

Every snippet must be able to stand on its own, i.e. they may not be interdependent. However, inside a single snippet, you may assign a variable and use it freely, as long as you refer to it directly by name, and not through a string containing its name.

All the snippets must be valid on the submitter’s computer at the time of submission (as reported by SE), but may not rely on unusual local conditions like number of files in a directory, the exact date or time, or specific input from the user.

Examples of valid snippets

3: INT(LOG10(YEAR(TODAY())))   because it remains true in the foreseeable future

4: CUBICROOT(LEN(CHARACTERSET()))   because a 256 letter character set is very common

8: SQRT(SYSTEMTYPE())   because 64-bit systems are very common

Examples of invalid snippets

5: LEN(USERNAME())   because most people do not use “Admin” as login :-)

9: LOG10(SYSTEMMEMORY())   because it only works on systems with exactly 1 GB of memory

42: CODE("*")   because it contains a string/character literal

The result of each snippet must result in an actual number (value, int, float, etc.) that can be used for further calculations using the same language as the snippet, i.e not a text string representing that number.

Only character based languages allowed.

Score is total byte count of all the 12 snippets combined. Newlines separating the snippets are not counted in.

Note that the above rules may prevent some languages from participating, even if they are Turing complete.

FAQ

Q Can the programs accept any input?

A Yes, but you may not just ask for input and enter the relevant number.

Q Are physical digits (non-data) digits allowed?

A Yes, e.g. LOG10().

Q Do Symbols in Ruby count as literals?

A Yes.

Q Does score include newlines between each snippet?

A No.

Q Is TI-BASIC "character based" enough to be valid?

A Yes.

Q Do false and true count as number literals?

A No, they are acceptable.

Q Can we use a number literal to call a function if that's the only way and the number doesn't influence the output of the function?

A Yes, if that is the normal way to write code in your language.

Q My language assumes there is a [something] at the start of each program/expression. Must I include it, or should my snippets just work if placed in the middle of a program/expression?

A They should just work in the middle of a program/expression.

Q What about regex literals?

A Forbidden, except for languages that only do regexes.

Q Is one piece of code that could print all the specified numbers acceptable?

A No, they have to be separate and mutually independent.

Q May I assume a boilerplate like int main() {}... or equivalent?

A Yes.

Q What output datatypes are allowed?

A Any numeric datatype, like int, float, etc.

Q Do I need to print the result of each snippet?

A No, making the result available for subsequent use is enough.

Q Are pre-set variables allowed?

A Yes, and they become reset (if changed) for every snippet.

Q Are π and e considered number literals?

A No, you may use them.

Q May I return 4 and 2 in different cells for 42?

A No, they must be connected as one number.

Q Bytes or characters?

A Bytes, but you may choose any desired codepage.

Q May constant functions and preset variables like J's 9:, Actually's 9, and Pretzel's 9 be used?

A Yes, if the vocabulary is finite (19 for J, 10 for Actually and Pretzel).

Title: No strings (or numbers) attached

Body:
Brain-Flak, <s>172</s> 143 bytes

(<>)
(())
(()())
(()()())
(()()()())
(()()()()())
((()()()){})
((()()()){}())
((()()()()){})
(((()()())){}{})
((()()()()()){})
(((((()()()){}()){})){}{})

Try it online! (copy-paste yourself)


答:
Jelly, 6 bytes

```<code>5Ḷc@’S
</code>```

Try it online! | Verify test cases

Explanation

Uses the OEIS formula ((n-1)C4 + (n-1)C3 + ... + (n-1)C0).

```<code>5Ḷc@’S    Main link.  Args: n

5         Yield 5.
 Ḷ        Lowered range: yield [0,1,2,3,4].
    ’     Yield n-1.
   @      Swap operands of the preceding dyad, 'c'.
  c       Combinations: yield [(n-1)C0, (n-1)C1, (n-1)C2, (n-1)C3, (n-1)C4].
     S    Sum: return (n-1)C0 + (n-1)C1 + (n-1)C2 + (n-1)C3 + (n-1)C4.
</code>```

Body:
Jelly, 6 bytes

5Ḷc@’S

Try it online! | Verify test cases

Explanation

Uses the OEIS formula ((n-1)C4 + (n-1)C3 + ... + (n-1)C0).

5Ḷc@’S    Main link.  Args: n

5         Yield 5.
 Ḷ        Lowered range: yield [0,1,2,3,4].
    ’     Yield n-1.
   @      Swap operands of the preceding dyad, 'c'.
  c       Combinations: yield [(n-1)C0, (n-1)C1, (n-1)C2, (n-1)C3, (n-1)C4].
     S    Sum: return (n-1)C0 + (n-1)C1 + (n-1)C2 + (n-1)C3 + (n-1)C4.


答:
Mathematica, <s>41</s> 37 bytes

```<code>Max[MovingMap[MinMax,#,#2-1].{-1,1}]&
</code>```

Title: Find the maximum deviation

Body:
Mathematica, <s>41</s> 37 bytes

Max[MovingMap[MinMax,#,#2-1].{-1,1}]&


问:
The alphabet in programming languages
Our task is to, for each letter of the (English) alphabet, write a program that prints the alphabet, in a language whose name starts with that letter.

Input: none

Output:

```<code>abcdefghijklmnopqrstuvwxyz
</code>```

uppercase and trailing newline optional

Rules:

The scoring metric is the length of the programming language name, plus the length of the code.  Hence, C will be assessed a "penalty" of 1, while GolfScript will be assessed a penalty of 10.

One language/implementation per answer.  Multiple answers are encouraged.

If a programming language name's first letter is not an English letter, it should not be coerced into one.  It will be treated as a separate letter (meaning less competition).

No answer will be accepted until every English letter has a solution.

Current rankings:

APL: 5

Brachylog: 11

Canvas: 7

DOS: 13

Eso2D: 20

Fish: 20

Gaia: 6

Husk: 8

IPEL: 23

Japt: 6

Keg: 6

Ly: 13

MathGolf: 9

Ni: 15

Owl: 14

Pip: 4

QuadR: 31

Ruby: 17

Stax: 6

Thunno: 8

Unix Shell: 31

V: 4

W: 4

XJam: 10

Yorick: 36

Z80Golf: 16

Tell me if I'm missing anybody.

Automatic leaderboard (experimental)

var QUESTION_ID=2078;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&r.indexOf('non-competing')===-1&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],lang:/a)-(d<a)||e.size-s.size});var s={},a=null,n="A";e.forEach(function(e){n=e.lang[0].toUpperCase(),a=e.size;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+" is for").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.lang,p=o[0].toUpperCase();s[p]=s[p]||{language:e.language,lang:e.lang,letter:p,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return(e.letter>s.letter)-(e.letter<s.letter)});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.language).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),jQuery("#languages").append(jQuery(i))}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*(?:<[^>]+>)?(?:[^]+?for )?((?:]*?>)?(?:(?! [(=→-])[^\n,:])*[^\s,:])(?:[,:]| [(=→-]).*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Winners by Letter

Language	User	Score

{{PLACE}}	{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Everything

	Language	Author	Size

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
D is for D2, 2 + 6 = 8

```<code>!a[.+]
</code>```

!a expand to 10 +, setting the current cell to 10 (a in base 36), and [.+] print the current cell as a base 36 string and increment the cell. Since the maximum value a cell can hold is 35, at 36 the cell is zeroed and the loop stop.

Title: The alphabet in programming languages

Body:
D is for D2, 2 + 6 = 8

!a[.+]

!a expand to 10 +, setting the current cell to 10 (a in base 36), and [.+] print the current cell as a base 36 string and increment the cell. Since the maximum value a cell can hold is 35, at 36 the cell is zeroed and the loop stop.


答:
Perl, <s>179</s> <s>165</s> <s>164</s> <s>163</s> <s>157</s> 156 bytes

Includes +4 for -p

Give wolves followed by chickens on STDIN

```<code>river.pl <<< "2 3"
</code>```

Outputs the boat contents per line. For this example it gives:

```<code>WC
C
CC
C
CC
W
WW
</code>```

river.pl:

```<code>#!/usr/bin/perl -p
/ /;@F=w x$`.c x$'."\xaf\n";$a{$`x/\n/}++||grep(y/c//<y/w//&/c/,$_,~$_)or$\||=$' x/^\w*\n|(\w?)(.*)(c|w)(.+)\n(?{push@F,$1.$3.~"$`$2$4\xf5".uc"$'$1$3\n"})^/ for@F}{
</code>```

Works as shown, but replace \xhh and \n by their literal versions to get the claimed score.

This will probably be beaten by a program that solves the general case (C>W>0)

```<code>* output `WC W WC C` until there is only one wolf left on the left bank (--w, --c)
* output `CC C` until there is only one chicken left on the left bank (--c)
* output `WC`
</code>```

Add to that the trivial solutions for only wolves and only chickens and a hardcoded special case for 2 2 and 3 3 (4 4 and higher have no solution). But that would be a boring program.

Explanation

The current state of the field is stored as a single string consisting of:

w for a wolf    on the bank with the boat

c for a chicken on the bank with the boat

\x88 (bit reversed w) for a wolf    on the other bank

\x9c (bit reversed c) for a chicken on the other bank

A character indicating the side the boat is on P for the right bank, \xaf (bit reversed P) for the left bank (starting side)

a newline \n

all the moves that have been done upto now terminated with newlines, e.g. something like WC\nW\nWC\nC\n (notice the Ws and C are in uppercase here)

The array @F will contain all reachable states. It is initialised by the starting string wolves times "w",  chickens times "c", \xaf \n

The program then loops over @F which will get extended during the looping so new states get processed too. For every element it then does:

Look at the string part left of the first \n which represents the current position of the animals and the boat. If that has been seen before skip $a{$`x/\n/}++

Check if there are chickens together with more wolves on any side. Skip if so grep(y/c//<y/w//&/c/,$_,~$_)

Check if the boat is the far side together with all animals. If so we have a solution. Store that in $\ and keep that since the first solution found is the shortest $\||=$' x/^\w*\n/

Otherwise try all ways of selecting 1 or 2 animals on the side with the boat. These are the c and w characters. (The animals at the other side won't match \w)  /(\w?)(.*)(c|w)(.+)\n(?{code})^/. Then bit reverse the whole string before the \n except the animals that were selected for the boat push@F,$1.$3.~"$`$2$4\xf5". Add the selected animals to the moves by uppercasing them: uc"$'$1$3\n"

The animal selection process effectively shuffles the string part representing them in many ways. So e.g. wcwc and wwcc can both get to represent 2 wolves and 2 chickens. The state check $a{$`x/\n/}++ will unnessarily distinguish these two so many more states than necessary will be generated and checked. Therefore the program will run out of memory and time as soon as the number of different animals gets larger. This is mitigated only a bit by the fact that the current version will stop adding new states once a solution is found

Title: Wolves and Chickens

Body:
There's a river and there are wolves and chickens on one side of the river. They have a raft and they all need to get to the other side. However, the raft cannot travel on its own. The raft will sink if more than two animals are on it. None of the animals want to get wet because the river's cold and dirty. None of the animals can jump or fly over the river. Also, if there are chickens on one side, there cannot be more wolves on that side than there are chickens on that side -- the wolves will then decide to eat the chickens. This means that you cannot take two wolves on the raft to a side with one chicken.

Your task is to make a program/function that takes a number of wolves and a number of chickens (greater than or equal to the number of wolves) as input and finds the smallest number of times the raft has to move across the river. If the task is not possible, the program/function should output/return an empty string. It will then print/return one method as to how this is done in the following way:

```<code>W if a wolf crosses the river on its own
C if a chicken crosses the river on its own
CW if a chicken and a wolf cross the river -- WC is also fine
CC if two chickens cross the river
WW if two wolves cross the river
</code>```

As you can deduce, the raft will automatically move in alternating directions (left and right, starting from left to right as the first one or two animals cross the river). This doesn't need to be outputted/returned. 'W', 'C', 'CW', 'CC' or 'WW' in the output may be separated by at least one of the following:

```<code>spaces (' ')
commas (',')
newlines
</code>```

Alternatively, you may store the directions as items in a list (an empty list means no solution).

Test cases (output separated by commas -- input takes the form wolves,chickens):

```<code>1,1 -> CW

2,2 -> CW,C,CC,C,CW

1,2 -> CW,W,CW

0,10 -> CC,C,CC,C,CC,C,CC,C,CC,C,CC,C,CC,C,CC,C,CC

3,2 -> no solution
</code>```

Try to make your code as short in bytes as possible.

Body:
Perl, <s>179</s> <s>165</s> <s>164</s> <s>163</s> <s>157</s> 156 bytes

Includes +4 for -p

Give wolves followed by chickens on STDIN

river.pl <<< "2 3"

Outputs the boat contents per line. For this example it gives:

WC
C
CC
C
CC
W
WW

river.pl:

#!/usr/bin/perl -p
/ /;@F=w x$`.c x$'."\xaf\n";$a{$`x/\n/}++||grep(y/c//<y/w//&/c/,$_,~$_)or$\||=$' x/^\w*\n|(\w?)(.*)(c|w)(.+)\n(?{push@F,$1.$3.~"$`$2$4\xf5".uc"$'$1$3\n"})^/ for@F}{

Works as shown, but replace \xhh and \n by their literal versions to get the claimed score.

This will probably be beaten by a program that solves the general case (C>W>0)

* output `WC W WC C` until there is only one wolf left on the left bank (--w, --c)
* output `CC C` until there is only one chicken left on the left bank (--c)
* output `WC`

Add to that the trivial solutions for only wolves and only chickens and a hardcoded special case for 2 2 and 3 3 (4 4 and higher have no solution). But that would be a boring program.

Explanation

The current state of the field is stored as a single string consisting of:

w for a wolf    on the bank with the boat

c for a chicken on the bank with the boat

\x88 (bit reversed w) for a wolf    on the other bank

\x9c (bit reversed c) for a chicken on the other bank

A character indicating the side the boat is on P for the right bank, \xaf (bit reversed P) for the left bank (starting side)

a newline \n

all the moves that have been done upto now terminated with newlines, e.g. something like WC\nW\nWC\nC\n (notice the Ws and C are in uppercase here)

The array @F will contain all reachable states. It is initialised by the starting string wolves times "w",  chickens times "c", \xaf \n

The program then loops over @F which will get extended during the looping so new states get processed too. For every element it then does:

Look at the string part left of the first \n which represents the current position of the animals and the boat. If that has been seen before skip $a{$`x/\n/}++

Check if there are chickens together with more wolves on any side. Skip if so grep(y/c//<y/w//&/c/,$_,~$_)

Check if the boat is the far side together with all animals. If so we have a solution. Store that in $\ and keep that since the first solution found is the shortest $\||=$' x/^\w*\n/

Otherwise try all ways of selecting 1 or 2 animals on the side with the boat. These are the c and w characters. (The animals at the other side won't match \w)  /(\w?)(.*)(c|w)(.+)\n(?{code})^/. Then bit reverse the whole string before the \n except the animals that were selected for the boat push@F,$1.$3.~"$`$2$4\xf5". Add the selected animals to the moves by uppercasing them: uc"$'$1$3\n"

The animal selection process effectively shuffles the string part representing them in many ways. So e.g. wcwc and wwcc can both get to represent 2 wolves and 2 chickens. The state check $a{$`x/\n/}++ will unnessarily distinguish these two so many more states than necessary will be generated and checked. Therefore the program will run out of memory and time as soon as the number of different animals gets larger. This is mitigated only a bit by the fact that the current version will stop adding new states once a solution is found


答:
MATL, 10 bytes

```<code>YCS5LY)dX>
</code>```

Try it online!

Explanation

Consider inputs [6,9,4,7,4,1], 3 as an example.

```<code>       % Implicitly take the two inputs: v, d
       % STACK: [6,9,4,7,4,1], 3
YC     % Matrix of overlapping d-blocks of v
       % STACK: [6 9 4 7
                 9 4 7 4
                 4 7 4 1]
S      % Sort each column
       % STACK: [4 4 4 1
                 6 7 4 4
                 9 9 7 7]
5LY)   % Keep first and last rows
       % STACK: [4 4 4 1
                 9 9 7 7]
d      % Differences along each column
       % STACK: [5 5 3 6]
X>     % Maximum
       % STACK: 6
       % Implicitly display
</code>```

Title: Find the maximum deviation

Body:
MATL, 10 bytes

YCS5LY)dX>

Try it online!

Explanation

Consider inputs [6,9,4,7,4,1], 3 as an example.

       % Implicitly take the two inputs: v, d
       % STACK: [6,9,4,7,4,1], 3
YC     % Matrix of overlapping d-blocks of v
       % STACK: [6 9 4 7
                 9 4 7 4
                 4 7 4 1]
S      % Sort each column
       % STACK: [4 4 4 1
                 6 7 4 4
                 9 9 7 7]
5LY)   % Keep first and last rows
       % STACK: [4 4 4 1
                 9 9 7 7]
d      % Differences along each column
       % STACK: [5 5 3 6]
X>     % Maximum
       % STACK: 6
       % Implicitly display


问:
Sylvester's sequence
Sylvester's sequence, OEIS A000058, is an integer sequence defined as follows:

Each member is the product of all previous members plus one.  The first member of the sequence is 2.

Task

Create a program to calculate the nth term of Sylvester's Sequence.  Standard input, output and loopholes apply.

Standard sequence rules apply.

This is code-golf, so the goal is to minimize the size of your source code as measured in bytes.

Test Cases

You may use either zero or one indexing. (Here I use zero indexing)

```<code>>>0
2
>>1
3
>>2
7
>>3
43
>>4
1807
</code>```

答:
C#, 144 Bytes

I used one indexing:

Golfed:

```<code>int s(int n){var a=new int[n];int b=1;for(int i=0;i<a.Length;i++){a[i]=b;b=1;a.ToList().GetRange(0,i).ForEach(o=>b*=o);a[i]=b+1;}return a[n-1];}
</code>```

Ungolfed:

```<code>class SylvestersSequence
{
public int s(int n)
{
  var a = new int[n];

  int b = 1;

  for (int i = 0; i < a.Length; i++)
  {
    a[i] = b;

    b = 1;

    a.ToList().GetRange(0, i).ForEach(o => b *= o);

    a[i] = b + 1;
  }

  return a[n - 1];
}
}
</code>```

Tests:

```<code>1 : 2
2 : 3
3 : 7
4 : 43
5 : 1807
6 : 3263443
</code>```

(Things start to go a bit weird after this...)

Title: Sylvester's sequence

Body:
C#, 144 Bytes

I used one indexing:

Golfed:

int s(int n){var a=new int[n];int b=1;for(int i=0;i<a.Length;i++){a[i]=b;b=1;a.ToList().GetRange(0,i).ForEach(o=>b*=o);a[i]=b+1;}return a[n-1];}

Ungolfed:

class SylvestersSequence
{
public int s(int n)
{
  var a = new int[n];

  int b = 1;

  for (int i = 0; i < a.Length; i++)
  {
    a[i] = b;

    b = 1;

    a.ToList().GetRange(0, i).ForEach(o => b *= o);

    a[i] = b + 1;
  }

  return a[n - 1];
}
}

Tests:

1 : 2
2 : 3
3 : 7
4 : 43
5 : 1807
6 : 3263443

(Things start to go a bit weird after this...)


答:
Actually, 15 bytes

Golfing suggestions welcome. Try it online!

```<code>╗;R`╜∙♂S╔♂Σi`Mc
</code>```

Ungolfing

```<code>         Implicit input n, then the list of coins a.
╗        Save a to register 0.
;R       Duplicate n and create a range [1..n] from that duplicate.
`...`M   Map the following function over that range. Variable i.
  ╜        Push a from register 0.
  ∙        Push the i-th Cartesian power of a.
  ♂S       Sort each member of car_pow.
  ╔        Uniquify car_pow so we don't count too any duplicate coin arrangements.
  ♂Σ       Take the sum of each coin arrangement.
  i        Flatten the list.
c        Using the result of the map and the remaining n, push map.count(n).
         Implicit return.
</code>```

Title: A penny saved is a penny

Body:
...counted!

You will pass your program a variable which represents a quantity of money in dollars and/or cents and an array of coin values.  Your challenge is to output the number of possible combinations of the given array of coin values that would add up to the amount passed to the code.  If it is not possible with the coins named, the program should return 0.

Note on American numismatic terminology:

1-cent coin: penny

5-cent coin: nickel

10-cent coin: dime

25-cent coin: quarter (quarter dollar)

Example 1:

Program is passed:

```<code>12, [1, 5, 10]
</code>```

(12 cents)

Output:

```<code>4
</code>```

There are 4 possible ways of combining the coins named to produce 12 cents:

12 pennies

1 nickel and 7 pennies

2 nickels and 2 pennies

1 dime and 2 pennies

Example 2:

Program is passed:

```<code>26, [1, 5, 10, 25]
</code>```

(26 cents)

Output:

```<code>13
</code>```

There are 13 possible ways of combining the coins named to produce 26 cents:

26 pennies

21 pennies and 1 nickel

16 pennies and 2 nickels

11 pennies and 3 nickels

6 pennies and 4 nickels

1 penny and 5 nickels

16 pennies and 1 dime

6 pennies and 2 dimes

11 pennies, 1 dime, and 1 nickel

6 pennies, 1 dime, and 2 nickels

1 penny, 1 dime, and 3 nickels

1 penny, 2 dimes, and 1 nickel

1 quarter and 1 penny

Example 3:

Program is passed:

```<code>19, [2, 7, 12]
</code>```

Output:

```<code>2
</code>```

There are 2 possible ways of combining the coins named to produce 19 cents:

1 12-cent coin and 1 7-cent coin

1 7-cent coin and 6 2-cent coins

Example 4:

Program is passed:

```<code>13, [2, 8, 25]
</code>```

Output:

```<code>0
</code>```

There are no possible ways of combining the coins named to produce 13 cents.

This has been through the Sandbox.  Standard loopholes apply.  This is code golf, so the answer with the fewest bytes wins.

Body:
Actually, 15 bytes

Golfing suggestions welcome. Try it online!

╗;R`╜∙♂S╔♂Σi`Mc

Ungolfing

         Implicit input n, then the list of coins a.
╗        Save a to register 0.
;R       Duplicate n and create a range [1..n] from that duplicate.
`...`M   Map the following function over that range. Variable i.
  ╜        Push a from register 0.
  ∙        Push the i-th Cartesian power of a.
  ♂S       Sort each member of car_pow.
  ╔        Uniquify car_pow so we don't count too any duplicate coin arrangements.
  ♂Σ       Take the sum of each coin arrangement.
  i        Flatten the list.
c        Using the result of the map and the remaining n, push map.count(n).
         Implicit return.


问:
Simple cat program
One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a "cat program": read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility cat it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc.

Task

You should write a full program which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's prompt and alert). These are the only admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable.

The output should contain exactly the input and nothing else. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. This also applies to trailing newlines. If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.)

Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. If you do this, I encourage you to add an error-free version to your answer as well (for reference).

As this is intended as a challenge within each language and not between languages, there are a few language specific rules:

If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well).

If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example yes | tr -d \\n | ./my_cat should print an infinite stream of ys. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing).

Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output.

Additional rules

This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

Also note that languages do have to fulfil our usual criteria for programming languages.

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

Unless they have been overruled earlier, all standard code-golf rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.

Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Brain-Flak, 0 + 3 = 3 bytes

Needs the -c flag.

```<code>
</code>```

Try it online!

This language cannot possibly handle infinite input streams.

This language absolutely always appends a trailing newline to the output.

In the original Ruby interpreter, the input is a command-line arg instead of a STDIN stream. The online interpreter seems to have been modified.

Title: Simple cat program

Body:
Brain-Flak, 0 + 3 = 3 bytes

Needs the -c flag.

Try it online!

This language cannot possibly handle infinite input streams.

This language absolutely always appends a trailing newline to the output.

In the original Ruby interpreter, the input is a command-line arg instead of a STDIN stream. The online interpreter seems to have been modified.


答:
PHP, 130 bytes

```<code>function r($n,$a){if($c=$a[0])for(;0<$n;$n-=$c)$o+=r($n,array_slice($a,1));return$o?:$n==0;}echo r($argv[1],array_slice($argv,2));
</code>```

99 byte recursive function (and 31 bytes of calling it) that repeatedly removes the value of the current coin from the target and calls itself with the new value and the other coins. Counts the number of times the target reaches 0 exactly. Run like:

```<code> php -r "function r($n,$a){if($c=$a[0])for(;0<$n;$n-=$c)$o+=r($n,array_slice($a,1));return$o?:$n==0;}echo r($argv[1],array_slice($argv,2));" 12 1 5 10
</code>```

Title: A penny saved is a penny

Body:
PHP, 130 bytes

function r($n,$a){if($c=$a[0])for(;0<$n;$n-=$c)$o+=r($n,array_slice($a,1));return$o?:$n==0;}echo r($argv[1],array_slice($argv,2));

99 byte recursive function (and 31 bytes of calling it) that repeatedly removes the value of the current coin from the target and calls itself with the new value and the other coins. Counts the number of times the target reaches 0 exactly. Run like:

 php -r "function r($n,$a){if($c=$a[0])for(;0<$n;$n-=$c)$o+=r($n,array_slice($a,1));return$o?:$n==0;}echo r($argv[1],array_slice($argv,2));" 12 1 5 10


答:
S is for Swift, 76 characters -> Score: 81

```<code>var s=""
for i in 97...122{s.append((Character(UnicodeScalar(i))))}
print(s)
</code>```

Title: The alphabet in programming languages

Body:
Our task is to, for each letter of the (English) alphabet, write a program that prints the alphabet, in a language whose name starts with that letter.

Input: none

Output:

```<code>abcdefghijklmnopqrstuvwxyz
</code>```

uppercase and trailing newline optional

Rules:

The scoring metric is the length of the programming language name, plus the length of the code.  Hence, C will be assessed a "penalty" of 1, while GolfScript will be assessed a penalty of 10.

One language/implementation per answer.  Multiple answers are encouraged.

If a programming language name's first letter is not an English letter, it should not be coerced into one.  It will be treated as a separate letter (meaning less competition).

No answer will be accepted until every English letter has a solution.

Current rankings:

APL: 5

Brachylog: 11

Canvas: 7

DOS: 13

Eso2D: 20

Fish: 20

Gaia: 6

Husk: 8

IPEL: 23

Japt: 6

Keg: 6

Ly: 13

MathGolf: 9

Ni: 15

Owl: 14

Pip: 4

QuadR: 31

Ruby: 17

Stax: 6

Thunno: 8

Unix Shell: 31

V: 4

W: 4

XJam: 10

Yorick: 36

Z80Golf: 16

Tell me if I'm missing anybody.

Automatic leaderboard (experimental)

var QUESTION_ID=2078;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&r.indexOf('non-competing')===-1&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],lang:/a)-(d<a)||e.size-s.size});var s={},a=null,n="A";e.forEach(function(e){n=e.lang[0].toUpperCase(),a=e.size;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+" is for").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.lang,p=o[0].toUpperCase();s[p]=s[p]||{language:e.language,lang:e.lang,letter:p,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return(e.letter>s.letter)-(e.letter<s.letter)});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.language).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),jQuery("#languages").append(jQuery(i))}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*(?:<[^>]+>)?(?:[^]+?for )?((?:]*?>)?(?:(?! [(=→-])[^\n,:])*[^\s,:])(?:[,:]| [(=→-]).*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Winners by Letter

Language	User	Score

{{PLACE}}	{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Everything

	Language	Author	Size

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
S is for Swift, 76 characters -> Score: 81

var s=""
for i in 97...122{s.append((Character(UnicodeScalar(i))))}
print(s)


答:
CJam, 17 bytes

```<code>q~ew{$)\(\;-}%:e>
</code>```

(Also q~ew:$z)\(\;.-:e>)

Try it online!

Explanation

```<code>q~                   e# Read the two inputs. Evaluate
  ew                 e# Overlapping blocks
    {       }%       e# For each block
     $               e# Sort
      )              e# Get last element (that is, maximum)
       \(            e# Swap, get first element (minimum)
         \;          e# Swap, delete rest of the block
           -         e# Subtract (maximum minus minimum)
              :e>    e# Maximum of array
</code>```

Title: Find the maximum deviation

Body:
This problem is "inspired" from a question that was originally asked on Quora (not for code golfing). I just want to make it a challenge for you guys (and my first problem submission here).

Given an array of integer elements v and an integer d (we assume that d is lower or equal to the array's length), consider all the sequences of d consecutive elements in the array. For each sequence, compute the difference between the maximum and minimum value of the elements in that sequence and name it the deviation.

Your task is to write a program or function that computes the maximum value among all deviations of all the sequences considered above, and return or output that value.

Worked-through Example:

```<code>v: (6,9,4,7,4,1)
d: 3

The sequences of length 3 are:
6,9,4 with deviation 5
9,4,7 with deviation 5
4,7,4 with deviation 3
7,4,1 with deviation 6

Thus the maximal deviation is 6, so the output is 6.
</code>```

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

Body:
CJam, 17 bytes

q~ew{$)\(\;-}%:e>

(Also q~ew:$z)\(\;.-:e>)

Try it online!

Explanation

q~                   e# Read the two inputs. Evaluate
  ew                 e# Overlapping blocks
    {       }%       e# For each block
     $               e# Sort
      )              e# Get last element (that is, maximum)
       \(            e# Swap, get first element (minimum)
         \;          e# Swap, delete rest of the block
           -         e# Subtract (maximum minus minimum)
              :e>    e# Maximum of array


答:
Racket, 46 bytes (score 52)

```<code>(for((i 26))(display(integer->char(+ i 97))))
</code>```

Title: The alphabet in programming languages

Body:
Racket, 46 bytes (score 52)

(for((i 26))(display(integer->char(+ i 97))))


答:
MATLAB with Statistics and Image Processing Toolboxes, 33 bytes

```<code>@(v,d)max(range(im2col(v,[1 d])))
</code>```

This defines an anonymous function. Example use:

```<code>>> f = @(v,d)max(range(im2col(v,[1 d])));
>> f([6,9,4,7,4,1], 3)
ans =
     6
</code>```

You can also try it on Octave at Ideone (but Octave, unlike Matlab, requires explicitly loading the image package).

Explanation

```<code>im2col(v,[1 d]))   % Takes overlapping blocks of size d from v, and arranges them as
                   % columns of a matrix
range(...)         % Maximum minus minimum of each column. Gives a row vector
max(...)           % Maximum of the above row vector
</code>```

Title: Find the maximum deviation

Body:
MATLAB with Statistics and Image Processing Toolboxes, 33 bytes

@(v,d)max(range(im2col(v,[1 d])))

This defines an anonymous function. Example use:

>> f = @(v,d)max(range(im2col(v,[1 d])));
>> f([6,9,4,7,4,1], 3)
ans =
     6

You can also try it on Octave at Ideone (but Octave, unlike Matlab, requires explicitly loading the image package).

Explanation

im2col(v,[1 d]))   % Takes overlapping blocks of size d from v, and arranges them as
                   % columns of a matrix
range(...)         % Maximum minus minimum of each column. Gives a row vector
max(...)           % Maximum of the above row vector


答:
R, 26 bytes (score 27)

```<code>paste(letters,collapse="")
</code>```

Output:

```<code>[1] "abcdefghijklmnopqrstuvwxyz"
</code>```

Title: The alphabet in programming languages

Body:
R, 26 bytes (score 27)

paste(letters,collapse="")

Output:

[1] "abcdefghijklmnopqrstuvwxyz"


答:
PHP, <s>89</s> 87 bytes

```<code>for($i=1;$r=array_slice($argv,++$i,$argv[1]);$d=max($r)-min($r))$o=$d>$o?$d:$o;echo+$o;
</code>```

Not particularly clever or pretty but it works. Use like:

```<code>php -r "for($i=1;$r=array_slice($argv,++$i,$argv[1]);$d=max($r)-min($r))$o=$d>$o?$d:$o;echo+$o;" 3 6 9 4 7 1
</code>```

for v=6,9,4,7,4,1, d=3

Edit: 2 bytes saved thanks to Jörg Hülsermann

Title: Find the maximum deviation

Body:
PHP, <s>89</s> 87 bytes

for($i=1;$r=array_slice($argv,++$i,$argv[1]);$d=max($r)-min($r))$o=$d>$o?$d:$o;echo+$o;

Not particularly clever or pretty but it works. Use like:

php -r "for($i=1;$r=array_slice($argv,++$i,$argv[1]);$d=max($r)-min($r))$o=$d>$o?$d:$o;echo+$o;" 3 6 9 4 7 1

for v=6,9,4,7,4,1, d=3

Edit: 2 bytes saved thanks to Jörg Hülsermann


问:
Shortest infinite loop producing no output
Your task is to create the shortest infinite loop!

The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.

The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.

The program must not write anything to STDERR.

Feel free to use a language (or language version) even if it's newer than this challenge.
-Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. :D

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainf**k-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like #[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes.

Standard loopholes are not allowed.

(I have taken some of these rules from Martin Büttner's "Hello World" challenge)

Please feel free to post in the comments to tell me how this challenge could be  improved.

Catalogue

This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:

```<code># Language name, X bytes
</code>```

Obviously replacing Language name and X bytes with the proper items. If you want to link to the languages' website, use this template, as posted above:

```<code>#[Language name](http://link.to/the/language), X bytes
</code>```

Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)

var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"//api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+lang+'').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang,user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
D2, 3 bytes

```<code>+[]
</code>```

Same as Brainfuck

More interesting version using the preprocessor (the code is actually never executed because the infinite loop is in the preprocessor):

```<code>(@a)a@a
</code>```

Simple recursive macro

Body:
D2, 3 bytes

+[]

Same as Brainfuck

More interesting version using the preprocessor (the code is actually never executed because the infinite loop is in the preprocessor):

(@a)a@a

Simple recursive macro