问:
Non-transitive dice game
Those of you who like Numberphile would be familiar with Dr. James Grime, who described a non-transitive dice game on his channel.

The game consists of three 6-faced dice:

Die 1: 3,3,3,3,3,6

Die 2: 2,2,2,5,5,5

Die 3: 1,4,4,4,4,4

Two players each select a die to use. They roll them and the higher die wins, best-of-whatever.

Probabilistically, die 1 beats dies 2 with >50% chance. Similarly, die 2 beats die 3, and, interestingly, die 3 beats die 1.

Write a program taking 1, 2 or 3 as input. This indicates the die the user chooses. The program then choose the die that would beat the user and output the results of 21 rolls, and "Computer/User wins with x points"

Rules

Code-golf, votes as tiebreaker

You must use RNG (or the likes) to actually simulate the dice rolls.

I am not too strict on output format. It's okay as long as you show the dices, somehow separate between the 21 rolls (in a way different from how you separate the dice in the same roll), and output that sentence above.

Input can be stdin, command line argument, from screen, etc.

Example

Input

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

Output

```<code>4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 6
1 3
4 3
4 3
1 3
4 3
1 3
4 3
4 3
4 3
4 3
4 6
 Computer wins with 16 points
</code>```

Here, the user chooses die 1 and his rolls are shown on the right column. The program chooses die 3 and beats him.

答:
Mathematica 234 247

Code

```<code>g@n_ := {t = RandomChoice[{{5, 25, 1, 5}/36 -> {{3, 1}, {3, 4}, {6, 1}, {6, 4}},
         {5, 1, 5, 1}/12 -> {{2, 3}, {2, 6}, {5, 3}, {5, 6}},
         {1, 1, 5, 5}/12 -> {{1, 2}, {1, 5}, {4, 2}, {4, 5}}}[[n]], 21],
         Row[{If[(c = Count[t, {x_, y_} /; y > x]) > 10, "Computer ", "Player "],
         "wins with ", If[c > 10, c, 21 - c], " points"}]}
</code>```

Usage

{Player's roll, Computer's roll}

```<code>g[1]
g[2]
g[3]
</code>```

Explanation

n is the number 1, 2, or 3 that corresponds to the die of the player.
Because  n also determines (but does not equal) the die of the computer, we can generate all possible rolls of the dice when n=1, n=2, n=3.  We can also determine their respective probabilities.

Examine the data right after RandomChoice:

{5, 25, 1, 5}/36 -> {{3, 1}, {3, 4}, {6, 1}, {6, 4}}

If the player draws die 1, the only possible outcomes are the following 4 pairs

{{3, 1}, {3, 4}, {6, 1}, {6, 4}}

The respective probabilities of these pairs are

{5, 25, 1, 5}/36, that is,

{5/36, 25/36, 1/36, 5/36}

RandomChoice[<data>, 21] outputs 21 rolls of the two dice.

Title: Non-transitive dice game

Body:
Mathematica 234 247

Code

g@n_ := {t = RandomChoice[{{5, 25, 1, 5}/36 -> {{3, 1}, {3, 4}, {6, 1}, {6, 4}},
         {5, 1, 5, 1}/12 -> {{2, 3}, {2, 6}, {5, 3}, {5, 6}},
         {1, 1, 5, 5}/12 -> {{1, 2}, {1, 5}, {4, 2}, {4, 5}}}[[n]], 21],
         Row[{If[(c = Count[t, {x_, y_} /; y > x]) > 10, "Computer ", "Player "],
         "wins with ", If[c > 10, c, 21 - c], " points"}]}

Usage

{Player's roll, Computer's roll}

g[1]
g[2]
g[3]

Explanation

n is the number 1, 2, or 3 that corresponds to the die of the player.
Because  n also determines (but does not equal) the die of the computer, we can generate all possible rolls of the dice when n=1, n=2, n=3.  We can also determine their respective probabilities.

Examine the data right after RandomChoice:

{5, 25, 1, 5}/36 -> {{3, 1}, {3, 4}, {6, 1}, {6, 4}}

If the player draws die 1, the only possible outcomes are the following 4 pairs

{{3, 1}, {3, 4}, {6, 1}, {6, 4}}

The respective probabilities of these pairs are

{5, 25, 1, 5}/36, that is,

{5/36, 25/36, 1/36, 5/36}

RandomChoice[<data>, 21] outputs 21 rolls of the two dice.


问:
List all ordered partitions of n
The challenge is to list all ordered partitions (composition (combinatorics)) of a given positive integer n. These are the lists of numbers from 1 to n whose sum is n. For example, given input n = 4, the result should be:

4

  1, 3

  3, 1

  2, 2

  2, 1, 1

  1, 2, 1

  1, 1, 2

  1, 1, 1, 1

The result can be in any order, but must contain each ordered partition once. This means that for n = 4, [1, 1, 2], [1, 2, 1] and [2, 1, 1] must all be part of the result.

Here's my own JavaScript code which achieves this:

```<code>function range(n) {
    for (var range = [], i = 0; i < n; range.push(++i));
    return range;
}

function composition(n) {
    return n < 1 ? [[]] : range(n).map(function(i) {
        return composition(n - i).map(function(j) {
            return [i].concat(j);
        });
    }).reduce(function(a, b) {
        return a.concat(b);
    });
}
</code>```

Golfed, ES6 (<s>169</s> <s>167</s> <s>119</s> <s>109</s> <s>105</s> <s>89</s> 85 bytes):

```<code>n=>n?[].concat(...[...Array(n)].map((x,i)=>i+1).map(b=>m(n-b).map(a=>[b,...a]))):[[]]
</code>```

答:
Haskell, 37 bytes

```<code>f 0=[[]]
f n=[a:x|a<-[1..n],x<-f$n-a]
</code>```

xnor saved two bytes.

ContentLicense: CC BY-SA 3.0

Title: List all ordered partitions of n

Body:
Haskell, 37 bytes

f 0=[[]]
f n=[a:x|a<-[1..n],x<-f$n-a]

xnor saved two bytes.


问:
Find the largest number n positions away from n
A sequel to this question.

Task

Given an array of positive integers, find the largest element k for which:

There exists some positive integer distance n, so that the element in the array located n places to the left or right from k equals n.

The array is guaranteed to contain at least one element satisfying this condition.

The shortest code (in bytes) wins. You may choose whichever I/O format you like.

Example

Given the input

```<code>[4, 6, 7, 9, 3, 6, 5, 7, 2]
</code>```

The eligible values are:

The 4, as there is a 7 located 7 positions to its right

The first 6, as there is a 3 located 3 positions to its right

The 3, as there is a 4 located 4 positions to its left

The 5, as there is a 2 located 2 positions to its right

The second 7, as there is a 3 located 3 positions to its left.

Of these values, the largest is 7.

Test cases

```<code>[1, 13] → 13
[2, 9, 8, 3, 72, 2] → 8
[5, 28, 14, 5, 6, 3, 4, 7] → 14
[1, 3, 5, 15, 4, 1, 2, 6, 7, 7] → 7
[5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3] → 5
[5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5] → 10
</code>```

答:
Octave / MATLAB, 40 Bytes

```<code>@(v)max(v(any(toeplitz(1:nnz(v))-v==1)))
</code>```

Input must be a column vector.

Thanks to Luis Mendo for suggestions saving 3 bytes (see comment)

Thanks to Suever for suggestions saving 4 more bytes (replacing ~~(sum()) with any())

Explanation:

Given an input vector v, this problem is equivalent to finding all solutions i,j of the following discrete equation,

```<code>abs(i-j) = v(i),   i,j both in 1..k,
</code>```

where abs() is the absolute value function. Each v(i) for which this equation is solved is one of the candidate solutions which we can maximize over.

As a discrete function of i and j, all possibilities for the left hand side can be arranged in the toeplitz matrix that looks something like this:

```<code>[0, 1, 2, 3, 4]
[1, 0, 1, 2, 3]
[2, 1, 0, 1, 2]    <--- abs(i-j)
[3, 2, 1, 0, 1]
[4, 3, 2, 1, 0]
</code>```

And since the right hand side doesn't depend on i, all possibilities for it can be arranged into a matrix where the columns are all copies of the input,

```<code>[v(1), v(1), v(1), v(1), v(1)]
[v(2), v(2), v(2), v(2), v(2)]
[v(3), v(3), v(3), v(3), v(3)]   <--- v(i)
[v(4), v(4), v(4), v(4), v(4)]
[v(5), v(5), v(5), v(5), v(5)]
</code>```

To find all solutions to the equation, we subtract these two matrices and find the locations where there is a zero. The rows where there is a zero correspond to the desired indices i's where there is a j such that abs(i-j) = v(i).

Other tricks:

It takes less characters to construct the absolute value function plus one, abs(i-j)+1, then check for locations where the difference is 1, rather than construct the true (unshifted) absolute value function.

Uses automatic operator broadcasting to implicitly make column copies of v

Gets the length of the input via nnz() instead of length(), which works since the inputs are said to be positive in the problem statement.

Body:
Octave / MATLAB, 40 Bytes

@(v)max(v(any(toeplitz(1:nnz(v))-v==1)))

Input must be a column vector.

Thanks to Luis Mendo for suggestions saving 3 bytes (see comment)

Thanks to Suever for suggestions saving 4 more bytes (replacing ~~(sum()) with any())

Explanation:

Given an input vector v, this problem is equivalent to finding all solutions i,j of the following discrete equation,

abs(i-j) = v(i),   i,j both in 1..k,

where abs() is the absolute value function. Each v(i) for which this equation is solved is one of the candidate solutions which we can maximize over.

As a discrete function of i and j, all possibilities for the left hand side can be arranged in the toeplitz matrix that looks something like this:

[0, 1, 2, 3, 4]
[1, 0, 1, 2, 3]
[2, 1, 0, 1, 2]    <--- abs(i-j)
[3, 2, 1, 0, 1]
[4, 3, 2, 1, 0]

And since the right hand side doesn't depend on i, all possibilities for it can be arranged into a matrix where the columns are all copies of the input,

[v(1), v(1), v(1), v(1), v(1)]
[v(2), v(2), v(2), v(2), v(2)]
[v(3), v(3), v(3), v(3), v(3)]   <--- v(i)
[v(4), v(4), v(4), v(4), v(4)]
[v(5), v(5), v(5), v(5), v(5)]

To find all solutions to the equation, we subtract these two matrices and find the locations where there is a zero. The rows where there is a zero correspond to the desired indices i's where there is a j such that abs(i-j) = v(i).

Other tricks:

It takes less characters to construct the absolute value function plus one, abs(i-j)+1, then check for locations where the difference is 1, rather than construct the true (unshifted) absolute value function.

Uses automatic operator broadcasting to implicitly make column copies of v

Gets the length of the input via nnz() instead of length(), which works since the inputs are said to be positive in the problem statement.


答:
CJam, 19 bytes

```<code>Lari{_1af.+1@f+|}*p
</code>```

Try it online!

Explanation

CJam doesn't have a useful combinatorics built-in for integer partitions. So we'll do this manually. To find all the ordered partitions of an integer n, we can look at a list of n ones and consider every possible way to insert separators. Then we'll sum the 1s in each section. Example for n = 3:

```<code>1 1 1 => 3
1 1|1 => 2|1
1|1 1 => 1|2
1|1|1 => 1|1|1
</code>```

I tried using a Cartesian product to generate all of these separators, but that ended up at 21 bytes. Instead I went back to this old technique for generating power sets (this is based on an old answer of Dennis's but I can't find it right now). The idea is this: to generate all partitions we can start from an empty list. Then n times we can make a binary decision: either we append a 1 (corresponds to a separator in the above example) or we increment the last value of the list (corresponds to not having a separator). To generate all partitions, we simply perform both operations at each step and keep all possible outputs for the next step. It turns out that in CJam, prepending and incrementing the first element is shorter, but the principle remains the same:

```<code>La       e# Push [[]] onto the stack. The outer list will be the list of
         e# all possible partitions at the current iteration, and we initialise
         e# it to one empty partition (basically all partitions of 0).
ri       e# Read input and convert to integer N.
{        e# Repeat this N times...
  _      e#   Duplicate the list of partitions of i-1.
  1af.+  e#   Increment the first element in each of these. This is done
         e#   by performing a pairwise addition between the partition and [1].
         e#   There is the catch that in the first iteration this will turn
         e#   the empty array into [1], so it's equivalent to the next step.
  1@f+   e#   Pull up the other copy of the list of partitions of i-1 and
         e#   prepend a 1 to each of them.
  |      e#   Set union. This gets rid of the duplicate result from the first
         e#   iteration (in all other iterations this is equivalent to concatenating
         e#   the two lists).
         e#   Voilà, a list of all partitions of i.
}*
p        e# Pretty-print the result.
</code>```

Title: List all ordered partitions of n

Body:
The challenge is to list all ordered partitions (composition (combinatorics)) of a given positive integer n. These are the lists of numbers from 1 to n whose sum is n. For example, given input n = 4, the result should be:

4

  1, 3

  3, 1

  2, 2

  2, 1, 1

  1, 2, 1

  1, 1, 2

  1, 1, 1, 1

The result can be in any order, but must contain each ordered partition once. This means that for n = 4, [1, 1, 2], [1, 2, 1] and [2, 1, 1] must all be part of the result.

Here's my own JavaScript code which achieves this:

```<code>function range(n) {
    for (var range = [], i = 0; i < n; range.push(++i));
    return range;
}

function composition(n) {
    return n < 1 ? [[]] : range(n).map(function(i) {
        return composition(n - i).map(function(j) {
            return [i].concat(j);
        });
    }).reduce(function(a, b) {
        return a.concat(b);
    });
}
</code>```

Golfed, ES6 (<s>169</s> <s>167</s> <s>119</s> <s>109</s> <s>105</s> <s>89</s> 85 bytes):

```<code>n=>n?[].concat(...[...Array(n)].map((x,i)=>i+1).map(b=>m(n-b).map(a=>[b,...a]))):[[]]
</code>```

Body:
CJam, 19 bytes

Lari{_1af.+1@f+|}*p

Try it online!

Explanation

CJam doesn't have a useful combinatorics built-in for integer partitions. So we'll do this manually. To find all the ordered partitions of an integer n, we can look at a list of n ones and consider every possible way to insert separators. Then we'll sum the 1s in each section. Example for n = 3:

1 1 1 => 3
1 1|1 => 2|1
1|1 1 => 1|2
1|1|1 => 1|1|1

I tried using a Cartesian product to generate all of these separators, but that ended up at 21 bytes. Instead I went back to this old technique for generating power sets (this is based on an old answer of Dennis's but I can't find it right now). The idea is this: to generate all partitions we can start from an empty list. Then n times we can make a binary decision: either we append a 1 (corresponds to a separator in the above example) or we increment the last value of the list (corresponds to not having a separator). To generate all partitions, we simply perform both operations at each step and keep all possible outputs for the next step. It turns out that in CJam, prepending and incrementing the first element is shorter, but the principle remains the same:

La       e# Push [[]] onto the stack. The outer list will be the list of
         e# all possible partitions at the current iteration, and we initialise
         e# it to one empty partition (basically all partitions of 0).
ri       e# Read input and convert to integer N.
{        e# Repeat this N times...
  _      e#   Duplicate the list of partitions of i-1.
  1af.+  e#   Increment the first element in each of these. This is done
         e#   by performing a pairwise addition between the partition and [1].
         e#   There is the catch that in the first iteration this will turn
         e#   the empty array into [1], so it's equivalent to the next step.
  1@f+   e#   Pull up the other copy of the list of partitions of i-1 and
         e#   prepend a 1 to each of them.
  |      e#   Set union. This gets rid of the duplicate result from the first
         e#   iteration (in all other iterations this is equivalent to concatenating
         e#   the two lists).
         e#   Voilà, a list of all partitions of i.
}*
p        e# Pretty-print the result.


答:
JavaScript (Firefox 30-57), 63 bytes

```<code>f=n=>n?[for(i of Array(n).keys())for(a of f(i))[n-i,...a]]:[[]]
</code>```

Title: List all ordered partitions of n

Body:
JavaScript (Firefox 30-57), 63 bytes

f=n=>n?[for(i of Array(n).keys())for(a of f(i))[n-i,...a]]:[[]]


答:
Julia, 113 Bytes

```<code>f(N)=unique(reduce(vcat,(map(x->[permutations(x)...],[vcat([1 for _=i+1:N],sum([1 for _=N-i:N-1])) for i=1:N]))))
</code>```

Non-recursive solution

Explained:

[vcat([1 for _=i+1:N],sum([1 for _=N-i:N-1])) for i=1:N] build a set of lists that sum to N, whose permutations will resemble the solution (e.g. for N=4: [[1,1,1,1],[1,1,2],[1,3],[4]])

map(x->[permutations(x)...],) Calculate all permutations

reduce(vcat,) combine them into a list of lists

unique() filter duplicates

Title: List all ordered partitions of n

Body:
Julia, 113 Bytes

f(N)=unique(reduce(vcat,(map(x->[permutations(x)...],[vcat([1 for _=i+1:N],sum([1 for _=N-i:N-1])) for i=1:N]))))

Non-recursive solution

Explained:

[vcat([1 for _=i+1:N],sum([1 for _=N-i:N-1])) for i=1:N] build a set of lists that sum to N, whose permutations will resemble the solution (e.g. for N=4: [[1,1,1,1],[1,1,2],[1,3],[4]])

map(x->[permutations(x)...],) Calculate all permutations

reduce(vcat,) combine them into a list of lists

unique() filter duplicates


答:
Python 2, 61 bytes

f=lambda n,s='1,':1/n*[eval(s)]or f(n-1,'1+'+s)+f(n-1,'1,'+s)
```

<p>This isn't the shortest, but I really like the method because it's so weird.</p>

<p>Recursively generates and evaluates <code>2**(n-1)</code> strings, like </p>

<pre class="lang-python prettyprint-override"><code>1+1+1+1,
1,1+1+1,
1+1,1+1,
1,1,1+1,
1+1+1,1,
1,1+1,1,
1+1,1,1,
1,1,1,1,
</code>```

for n=4. These strings evaluate to tuples representing all the partitions. Between any two 1's is either a +, joining them into a single number, or a ,, splitting adjacent sections.

Title: List all ordered partitions of n

Body:
Python 2, 61 bytes

f=lambda n,s='1,':1/n*[eval(s)]or f(n-1,'1+'+s)+f(n-1,'1,'+s)

This isn't the shortest, but I really like the method because it's so weird.

Recursively generates and evaluates 2**(n-1) strings, like

1+1+1+1,
1,1+1+1,
1+1,1+1,
1,1,1+1,
1+1+1,1,
1,1+1,1,
1+1,1,1,
1,1,1,1,

for n=4. These strings evaluate to tuples representing all the partitions. Between any two 1's is either a +, joining them into a single number, or a ,, splitting adjacent sections.


问:
Find the largest number that's adjacent to a zero
Challenge:

Take a vector / list of integers as input, and output the largest number that's adjacent to a zero.

Specifications:

As always, optional input and output format

You may assume that there will be at least one zero, and at least one non-zero element.

Test cases:

```<code>1 4 3 6 0 3 7 0
7

9 4 9 0 9 0 9 15 -2
9

-4 -6 -2 0 -9
-2

-11 0 0 0 0 0 -12 10
0

0 20
20
</code>```

Good luck and happy golfing!

答:
SPSS Syntax (98 bytes)

Golfed solution:

```<code>CRE L=lead(A,1).
COMP R=MAX(lag(A),L).
EXE.
SEL IF A=0.
EXE.
AGG
/S=MAX(R).
LIST S
/CAS=1.
</code>```

Ungolfed:

```<code>CREATE L=lead(A,1).
COMPUTE R=MAX(lag(A),L).
EXECUTE.
SELECT IF A=0.
EXECUTE.
AGGREGATE
/S=MAX(R).
LIST S
/CASES=1.
</code>```

Explanation:
Input values is ordered vertically in a column.
The first line of code creates a column with the lead number, the number before any given number. MAX(lag,A) returns the lagging number, the number after any given number (in test series A). So the second line of code creates a column with the highest number of neighbourging numbers of any given number. We are only interested in the neighbours of zeros, so the forth line selects all the rows with zeros, which now also include the highest valued neighbours. The 6th and 7th line of code finds the max value of selected neighbours.

With data inputs:

```<code>* This syntax solves: Returning the greatest adjacent number bigger or equal to itself,
  for any number V.
* CodeGolf asks for the solution for the case V=0.
* Bytes=98.

DATA LIST LIST
/ Sample (A7) a b c d e f g h i j k l m .
BEGIN DATA.
"A" 1, 4, 3, 6, 0, 3, 7, 0
"B" 9, 4, 9, 0, 9, 0, 9, 15, -2
"C" -4, -6, -2, 0, -9
"D" -11, 0, 0, 0, 0, 0, -12, 10
"E"  0, 20
END DATA.
DATASET NAME Inputs WINDOW=FRONT.

FLIP VARIABLES=a b c d e f g h i
/NEWNAMES=Sample.
DATASET NAME CodeGolf WINDOW=FRONT.
DATASET CLOSE Inputs.

CRE L=lead(A,1).
COMP R=MAX(lag(A),L).
EXE.
SEL IF A=0.
EXE.
AGG
/S=MAX(R).
LIST S
/CAS=1.
</code>```

Just change the sample references (A to E) for testing each sample.

Body:
SPSS Syntax (98 bytes)

Golfed solution:

CRE L=lead(A,1).
COMP R=MAX(lag(A),L).
EXE.
SEL IF A=0.
EXE.
AGG
/S=MAX(R).
LIST S
/CAS=1.

Ungolfed:

CREATE L=lead(A,1).
COMPUTE R=MAX(lag(A),L).
EXECUTE.
SELECT IF A=0.
EXECUTE.
AGGREGATE
/S=MAX(R).
LIST S
/CASES=1.

Explanation:
Input values is ordered vertically in a column.
The first line of code creates a column with the lead number, the number before any given number. MAX(lag,A) returns the lagging number, the number after any given number (in test series A). So the second line of code creates a column with the highest number of neighbourging numbers of any given number. We are only interested in the neighbours of zeros, so the forth line selects all the rows with zeros, which now also include the highest valued neighbours. The 6th and 7th line of code finds the max value of selected neighbours.

With data inputs:

* This syntax solves: Returning the greatest adjacent number bigger or equal to itself,
  for any number V.
* CodeGolf asks for the solution for the case V=0.
* Bytes=98.

DATA LIST LIST
/ Sample (A7) a b c d e f g h i j k l m .
BEGIN DATA.
"A" 1, 4, 3, 6, 0, 3, 7, 0
"B" 9, 4, 9, 0, 9, 0, 9, 15, -2
"C" -4, -6, -2, 0, -9
"D" -11, 0, 0, 0, 0, 0, -12, 10
"E"  0, 20
END DATA.
DATASET NAME Inputs WINDOW=FRONT.

FLIP VARIABLES=a b c d e f g h i
/NEWNAMES=Sample.
DATASET NAME CodeGolf WINDOW=FRONT.
DATASET CLOSE Inputs.

CRE L=lead(A,1).
COMP R=MAX(lag(A),L).
EXE.
SEL IF A=0.
EXE.
AGG
/S=MAX(R).
LIST S
/CAS=1.

Just change the sample references (A to E) for testing each sample.


问:
Substring Chainification

Introduction

For this example, let's take the string Hello, World! and the array [3, 2, 3]. To find the substring chain, we go through the following process:

The first number of the array is 3, so we get the substring [0 - 3], which is Hel. After that, we remove the first 3 characters from the initial string, which leaves us with lo, World!.

The second number of the array is 2, so we get the substring [0 - 2] from our new string, which gives us lo. The leftover string becomes , World!.

The last number is a 3, which gives us , W. The substring chain is all of the substrings combined, which gives us:

```<code>['Hel', 'lo', ', W']
</code>```

For a more visual example:

```<code>[3, 2, 3], 'Hello, World!'
3 -> Hel
2 ->    lo
3 ->      , W
</code>```

The task

Given a non-empty string and a non-empty array only consisting of positive integers (> 0), output the substring chain. You may assume that the sum of all integers in the array does not exceed the length of the string.

You can also assume that the strings will never contain any newlines.

Test cases

```<code>Input: abcdefghijk, [2, 1, 3]
Output: ['ab', 'c', 'def']

Input: Code Golf, [4, 1]
Output: ['Code', ' ']

Input: Ayyy, [3]
Output: ['Ayy']

Input: lexicographically, [2, 2, 2, 7, 4]
Output: ['le', 'xi', 'co', 'graphic', 'ally']
</code>```

This is code-golf, so the submission with the smallest number of bytes wins!

答:
PHP, 63 Bytes

```<code><?foreach($_GET[a]as$p){echo" ".substr($_GET[s],$s,$p);$s+=$p;}
</code>```

Output as Array 85 Bytes

```<code><?foreach($_GET["a"]as$p){$o[]=substr($_GET["s"],$s,$p);$s+=$p;}echo json_encode($o);
</code>```

Title: Substring Chainification

Body:
PHP, 63 Bytes

<?foreach($_GET[a]as$p){echo" ".substr($_GET[s],$s,$p);$s+=$p;}

Output as Array 85 Bytes

<?foreach($_GET["a"]as$p){$o[]=substr($_GET["s"],$s,$p);$s+=$p;}echo json_encode($o);


答:
T-SQL(sqlserver 2016), 132 bytes

Golfed:

```<code>;WITH C as(SELECT value*1v,row_number()over(order by 1/0)n FROM STRING_SPLIT(@,','))SELECT max(c.v)FROM C,C D WHERE abs(D.n-C.n)=D.v
</code>```

Ungolfed:

```<code>DECLARE @ varchar(max)='2, 9, 8, 3, 72, 2'

;WITH C as
(
  SELECT
    value*1v,
    row_number()over(order by 1/0)n
  FROM
    STRING_SPLIT(@,',')
)
SELECT
  max(c.v)
FROM
  C,C D
WHERE
  abs(D.n-C.n)=D.v
</code>```

Fiddle

Title: Find the largest number n positions away from n

Body:
A sequel to this question.

Task

Given an array of positive integers, find the largest element k for which:

There exists some positive integer distance n, so that the element in the array located n places to the left or right from k equals n.

The array is guaranteed to contain at least one element satisfying this condition.

The shortest code (in bytes) wins. You may choose whichever I/O format you like.

Example

Given the input

```<code>[4, 6, 7, 9, 3, 6, 5, 7, 2]
</code>```

The eligible values are:

The 4, as there is a 7 located 7 positions to its right

The first 6, as there is a 3 located 3 positions to its right

The 3, as there is a 4 located 4 positions to its left

The 5, as there is a 2 located 2 positions to its right

The second 7, as there is a 3 located 3 positions to its left.

Of these values, the largest is 7.

Test cases

```<code>[1, 13] → 13
[2, 9, 8, 3, 72, 2] → 8
[5, 28, 14, 5, 6, 3, 4, 7] → 14
[1, 3, 5, 15, 4, 1, 2, 6, 7, 7] → 7
[5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3] → 5
[5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5] → 10
</code>```

Body:
T-SQL(sqlserver 2016), 132 bytes

Golfed:

;WITH C as(SELECT value*1v,row_number()over(order by 1/0)n FROM STRING_SPLIT(@,','))SELECT max(c.v)FROM C,C D WHERE abs(D.n-C.n)=D.v

Ungolfed:

DECLARE @ varchar(max)='2, 9, 8, 3, 72, 2'

;WITH C as
(
  SELECT
    value*1v,
    row_number()over(order by 1/0)n
  FROM
    STRING_SPLIT(@,',')
)
SELECT
  max(c.v)
FROM
  C,C D
WHERE
  abs(D.n-C.n)=D.v

Fiddle


问:
Checkmate (aka the urinal problem)
My Precalc teacher has one of his favorite problems that he made up (or more likely <s>stole</s> inspired by xkcd) that involves a row of n urinals. "Checkmate" is a situation in which every urinal is already occupied OR has an occupied urinal next to them. For instance, if a person is an X, then

X-X--X

is considered checkmate. Note that a person cannot occupy a urinal next to an already occupied urinal.

Task

Your program will take a number through stdin, command line args, or a function argument. Your program will then print out or return the number of ways that checkmate can occur in with the inputted number of urinals.

Examples

0 -> 1 (the null case counts as checkmate)

1 -> 1 (X)

2 -> 2 (X- or -X)

3 -> 2 (X-X or -X-)

4 -> 3 (X-X-, -X-X, or X--X)

5 -> 4 (X-X-X, X--X-, -X-X-, or -X--X)

6 -> 5 (X-X-X-, X--X-X, X-X--X, -X--X- or -X-X-X)

7 -> 7 (X-X-X-X, X--X-X-, -X-X--X, -X--X-X, X-X--X-, X--X--X or -X-X-X-)

8 -> 9 (-X--X--X, -X--X-X-, -X-X--X-, -X-X-X-X, X--X--X-, X--X-X-X, X-X--X-X, X-X-X--X, X-X-X-X-)

...

Scoring

The smallest program in bytes wins.

答:
FRACTRAN, <s>104</s> 93 bytes

Input is 11**n*29 and output is 29**checkmate(n).

This is mostly for fun, especially since I'm currently being outgolfed by Python, JS, and Java. Same number of bytes as PHP though :D Golfing suggestions welcome.

```<code>403/85 5/31 3/5 9061/87 3/41 37/3 667/74 37/23 7/37 38/91 7/19 5/77 1/7 1/17 1/2 340/121 1/11
</code>```

Ungolfing

```<code>               At the start we have 11**n * 29
1/11           If n < 2, we remove the 11s and print 29**1
340/121        If n >= 2, we subtract two 11s (n-2) and add one 17, two 2s and one 5.
                 We now have 17**1 * 29**1 * 2**2 * 5.
                 These are the register for a, b, c at registers 17, 29, and 2.
                 5 is an indicator to start the first loop.
                 This loop will move a to register 13.
403/85 5/31    Remove the 17s one at a time, adds them to the 13 register.
                 5 and 31 reset the loop.
3/5            Next loop: moves b to a and adds b to a in register 13.
9061/87 3/41   Remove the 29s one at a time, adds them to the 17 and 13 registers.
                 3 and 41 reset the loop.
37/3           Next loop: moves c to b in register 29.
667/74 37/23   Remove the 2s one at a time, adds them to the 29 register.
                 37 and 23 reset the loop.
7/37           Next loop: moves a+b to c in register 2.
38/91 7/19     Remove the 13s one at a time, adds them to the 2 register.
                 7 and 19 reset the loop.
5/77           Move to the first loop if and only if we have an 11 remaining.
1/7 1/17 1/2   Remove the 7 loop indicator, and all 17s and 2s.
               Return 29**checkmate(n).
</code>```

Title: Checkmate (aka the urinal problem)

Body:
FRACTRAN, <s>104</s> 93 bytes

Input is 11**n*29 and output is 29**checkmate(n).

This is mostly for fun, especially since I'm currently being outgolfed by Python, JS, and Java. Same number of bytes as PHP though :D Golfing suggestions welcome.

403/85 5/31 3/5 9061/87 3/41 37/3 667/74 37/23 7/37 38/91 7/19 5/77 1/7 1/17 1/2 340/121 1/11

Ungolfing

               At the start we have 11**n * 29
1/11           If n < 2, we remove the 11s and print 29**1
340/121        If n >= 2, we subtract two 11s (n-2) and add one 17, two 2s and one 5.
                 We now have 17**1 * 29**1 * 2**2 * 5.
                 These are the register for a, b, c at registers 17, 29, and 2.
                 5 is an indicator to start the first loop.
                 This loop will move a to register 13.
403/85 5/31    Remove the 17s one at a time, adds them to the 13 register.
                 5 and 31 reset the loop.
3/5            Next loop: moves b to a and adds b to a in register 13.
9061/87 3/41   Remove the 29s one at a time, adds them to the 17 and 13 registers.
                 3 and 41 reset the loop.
37/3           Next loop: moves c to b in register 29.
667/74 37/23   Remove the 2s one at a time, adds them to the 29 register.
                 37 and 23 reset the loop.
7/37           Next loop: moves a+b to c in register 2.
38/91 7/19     Remove the 13s one at a time, adds them to the 2 register.
                 7 and 19 reset the loop.
5/77           Move to the first loop if and only if we have an 11 remaining.
1/7 1/17 1/2   Remove the 7 loop indicator, and all 17s and 2s.
               Return 29**checkmate(n).


答:
C,  205  191

```<code>p;r(c){return 1+c+3*(rand()%6>2*c);}main(i,c,q,s){for(c=51-getchar();++i<23;printf("%u %u\n",q,s))q=r(c),p+=(s=r(-~c%3))<q;printf("%ser wins with %u points",p<11?"Comput":"Us",p<11?21-p:p);}
</code>```

Reads the user's choice from stdin.

Title: Non-transitive dice game

Body:
Those of you who like Numberphile would be familiar with Dr. James Grime, who described a non-transitive dice game on his channel.

The game consists of three 6-faced dice:

Die 1: 3,3,3,3,3,6

Die 2: 2,2,2,5,5,5

Die 3: 1,4,4,4,4,4

Two players each select a die to use. They roll them and the higher die wins, best-of-whatever.

Probabilistically, die 1 beats dies 2 with >50% chance. Similarly, die 2 beats die 3, and, interestingly, die 3 beats die 1.

Write a program taking 1, 2 or 3 as input. This indicates the die the user chooses. The program then choose the die that would beat the user and output the results of 21 rolls, and "Computer/User wins with x points"

Rules

Code-golf, votes as tiebreaker

You must use RNG (or the likes) to actually simulate the dice rolls.

I am not too strict on output format. It's okay as long as you show the dices, somehow separate between the 21 rolls (in a way different from how you separate the dice in the same roll), and output that sentence above.

Input can be stdin, command line argument, from screen, etc.

Example

Input

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

Output

```<code>4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 6
1 3
4 3
4 3
1 3
4 3
1 3
4 3
4 3
4 3
4 3
4 6
 Computer wins with 16 points
</code>```

Here, the user chooses die 1 and his rolls are shown on the right column. The program chooses die 3 and beats him.

Body:
C,  205  191

p;r(c){return 1+c+3*(rand()%6>2*c);}main(i,c,q,s){for(c=51-getchar();++i<23;printf("%u %u\n",q,s))q=r(c),p+=(s=r(-~c%3))<q;printf("%ser wins with %u points",p<11?"Comput":"Us",p<11?21-p:p);}

Reads the user's choice from stdin.


答:
R, 48 54 bytes

```<code>s=scan()

w=which;max(s[c(w(s==0)+1,w(s==0)-1)],na.rm=T)
</code>```

Reads vector from console input, then takes the maximum over all values adjacent to 0.

Edit: Catches NAs produced at the boundary, thanks rturnbull!

Title: Find the largest number that's adjacent to a zero

Body:
Challenge:

Take a vector / list of integers as input, and output the largest number that's adjacent to a zero.

Specifications:

As always, optional input and output format

You may assume that there will be at least one zero, and at least one non-zero element.

Test cases:

```<code>1 4 3 6 0 3 7 0
7

9 4 9 0 9 0 9 15 -2
9

-4 -6 -2 0 -9
-2

-11 0 0 0 0 0 -12 10
0

0 20
20
</code>```

Good luck and happy golfing!

Body:
R, 48 54 bytes

s=scan()

w=which;max(s[c(w(s==0)+1,w(s==0)-1)],na.rm=T)

Reads vector from console input, then takes the maximum over all values adjacent to 0.

Edit: Catches NAs produced at the boundary, thanks rturnbull!


答:
CJam, <s>17</s> 14 bytes

```<code>ri"X)"m*{~]p}/
</code>```

Try it online!

Explanation

I know I said that using the Cartesian product is longer, but I ended up finding a way to use it more efficiently. I think that both approaches are interesting in their own right, so I'm putting them in separate posts.

This is still based on the idea that, we can choose n times between appending a 1 to the current partition or to increment the last element of the current partition. In this solution, we do this by generating 2n-1 different programs which correspond to these different choices.

```<code>ri      e# Read input and convert to integer N.
        e# Decrement.
"X)"m*  e# Get all strings of length N which consist of 'X' and ')'. If
        e# we treat these strings as CJam code then 'X' pushes a 1 and ')'
        e# increments the top of the stack.
        e# Note that some of these strings will begin with an increment that
        e# doesn't have anything on the stack to work with. This will result in
        e# an error and terminate the program. Luckily, the programs are ordered
        e# such that all programs starting with 'X' are first in the list, so
        e# we get to print all the 2^(N-1) permutations before erroring out.
{       e# For each of these programs (well for the first half of them)...
  ~     e#   Evaluate the string as CJam code. This leaves the partition as
        e#   individual integers on the stack.
  ]p    e#   Wrap the stack in a list and pretty-print it.
}/
</code>```

Title: List all ordered partitions of n

Body:
CJam, <s>17</s> 14 bytes

ri"X)"m*{~]p}/

Try it online!

Explanation

I know I said that using the Cartesian product is longer, but I ended up finding a way to use it more efficiently. I think that both approaches are interesting in their own right, so I'm putting them in separate posts.

This is still based on the idea that, we can choose n times between appending a 1 to the current partition or to increment the last element of the current partition. In this solution, we do this by generating 2n-1 different programs which correspond to these different choices.

ri      e# Read input and convert to integer N.
        e# Decrement.
"X)"m*  e# Get all strings of length N which consist of 'X' and ')'. If
        e# we treat these strings as CJam code then 'X' pushes a 1 and ')'
        e# increments the top of the stack.
        e# Note that some of these strings will begin with an increment that
        e# doesn't have anything on the stack to work with. This will result in
        e# an error and terminate the program. Luckily, the programs are ordered
        e# such that all programs starting with 'X' are first in the list, so
        e# we get to print all the 2^(N-1) permutations before erroring out.
{       e# For each of these programs (well for the first half of them)...
  ~     e#   Evaluate the string as CJam code. This leaves the partition as
        e#   individual integers on the stack.
  ]p    e#   Wrap the stack in a list and pretty-print it.
}/


问:
Alexa and the Tea Plantation
Hey guys, first time poster here. I went on Coderoulette recently and some guy posted this question. I looked around online but it doesn't seem to be anywhere. I figured I would post it here for anyone who is a fan of these types of problems. Enjoy!

Alexa is a druid who loves Mathematics! She lives in the land of Alfa, taking care of a tea plantation.

The plantation has N plants and the height of the ith plant is Hi.

Alexa has developed a recent interest in palindromes. She wants to crop the plants so the height of the plants forms a palindrome (without any reordering). She has 2 spells in her arsenal- the 'Growlith' spell will increase the height of a plant by 1 unit, the 'Shrinkooza' spell will decrease the height of a plant by 1 unit. The 'Growlith' and 'Shrinkooza' spells cost A and B units of magic respectively. Help Alexa find the minimum units of magic, that shall enable her to fulfill her objective.

Input Format

First line contains an integer T. T testcases follow.

First line of each test case consists of 3 space-separated integers N, A and B.

Next line consists of N space-separated integers, the initial height of the plants.

Output Format

Print the answer to each test case on a new line.

Constraints

1 <= T <= 10

1 <= N <= 105

0 <= A, B <= 108

1 <= Hi <= 103

Example

Input

```<code>1
5 2 2
1 6 2 3 4
</code>```

Output

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

Explanation

She can use the 'Growlith' spell on the first plant 3 times and the 'Shrinkooza' spell on the second plant 3 times to form 4 3 2 3 4.

Challenge

Write code that will create a palindrome using the least units of magic possible for N plants.

Scoring

This is code golf. The shortest code in bytes wins.

答:
JavaScript (ES6), 70 bytes

```<code>f=(a,g,s)=>a.reduce((t,h,i)=>t+Math.abs(a[a.length+~i]-h),0)*(g>s?s:g)/2
</code>```

Double-counts the differences, but we only need to make half the changes, which is achieved by dividing by 2 at the end.

Title: Alexa and the Tea Plantation

Body:
JavaScript (ES6), 70 bytes

f=(a,g,s)=>a.reduce((t,h,i)=>t+Math.abs(a[a.length+~i]-h),0)*(g>s?s:g)/2

Double-counts the differences, but we only need to make half the changes, which is achieved by dividing by 2 at the end.


问:
Is it an Odd Word?

Challenge

Given a single word as input, determine if the word is odd or even.

Odd and Even words

Assume the general rules:

```<code>odd + odd = even
even + odd = odd
odd + even = odd
even + even = even
</code>```

In the alphabet, the odd letters are:

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

And the even letters are:

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

The same applies to capital letters (AEIOU are odd and BCDFGHJKLMNPQRSTVWXYZ are even).

You then 'add' each of the letters in the word together. For example, the word cats is equivalent to:

```<code>even + odd + even + even
</code>```

Which simplifies to:

```<code>odd + even
</code>```

Which simplifies further to:

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

So the word cats is odd.

Examples

```<code>Input:  trees
Output: even
</code>```

```<code>Input:  brush
Output: odd
</code>```

```<code>Input:  CAts
Output: odd
</code>```

```<code>Input:  Savoie
Output: even
</code>```

```<code>Input:  rhythm
Output: even
</code>```

Rules

All input will be a single word which will only contain alphabetical characters.

If the word is odd, output a truthy value. If the word is even, output a falsey value.

Winning

The shortest code in bytes wins.

答:
Julia, 53 Bytes

```<code>f(s)=sum(map(x->x in ["aeiouAEIOU"...]?1:2,[s...]))%2
</code>```

replace odd characters with 1 and even characters with 2, then sum up. if the sum is even, then the word is even.

Title: Is it an Odd Word?

Body:
Julia, 53 Bytes

f(s)=sum(map(x->x in ["aeiouAEIOU"...]?1:2,[s...]))%2

replace odd characters with 1 and even characters with 2, then sum up. if the sum is even, then the word is even.


答:
Pyth, <s>7</s> 6 bytes

7 byte solution:

Pyth has an integer partition builtin ./, so 5 of the 7 bytes is getting the orderings.

```<code>{s.pM./
</code>```

Try it online!

Explanation:

```<code>     ./  Integer partition (sorted by default)
  .pM    get all the orderings of each of the partitions as a nested list of lists of orderings
 s       Flatten by one layer
{        Remove duplicates
</code>```

6 byte solution:

If you have a list, ./ will compute with orderings; all that remains is to make the lists numbers again.

```<code>lMM./m
</code>```

Try it online!

Explanation:

```<code>     m  Get lists by gathering a list of [0, 1,...input] (I could use U as well)

   ./   Partition with orderings
 MM     Map an operation across each of the orderings lists of elements
l       where that operation is the length of the sublists
</code>```

Title: List all ordered partitions of n

Body:
The challenge is to list all ordered partitions (composition (combinatorics)) of a given positive integer n. These are the lists of numbers from 1 to n whose sum is n. For example, given input n = 4, the result should be:

4

  1, 3

  3, 1

  2, 2

  2, 1, 1

  1, 2, 1

  1, 1, 2

  1, 1, 1, 1

The result can be in any order, but must contain each ordered partition once. This means that for n = 4, [1, 1, 2], [1, 2, 1] and [2, 1, 1] must all be part of the result.

Here's my own JavaScript code which achieves this:

```<code>function range(n) {
    for (var range = [], i = 0; i < n; range.push(++i));
    return range;
}

function composition(n) {
    return n < 1 ? [[]] : range(n).map(function(i) {
        return composition(n - i).map(function(j) {
            return [i].concat(j);
        });
    }).reduce(function(a, b) {
        return a.concat(b);
    });
}
</code>```

Golfed, ES6 (<s>169</s> <s>167</s> <s>119</s> <s>109</s> <s>105</s> <s>89</s> 85 bytes):

```<code>n=>n?[].concat(...[...Array(n)].map((x,i)=>i+1).map(b=>m(n-b).map(a=>[b,...a]))):[[]]
</code>```

Body:
Pyth, <s>7</s> 6 bytes

7 byte solution:

Pyth has an integer partition builtin ./, so 5 of the 7 bytes is getting the orderings.

{s.pM./

Try it online!

Explanation:

     ./  Integer partition (sorted by default)
  .pM    get all the orderings of each of the partitions as a nested list of lists of orderings
 s       Flatten by one layer
{        Remove duplicates

6 byte solution:

If you have a list, ./ will compute with orderings; all that remains is to make the lists numbers again.

lMM./m

Try it online!

Explanation:

     m  Get lists by gathering a list of [0, 1,...input] (I could use U as well)

   ./   Partition with orderings
 MM     Map an operation across each of the orderings lists of elements
l       where that operation is the length of the sublists


Title: List all ordered partitions of n

Body:
Ruby, 61 bytes

f=->n{n<1?[[]]:(1..n).map{|i|f[n-i].map{|x|x<<i}}.flatten(1)}

ungolfed

f=->n{
  n < 1 ?
    [[]]
  :
    (1..n).map { |i|
      f[n-i].map { |x|
        x << i
      }
    }.flatten(1)
}

usage

p f[4]
# => [[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3], [2, 1, 1], [2, 2], [3, 1], [4]]


问:
Create output twice the length of the code

The Challenge

Write a complete program that writes twice as many bytes to standard output as the length of the program.

Rules

The program must write ASCII characters to the standard output.

The contents of the output doesn't matter.

The output, measured in bytes, must be exactly twice the length of the program, also measured in bytes, unless you fulfill the bonus.

Any trailing newline is included in the output's byte count.

Bonus

Your program can optionally take a number, n, as input. If so, the output must be exactly n * program length bytes. You can assume that n will always be a positive integer. If no input is provided, n must default to 2.

If you do this,  you can subtract 25 bytes from your score.

Shortest program wins.

Restrictions

No standard loopholes.

The program must be at least 1 byte long.

No adding unnecessary whitespace to the source code to change its length. Similarly, comments don't count.

Unless you fulfill the bonus, the program must accept no input. If you do fulfill the bonus, the integer must be the only input.

Lowest score (program length in bytes - bonus) wins.

The shortest answer for each language wins for that language.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

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 leaderboard snippet:

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

var QUESTION_ID=59436,OVERRIDE_USER=41505;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){e.owner.user_id===OVERRIDE_USER&&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&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").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.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(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*([^\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}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Nim, 27 bytes

```<code>echo getStackTrace()[0..51]
</code>```

Prints the first 53 bytes of the following, plus a trailing newline:

```<code>Traceback (most recent call last)
<filename>.nim(1)       <filename>
</code>```

Note that despite having the filename in the output, this answer's validity is not dependant on the length of the filename. For example, saved in x.nim, this is output:

```<code>Traceback (most recent call last)
x.nim(1)
</code>```

There are nine trailing spaces there. Conversely, when saved in areallylongfilename.nim, this is output:

```<code>Traceback (most recent call last)
areallylongfilena
</code>```

Newlines are also output in each example. Example usage:

```<code>$ nim c length.nim
$ ./length | wc -c
54
</code>```

Body:
Nim, 27 bytes

echo getStackTrace()[0..51]

Prints the first 53 bytes of the following, plus a trailing newline:

Traceback (most recent call last)
<filename>.nim(1)       <filename>

Note that despite having the filename in the output, this answer's validity is not dependant on the length of the filename. For example, saved in x.nim, this is output:

Traceback (most recent call last)
x.nim(1)

There are nine trailing spaces there. Conversely, when saved in areallylongfilename.nim, this is output:

Traceback (most recent call last)
areallylongfilena

Newlines are also output in each example. Example usage:

$ nim c length.nim
$ ./length | wc -c
54


答:
JavaScript (ES6), <s> 56 54 </s> 53 bytes

l=>l.map((n,i)=>m=Math.min(m,~l[i+n],~l[i-n]),m=0)|~m
```

Try it online!

Body:
JavaScript (ES6), <s> 56 54 </s> 53 bytes

l=>l.map((n,i)=>m=Math.min(m,~l[i+n],~l[i-n]),m=0)|~m

Try it online!

ContentLicense: CC BY-SA 4.0


答:
Scala, 52 - 25 = 27 bytes

```<code>object A extends App{println("#"*(args(0).toInt*52)}
</code>```

Simply prints the string # repeated (arg * lengthOfCode) times.

Title: Create output twice the length of the code

Body:
The Challenge

Write a complete program that writes twice as many bytes to standard output as the length of the program.

Rules

The program must write ASCII characters to the standard output.

The contents of the output doesn't matter.

The output, measured in bytes, must be exactly twice the length of the program, also measured in bytes, unless you fulfill the bonus.

Any trailing newline is included in the output's byte count.

Bonus

Your program can optionally take a number, n, as input. If so, the output must be exactly n * program length bytes. You can assume that n will always be a positive integer. If no input is provided, n must default to 2.

If you do this,  you can subtract 25 bytes from your score.

Shortest program wins.

Restrictions

No standard loopholes.

The program must be at least 1 byte long.

No adding unnecessary whitespace to the source code to change its length. Similarly, comments don't count.

Unless you fulfill the bonus, the program must accept no input. If you do fulfill the bonus, the integer must be the only input.

Lowest score (program length in bytes - bonus) wins.

The shortest answer for each language wins for that language.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

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 leaderboard snippet:

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

var QUESTION_ID=59436,OVERRIDE_USER=41505;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){e.owner.user_id===OVERRIDE_USER&&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&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").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.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(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*([^\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}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Scala, 52 - 25 = 27 bytes

object A extends App{println("#"*(args(0).toInt*52)}

Simply prints the string # repeated (arg * lengthOfCode) times.


Title: Non-transitive dice game

Body:
R - 228

d=matrix(rep(c(rep(3,5),6,2,2,2,5,5,5,1,rep(4,5)),2),6)
x=scan()
r=expand.grid(Computer=d[,x+2],User=d[,x])[sample(36,21,T),]
print(r)
s=summary.factor(names(r)[max.col(r)])
cat(names(which.max(s)),"wins with",max(s),"points\n")

Example run:

> source('ntd.R')
1: 2
2:
Read 1 item
     Computer User
28          3    5
31          3    5
36          6    5
18          6    2
11          3    2
31.1        3    5
14          3    2
8           3    2
9           3    2
17          3    2
2           3    2
29          3    5
3           3    2
16          3    2
4           3    2
21          3    5
14.1        3    2
23          3    5
16.1        3    2
17.1        3    2
19          3    5
Computer wins with 14 points


答:
T-SQL, 203 bytes

Golfed:

```<code>USE master
DECLARE @ INT=12

;WITH z as( SELECT top(@)cast(number+1as varchar(max))a FROM spt_values WHERE'P'=type),c as(SELECT a*1a,a b FROM z UNION ALL SELECT c.a+z.a,b+','+z.a FROM c,z WHERE c.a+z.a*1<=@)SELECT b FROM c WHERE a=@
</code>```

Ungolfed:

```<code>USE master --needed to make sure it is executed from the correct database
DECLARE @ INT=12

;WITH z as
(
  SELECT top(@)cast(number+1as varchar(max))a
  FROM spt_values
  WHERE'P'=type
),c as
(
  SELECT a*1a,a b
  FROM z
  UNION ALL
  SELECT c.a+z.a,b+','+z.a
  FROM c,z
  WHERE c.a+z.a*1<=@
)
SELECT b
FROM c
WHERE a=@
</code>```

Fiddle

Title: List all ordered partitions of n

Body:
T-SQL, 203 bytes

Golfed:

USE master
DECLARE @ INT=12

;WITH z as( SELECT top(@)cast(number+1as varchar(max))a FROM spt_values WHERE'P'=type),c as(SELECT a*1a,a b FROM z UNION ALL SELECT c.a+z.a,b+','+z.a FROM c,z WHERE c.a+z.a*1<=@)SELECT b FROM c WHERE a=@

Ungolfed:

USE master --needed to make sure it is executed from the correct database
DECLARE @ INT=12

;WITH z as
(
  SELECT top(@)cast(number+1as varchar(max))a
  FROM spt_values
  WHERE'P'=type
),c as
(
  SELECT a*1a,a b
  FROM z
  UNION ALL
  SELECT c.a+z.a,b+','+z.a
  FROM c,z
  WHERE c.a+z.a*1<=@
)
SELECT b
FROM c
WHERE a=@

Fiddle


答:
05AB1E, 7 - 25 = -18 bytes

Saved a byte thanks to Okx.

```<code>YI7*ð×?
</code>```

Try it online!

Explanation

```<code>Y       # push 2
 I      # push input
  7*    # multiply top of stack with 6 (program length)
    ð×  # repeat <space> that many times
      ? # print top of stack
</code>```

Body:
05AB1E, 7 - 25 = -18 bytes

Saved a byte thanks to Okx.

YI7*ð×?

Try it online!

Explanation

Y       # push 2
 I      # push input
  7*    # multiply top of stack with 6 (program length)
    ð×  # repeat <space> that many times
      ? # print top of stack


答:
Java 8, 82 Bytes

```<code>interface A{static void main(String[]s){for(A a:new A[164])System.out.println();}}
</code>```

Prints out 164 empty lines.

Body:
Java 8, 82 Bytes

interface A{static void main(String[]s){for(A a:new A[164])System.out.println();}}

Prints out 164 empty lines.


答:
MATL, 13 Bytes

```<code>ttn:tYTq=a)X>
</code>```

Input must be a column vector. I.e., input is semicolon-separated like [1;2;3], or comma separated with a transpose tick at the end like [1,2,3]'.

Try it online!

All test cases: (A), (B), (C), (D), (E), (F)

Thanks to Suever for suggestions in the MATL chatroom to save 2 characters.

Explanation:

The overall strategy is the same as my Octave/MATLAB answer, where the basic concept is explained:
https://codegolf.stackexchange.com/a/94161/42247

The specific code in this MATL answer is built up as follows:

The core of the method is the construction of the Toeplitz matrix whose ij'th entry is abs(i-j). We first construct the Toeplitz matrix with entries abs(i-1)+1 with MATL's toeplitz command YT as follows:

```<code>n:tYT % Equivalent to @(v)toeplitz(1:length(v))
</code>```

To see how this works, let us call the input vector to this code snippet 'v'. The 'n' finds the length of v, then ':' constructs the vector 1:length(v). Next the 't' makes another copy of 1:length(v) on the stack; this extra copy is needed due to a well-known bug in the YT function in MATL (the MATL equivalent of toeplitz()), wherein it expects two copies of the input instead of 1. Then YT takes the two copies of this vector 1:length(v) off the stack, and makes the abs(i-j)+1 Toeplitz matrix from them.

Now we need to subtract 1 from this matrix to get the Toeplitz matrix with entries abs(i-j), and find the ij locations where this abs(i-j) Toeplitz matrix is equal to the matrix of all column vectors containing column-copies of the input vector v. This is done as follows:

```<code>t n:tYT q=
% t [code] q= is equivalent to @(v) [code](v)-1 == v
</code>```

The first 't' makes an extra copy of the input and stores it on the stack. The 'n:tYT' makes the toeplitz matrix as described earlier and outputs it into the stack. Then 'q' subtracts 1 from the Toeplitz matrix, and '=' does the elementwise equality comparison between the abs(i-j) matrix and the vector whose columns are copies of the input. Note that by comparing a column vector to a matrix, we are implicitly taking advantage of MATLAB/MATL's operator broadcasting rules (the column vector in the comparison gets copied to make a matrix without issuing any commands).

Finally, we need to find the row indices i where there is a column j such that the ij'th entry in the matrix difference constructed above equals 1, then get the value of the input vector corresponding to these indices, then take the maximum. This in the following three steps:

1) Find the indices for any row that contains a nonzero:

```<code>tn:tYTq= a
% [code] a is equivalent to @(v) any([code](v))
</code>```

2) Extract the elements of the input vector corresponding to those indices:

```<code>t tn:tYTq= a ) X>
% t [code] ) is equivalent to @(v) v([code](v)]
</code>```

3) Find and return the maximum element:

```<code>t tn:tYTq= a ) X>
% [code] X> is equivalent to @(v) max(v).
</code>```

Body:
A sequel to this question.

Task

Given an array of positive integers, find the largest element k for which:

There exists some positive integer distance n, so that the element in the array located n places to the left or right from k equals n.

The array is guaranteed to contain at least one element satisfying this condition.

The shortest code (in bytes) wins. You may choose whichever I/O format you like.

Example

Given the input

```<code>[4, 6, 7, 9, 3, 6, 5, 7, 2]
</code>```

The eligible values are:

The 4, as there is a 7 located 7 positions to its right

The first 6, as there is a 3 located 3 positions to its right

The 3, as there is a 4 located 4 positions to its left

The 5, as there is a 2 located 2 positions to its right

The second 7, as there is a 3 located 3 positions to its left.

Of these values, the largest is 7.

Test cases

```<code>[1, 13] → 13
[2, 9, 8, 3, 72, 2] → 8
[5, 28, 14, 5, 6, 3, 4, 7] → 14
[1, 3, 5, 15, 4, 1, 2, 6, 7, 7] → 7
[5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3] → 5
[5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5] → 10
</code>```

Body:
MATL, 13 Bytes

ttn:tYTq=a)X>

Input must be a column vector. I.e., input is semicolon-separated like [1;2;3], or comma separated with a transpose tick at the end like [1,2,3]'.

Try it online!

All test cases: (A), (B), (C), (D), (E), (F)

Thanks to Suever for suggestions in the MATL chatroom to save 2 characters.

Explanation:

The overall strategy is the same as my Octave/MATLAB answer, where the basic concept is explained:
https://codegolf.stackexchange.com/a/94161/42247

The specific code in this MATL answer is built up as follows:

The core of the method is the construction of the Toeplitz matrix whose ij'th entry is abs(i-j). We first construct the Toeplitz matrix with entries abs(i-1)+1 with MATL's toeplitz command YT as follows:

n:tYT % Equivalent to @(v)toeplitz(1:length(v))

To see how this works, let us call the input vector to this code snippet 'v'. The 'n' finds the length of v, then ':' constructs the vector 1:length(v). Next the 't' makes another copy of 1:length(v) on the stack; this extra copy is needed due to a well-known bug in the YT function in MATL (the MATL equivalent of toeplitz()), wherein it expects two copies of the input instead of 1. Then YT takes the two copies of this vector 1:length(v) off the stack, and makes the abs(i-j)+1 Toeplitz matrix from them.

Now we need to subtract 1 from this matrix to get the Toeplitz matrix with entries abs(i-j), and find the ij locations where this abs(i-j) Toeplitz matrix is equal to the matrix of all column vectors containing column-copies of the input vector v. This is done as follows:

t n:tYT q=
% t [code] q= is equivalent to @(v) [code](v)-1 == v

The first 't' makes an extra copy of the input and stores it on the stack. The 'n:tYT' makes the toeplitz matrix as described earlier and outputs it into the stack. Then 'q' subtracts 1 from the Toeplitz matrix, and '=' does the elementwise equality comparison between the abs(i-j) matrix and the vector whose columns are copies of the input. Note that by comparing a column vector to a matrix, we are implicitly taking advantage of MATLAB/MATL's operator broadcasting rules (the column vector in the comparison gets copied to make a matrix without issuing any commands).

Finally, we need to find the row indices i where there is a column j such that the ij'th entry in the matrix difference constructed above equals 1, then get the value of the input vector corresponding to these indices, then take the maximum. This in the following three steps:

1) Find the indices for any row that contains a nonzero:

tn:tYTq= a
% [code] a is equivalent to @(v) any([code](v))

2) Extract the elements of the input vector corresponding to those indices:

t tn:tYTq= a ) X>
% t [code] ) is equivalent to @(v) v([code](v)]

3) Find and return the maximum element:

t tn:tYTq= a ) X>
% [code] X> is equivalent to @(v) max(v).


问:
Is this number a prime?
Believe it or not, we do not yet have a code golf challenge for a simple primality test. While it may not be the most interesting challenge, particularly for "usual" languages, it can be nontrivial in many languages.

Rosetta code features lists by language of idiomatic approaches to primality testing, one using the Miller-Rabin test specifically and another using trial division. However, "most idiomatic" often does not coincide with "shortest." In an effort to make Programming Puzzles and Code Golf the go-to site for code golf, this challenge seeks to compile a catalog of the shortest approach in every language, similar to "Hello, World!" and Golf you a quine for great good!.

Furthermore, the capability of implementing a primality test is part of our definition of programming language, so this challenge will also serve as a directory of proven programming languages.

Task

Write a full program that, given a strictly positive integer n as input, determines whether n is prime and prints a truthy or falsy value accordingly.

For the purpose of this challenge, an integer is prime if it has exactly two strictly positive divisors. Note that this excludes 1, who is its only strictly positive divisor.

Your algorithm must be deterministic (i.e., produce the correct output with probability 1) and should, in theory, work for arbitrarily large integers. In practice, you may assume that the input can be stored in your data type, as long as the program works for integers from 1 to 255.

Input

If your language is able to read from STDIN, accept command-line arguments or any other alternative form of user input, you can read the integer as its decimal representation, unary representation (using a character of your choice), byte array (big or little endian) or single byte (if this is your languages largest data type).

If (and only if) your language is unable to accept any kind of user input, you may hardcode the input in your program.

In this case, the hardcoded integer must be easily exchangeable. In particular, it may appear only in a single place in the entire program.

For scoring purposes, submit the program that corresponds to the input 1.

Output

Output has to be written to STDOUT or closest alternative.

If possible, output should consist solely of a truthy or falsy value (or a string representation thereof), optionally followed by a single newline.

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.

Additional rules

This is not about finding the language with the shortest approach for prime testing, this is about finding the shortest approach 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.

The language Piet, for example, will be scored in codels, which is the natural choice for this language.

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

Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program performs a primality test, then congrats for paving the way for a very boring answer.

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.

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.

Built-in functions for testing primality are allowed. This challenge is meant to catalog the shortest possible solution in each language, so if it's shorter to use a built-in in your language, go for it.

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 catalog as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.

Catalog

The Stack Snippet at the bottom of this post generates the catalog 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

```

答:
PHP, <s>70</s> 65 bytes

```<code>for($i=2;$i<$n=$argv[1];$i++)if(is_int($n/$i)?1:0){echo 0;break;}
</code>```

Empty output if the number is prime, print 0 if the number is not prime.

Not very original or best answer, but this is it...

Test online

Title: Is this number a prime?

Body:
PHP, <s>70</s> 65 bytes

for($i=2;$i<$n=$argv[1];$i++)if(is_int($n/$i)?1:0){echo 0;break;}

Empty output if the number is prime, print 0 if the number is not prime.

Not very original or best answer, but this is it...

Test online


答:
GNU sed, 55 + 2(rn flags) = 57 bytes

1H;1d;G;:;s=.(\n.*)\n(.)=\1\2\n=;t;s=.==;P;s=[^\n]*==;h
```

<p><strong>Try it online!</strong> (thanks to @Dennis for adding sed)</p>

<p><strong>Explanation:</strong> The input string should be on the first line and the numbers, in unary, on separate lines after that. A new line is read implicitly at the start of a cycle, running the script each time.</p>

<pre class="lang-sed prettyprint-override"><code>1H;1d                       # once: append string to hold space and start new cycle
                            #Initially, the hold space contains an useful '\n'.
G                           # append hold space to pattern space. The pattern space
                            #format will be: 'UNARY\n\nSTRING'.
:;s=.(\n.*)\n(.)=\1\2\n=;t  # iteratively remove a char from the string, as many
                            #times as unary chars, and store it on 2nd pattern line
s=.==;P                     # remove '\n', then print the new top line
s=[^\n]*==;h                # delete up to '\n' and update hold space
</code>```

Test run: using a here-document with EOF as the end marker

sed -rnf program.sed << EOF
> abcdefghijk
> 00
> 0
> 000
> EOF
```

<p><strong>Output:</strong></p>

<pre class="lang-sh prettyprint-override"><code>ab
c
def
</code>```

Title: Substring Chainification

Body:
Introduction

For this example, let's take the string Hello, World! and the array [3, 2, 3]. To find the substring chain, we go through the following process:

The first number of the array is 3, so we get the substring [0 - 3], which is Hel. After that, we remove the first 3 characters from the initial string, which leaves us with lo, World!.

The second number of the array is 2, so we get the substring [0 - 2] from our new string, which gives us lo. The leftover string becomes , World!.

The last number is a 3, which gives us , W. The substring chain is all of the substrings combined, which gives us:

```<code>['Hel', 'lo', ', W']
</code>```

For a more visual example:

```<code>[3, 2, 3], 'Hello, World!'
3 -> Hel
2 ->    lo
3 ->      , W
</code>```

The task

Given a non-empty string and a non-empty array only consisting of positive integers (> 0), output the substring chain. You may assume that the sum of all integers in the array does not exceed the length of the string.

You can also assume that the strings will never contain any newlines.

Test cases

```<code>Input: abcdefghijk, [2, 1, 3]
Output: ['ab', 'c', 'def']

Input: Code Golf, [4, 1]
Output: ['Code', ' ']

Input: Ayyy, [3]
Output: ['Ayy']

Input: lexicographically, [2, 2, 2, 7, 4]
Output: ['le', 'xi', 'co', 'graphic', 'ally']
</code>```

This is code-golf, so the submission with the smallest number of bytes wins!

Body:
GNU sed, 55 + 2(rn flags) = 57 bytes

1H;1d;G;:;s=.(\n.*)\n(.)=\1\2\n=;t;s=.==;P;s=[^\n]*==;h

Try it online! (thanks to @Dennis for adding sed)

Explanation: The input string should be on the first line and the numbers, in unary, on separate lines after that. A new line is read implicitly at the start of a cycle, running the script each time.

1H;1d                       # once: append string to hold space and start new cycle
                            #Initially, the hold space contains an useful '\n'.
G                           # append hold space to pattern space. The pattern space
                            #format will be: 'UNARY\n\nSTRING'.
:;s=.(\n.*)\n(.)=\1\2\n=;t  # iteratively remove a char from the string, as many
                            #times as unary chars, and store it on 2nd pattern line
s=.==;P                     # remove '\n', then print the new top line
s=[^\n]*==;h                # delete up to '\n' and update hold space

Test run: using a here-document with EOF as the end marker

sed -rnf program.sed << EOF
> abcdefghijk
> 00
> 0
> 000
> EOF

Output:

ab
c
def


答:
q, 29 bytes

```<code>{mod[sum x in "aeiouAEIOU";2]}
</code>```

Title: Is it an Odd Word?

Body:
Challenge

Given a single word as input, determine if the word is odd or even.

Odd and Even words

Assume the general rules:

```<code>odd + odd = even
even + odd = odd
odd + even = odd
even + even = even
</code>```

In the alphabet, the odd letters are:

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

And the even letters are:

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

The same applies to capital letters (AEIOU are odd and BCDFGHJKLMNPQRSTVWXYZ are even).

You then 'add' each of the letters in the word together. For example, the word cats is equivalent to:

```<code>even + odd + even + even
</code>```

Which simplifies to:

```<code>odd + even
</code>```

Which simplifies further to:

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

So the word cats is odd.

Examples

```<code>Input:  trees
Output: even
</code>```

```<code>Input:  brush
Output: odd
</code>```

```<code>Input:  CAts
Output: odd
</code>```

```<code>Input:  Savoie
Output: even
</code>```

```<code>Input:  rhythm
Output: even
</code>```

Rules

All input will be a single word which will only contain alphabetical characters.

If the word is odd, output a truthy value. If the word is even, output a falsey value.

Winning

The shortest code in bytes wins.

Body:
q, 29 bytes

{mod[sum x in "aeiouAEIOU";2]}


答:
Mathematica 10.0, 44 bytes

An attempt without using partition-related builtins. From each ordered partition of size k, two successor partitions of k + 1 are generated: one by prepending 1, and the other by incrementing the first value.

```<code>Nest[##&[{1,##},{#+1,##2}]&@@@#&,{{1}},#-1]&
</code>```

A funnier, but sadly 2 bytes longer way of implementing the same idea:

```<code>#@{1}&/@Tuples[Prepend[1]@*MapAt[#+1&,1],#-1]&
</code>```

Title: List all ordered partitions of n

Body:
The challenge is to list all ordered partitions (composition (combinatorics)) of a given positive integer n. These are the lists of numbers from 1 to n whose sum is n. For example, given input n = 4, the result should be:

4

  1, 3

  3, 1

  2, 2

  2, 1, 1

  1, 2, 1

  1, 1, 2

  1, 1, 1, 1

The result can be in any order, but must contain each ordered partition once. This means that for n = 4, [1, 1, 2], [1, 2, 1] and [2, 1, 1] must all be part of the result.

Here's my own JavaScript code which achieves this:

```<code>function range(n) {
    for (var range = [], i = 0; i < n; range.push(++i));
    return range;
}

function composition(n) {
    return n < 1 ? [[]] : range(n).map(function(i) {
        return composition(n - i).map(function(j) {
            return [i].concat(j);
        });
    }).reduce(function(a, b) {
        return a.concat(b);
    });
}
</code>```

Golfed, ES6 (<s>169</s> <s>167</s> <s>119</s> <s>109</s> <s>105</s> <s>89</s> 85 bytes):

```<code>n=>n?[].concat(...[...Array(n)].map((x,i)=>i+1).map(b=>m(n-b).map(a=>[b,...a]))):[[]]
</code>```

Body:
Mathematica 10.0, 44 bytes

An attempt without using partition-related builtins. From each ordered partition of size k, two successor partitions of k + 1 are generated: one by prepending 1, and the other by incrementing the first value.

Nest[##&[{1,##},{#+1,##2}]&@@@#&,{{1}},#-1]&

A funnier, but sadly 2 bytes longer way of implementing the same idea:

#@{1}&/@Tuples[Prepend[1]@*MapAt[#+1&,1],#-1]&


问:
String Distance

Challenge

Given an input of an all-lowercase string [a-z], output the total distance between the letters.

Example

```<code>Input: golf

Distance from g to o : 8
Distance from o to l : 3
Distance from l to f : 6

Output: 17
</code>```

Rules

Standard loopholes forbidden

This is code-golf - shortest answer in bytes wins.

The alphabet can be traversed from either direction. You must always use the shortest path. (i.e the distance between x and c is 5).

Test cases

```<code>Input: aa
Output: 0

Input: stack
Output: 18

Input: zaza
Output: 3

Input: valleys
Output: 35
</code>```

答:
C#, 87 85 bytes

Improved solution - replaced Math.Abs() with the add & modulo trick to save 2 bytes:

```<code>s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=(s[i]-s[++i]+26)%26)>13?26-d:d;return l;};
</code>```

Initial solution:

```<code>s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;};
</code>```

Try it online!

Full source, including test cases:

```<code>using System;

namespace StringDistance
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,int>f= s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;};

            Console.WriteLine(f("golf"));   //17
            Console.WriteLine(f("aa"));     //0
            Console.WriteLine(f("stack"));  //18
            Console.WriteLine(f("zaza"));   //3
            Console.WriteLine(f("valleys"));//35
        }
    }
}
</code>```

Title: String Distance

Body:
C#, 87 85 bytes

Improved solution - replaced Math.Abs() with the add & modulo trick to save 2 bytes:

s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=(s[i]-s[++i]+26)%26)>13?26-d:d;return l;};

Initial solution:

s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;};

Try it online!

Full source, including test cases:

using System;

namespace StringDistance
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,int>f= s=>{int l=0,d,i=0;for(;i<s.Length-1;)l+=(d=Math.Abs(s[i]-s[++i]))>13?26-d:d;return l;};

            Console.WriteLine(f("golf"));   //17
            Console.WriteLine(f("aa"));     //0
            Console.WriteLine(f("stack"));  //18
            Console.WriteLine(f("zaza"));   //3
            Console.WriteLine(f("valleys"));//35
        }
    }
}


答:
Ruby 1.8, 165

```<code>i,s,*d=getc,21,[4]*5<<1,[3]*5<<6,[2,5]*3
puts"#{s.times{p r=[i,i-1].map{|o|d[o%3][rand 6]};s+=r[0]<=>r[1]}>s?"Human":"Computer"} wins with #{[s/=2,21-s].max} points"
</code>```

getc gets the ascii value of the input (ruby 1.8 only), which happily is congruent modulo 3 to its integer value.

s starts out at 21, so s.times{code} will execute code 21 times and return 21.  On each iteration, the loop either adds or subtracts 1 from s depending on who wins, so we can see who won by seeing whether s has ended up below 21.  Neat so far, but then I need the clumsy expression [s/=2,21-s].max to extract the actual number of points.  I've long wanted to do arithmetic with the return value of <=>, so I'm happy anyway.

Title: Non-transitive dice game

Body:
Those of you who like Numberphile would be familiar with Dr. James Grime, who described a non-transitive dice game on his channel.

The game consists of three 6-faced dice:

Die 1: 3,3,3,3,3,6

Die 2: 2,2,2,5,5,5

Die 3: 1,4,4,4,4,4

Two players each select a die to use. They roll them and the higher die wins, best-of-whatever.

Probabilistically, die 1 beats dies 2 with >50% chance. Similarly, die 2 beats die 3, and, interestingly, die 3 beats die 1.

Write a program taking 1, 2 or 3 as input. This indicates the die the user chooses. The program then choose the die that would beat the user and output the results of 21 rolls, and "Computer/User wins with x points"

Rules

Code-golf, votes as tiebreaker

You must use RNG (or the likes) to actually simulate the dice rolls.

I am not too strict on output format. It's okay as long as you show the dices, somehow separate between the 21 rolls (in a way different from how you separate the dice in the same roll), and output that sentence above.

Input can be stdin, command line argument, from screen, etc.

Example

Input

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

Output

```<code>4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 6
1 3
4 3
4 3
1 3
4 3
1 3
4 3
4 3
4 3
4 3
4 6
 Computer wins with 16 points
</code>```

Here, the user chooses die 1 and his rolls are shown on the right column. The program chooses die 3 and beats him.

Body:
Ruby 1.8, 165

i,s,*d=getc,21,[4]*5<<1,[3]*5<<6,[2,5]*3
puts"#{s.times{p r=[i,i-1].map{|o|d[o%3][rand 6]};s+=r[0]<=>r[1]}>s?"Human":"Computer"} wins with #{[s/=2,21-s].max} points"

getc gets the ascii value of the input (ruby 1.8 only), which happily is congruent modulo 3 to its integer value.

s starts out at 21, so s.times{code} will execute code 21 times and return 21.  On each iteration, the loop either adds or subtracts 1 from s depending on who wins, so we can see who won by seeing whether s has ended up below 21.  Neat so far, but then I need the clumsy expression [s/=2,21-s].max to extract the actual number of points.  I've long wanted to do arithmetic with the return value of <=>, so I'm happy anyway.


答:
><>, 25+2 = 27 bytes

```<code>211rv
v!?:<r@+@:$r-1
>rn;
</code>```

Needs the input to be present on the stack at program start, so +2 bytes for the -v flag. Try it online!

The first line initialises the stack to 1 1 2 n, where n is the input number. The second line, running backwards, checks that n is greater than 1. If it is, n is decremented and the next element in the sequence is generated as follows:

```<code>r$:@+@r              a(n-3) a(n-2) a(n-1) n

r        Reverse   - n a(n-1) a(n-2) a(n-3)
 $       Swap      - n a(n-1) a(n-3) a(n-2)
  :      Duplicate - n a(n-1) a(n-3) a(n-2) a(n-2)
   @     Rotate 3  - n a(n-1) a(n-2) a(n-3) a(n-2)
    +    Add       - n a(n-1) a(n-2) a(n)
     @   Rotate 3  - n a(n) a(n-1) a(n-2)
      r  Reverse   - a(n-2) a(n-1) a(n) n
</code>```

The final line outputs the number on the bottom of the stack, which is the required element in the sequence.

Title: Checkmate (aka the urinal problem)

Body:
My Precalc teacher has one of his favorite problems that he made up (or more likely <s>stole</s> inspired by xkcd) that involves a row of n urinals. "Checkmate" is a situation in which every urinal is already occupied OR has an occupied urinal next to them. For instance, if a person is an X, then

X-X--X

is considered checkmate. Note that a person cannot occupy a urinal next to an already occupied urinal.

Task

Your program will take a number through stdin, command line args, or a function argument. Your program will then print out or return the number of ways that checkmate can occur in with the inputted number of urinals.

Examples

0 -> 1 (the null case counts as checkmate)

1 -> 1 (X)

2 -> 2 (X- or -X)

3 -> 2 (X-X or -X-)

4 -> 3 (X-X-, -X-X, or X--X)

5 -> 4 (X-X-X, X--X-, -X-X-, or -X--X)

6 -> 5 (X-X-X-, X--X-X, X-X--X, -X--X- or -X-X-X)

7 -> 7 (X-X-X-X, X--X-X-, -X-X--X, -X--X-X, X-X--X-, X--X--X or -X-X-X-)

8 -> 9 (-X--X--X, -X--X-X-, -X-X--X-, -X-X-X-X, X--X--X-, X--X-X-X, X-X--X-X, X-X-X--X, X-X-X-X-)

...

Scoring

The smallest program in bytes wins.

Body:
><>, 25+2 = 27 bytes

211rv
v!?:<r@+@:$r-1
>rn;

Needs the input to be present on the stack at program start, so +2 bytes for the -v flag. Try it online!

The first line initialises the stack to 1 1 2 n, where n is the input number. The second line, running backwards, checks that n is greater than 1. If it is, n is decremented and the next element in the sequence is generated as follows:

r$:@+@r              a(n-3) a(n-2) a(n-1) n

r        Reverse   - n a(n-1) a(n-2) a(n-3)
 $       Swap      - n a(n-1) a(n-3) a(n-2)
  :      Duplicate - n a(n-1) a(n-3) a(n-2) a(n-2)
   @     Rotate 3  - n a(n-1) a(n-2) a(n-3) a(n-2)
    +    Add       - n a(n-1) a(n-2) a(n)
     @   Rotate 3  - n a(n) a(n-1) a(n-2)
      r  Reverse   - a(n-2) a(n-1) a(n) n

The final line outputs the number on the bottom of the stack, which is the required element in the sequence.


问:
Make An ASCII Poker Chip Stack Arrangement
Poker has etiquette in how you arrange your chips, often enforced in tournaments - your chips may not be "hidden" from your opponents by being behind others, mostly to not hide some large denomination chip(s).

The Challenge

We are going to be playing poker in ASCII, so we need to write a function or program that will draw our ASCII chip stack arrangement given its total value, n.

Input

- A positive integer, n (up to 2**32-1 should be handled)

Output

- An ASCII representation of the stack arrangement as defined below.

This may contain white-space to the right of each line such that no line is longer than one more character than the length used by printable characters in the longest (bottom) line;

This may contain a single trailing new line; and

The characters representing chips may be in lowercase if you prefer.

The stack arrangement will:

Contain the fewest chips possible, given the denominations (see below);

Will have equal valued chips in "stacks" (columns);

Be ordered such that the shorter stacks are to the right of taller stacks; and

Be ordered such that stacks with greater denomination chips will be to the right of equal sized stacks of lower denominations (representing that they are visible to our opponent(s) on the right)

The chips themselves are to be represented as individual characters identifying their colour:

```<code>    White : 1    = W
      Red : 5    = R
    Green : 25   = G
    Black : 100  = B
   Yellow : 500  = Y
     Pink : 1K   = P
   Orange : 5K   = O
     Cyan : 25K  = C
  Magenta : 100K = M
Aqua-blue : 500K = A
 Lavender : 1M   = L
   Indigo : 5M   = I
Turquoise : 25M  = T
   Violet : 100M = V
   Silver : 500M = S
</code>```

Example

For n = 276,352 the smallest number of chips would be:

```<code>2 * 100K + 3 * 25K + 1 * 1K + 3 * 100 + 2 * 25 + 2 * 1
    MM         CCC       P        BBB       GG       WW
</code>```

The single P must go on the far right,

then the three stacks of size 2 must go next,

- but the MM must go furthest to the right followed by the GG and then the WW since 100K > 25 > 1
then the two stacks of size 3 go on the left,

- but the CCC must go to the right of the BBB since 25K > 100

Now we must place these chips into actual stacks, to make our output:

```<code>BC
BCWGM
BCWGMP
</code>```

Test Cases

```<code>Input:
1

Output:
W

Input:
9378278

Output:
L
LWGPCM
LWGPCMB
LWGPCMBI

Input:
22222222

Output:
ROI
ROI
ROIWBPML
ROIWBPML

Input:
1342185143

Output:
WRCIV
WRCIVOLS
WRCIVOLSGBMT

Input:
2147483647

Output:
RMIS
RMISPC
RMISPCWL
RMISPCWLGBYOTV

Input:
4294967295

Output:
S
S
S
S
SRML
SRMLGOIT
SRMLGOITBPCV
SRMLGOITBPCVA
</code>```

This is code-golf, so shortest code in bytes wins. No loopholes, yada yada, you know the drill.

Body:
PHP, 274 Bytes

$t=$argv[1];$n=[500,100,25,5,1];$c=YBGRWAMCOPSVTIL;foreach($n as$k=>$v)for($i=0;$i<3;)$r[$v*10**($i*3)]=$c[$k+$i++*5];krsort($r);foreach($r as$v=>$k)$t-=($x[$v]=floor($t/$v))*$v;ksort($x);arsort($x);for($y=max($x);$y;$y--){foreach($x as$k=>$v)if($v>=$y)echo$r[$k];echo"\n";}


问:
Create a pyramidal matrix
A pyramidal matrix is a square matrix where all numbers increase or decrease from the center point, like the two matrices below:

```<code>1  1  1  1  1
1  2  2  2  1
1  2  3  2  1
1  2  2  2  1
1  1  1  1  1
</code>```

Or:

```<code>3  3  3  3  3
3  2  2  2  3
3  2  1  2  3
3  2  2  2  3
3  3  3  3  3
</code>```

Given a non-zero integer n, create a pyramidal matrix where the numbers goes from 1 to n either in increasing order (if n<0), or decreasing order (if n>0) from the center. If n is even, then there will be 4 center numbers (see the examples).

As always:

Optional input and output format

Number of spaces, delimiter etc. is optional

Test cases:

```<code>1
1

-1
1

5
1  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  1
1  2  3  3  3  3  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  4  5  4  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  3  3  3  3  2  1
1  2  2  2  2  2  2  2  1
1  1  1  1  1  1  1  1  1

-5
5  5  5  5  5  5  5  5  5
5  4  4  4  4  4  4  4  5
5  4  3  3  3  3  3  4  5
5  4  3  2  2  2  3  4  5
5  4  3  2  1  2  3  4  5
5  4  3  2  2  2  3  4  5
5  4  3  3  3  3  3  4  5
5  4  4  4  4  4  4  4  5
5  5  5  5  5  5  5  5  5
</code>```

```<code>2
1  1  1  1
1  2  2  1
1  2  2  1
1  1  1  1

-2
2  2  2  2
2  1  1  2
2  1  1  2
2  2  2  2

-4
4  4  4  4  4  4  4  4
4  3  3  3  3  3  3  4
4  3  2  2  2  2  3  4
4  3  2  1  1  2  3  4
4  3  2  1  1  2  3  4
4  3  2  2  2  2  3  4
4  3  3  3  3  3  3  4
4  4  4  4  4  4  4  4
</code>```

答:
MATL, <s>26</s> 24 bytes

```<code>oXyG|to-:"TTYaQ]G0<?G+q|
</code>```

Try it online! Or verify all test cases (slightly modified code to serve as test suite).

Explanation

The code first builds the output array assuming positive input n. The array is initiallized as 1 for odd input or as the empty array for even input (this is created as an identity matrix with size equal to the parity of the input). Then the following is repeated n times for even input, and n-1 times for odd input: extend the array with a frame containing 0, and add 1 to all elements.

For example, the steps for input n are:

Initial array:

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

Extend with frame:

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

Add 1:

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

Extend with frame:

```<code>0 0 0 0 0
0 1 1 1 0
0 1 2 1 0
0 1 1 1 0
0 0 0 0 0
</code>```

Add 1:

```<code>1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
</code>```

This gives the correct output for positive input. If the input is negative, the array needs to be modified by adding the input minus 1 and taking the absolute value:

```<code>    3 3 3 3 3
    3 2 2 2 3
    3 2 1 2 3
    3 2 2 2 3
    3 3 3 3 3
</code>```

You can watch the array growing (modified code to show intermediate steps) at MATL Online! The interpreter is still a beta. If it doesn't work press "Run" again or reload the page.

Commented code

```<code>o        % Take input implicitly and push 0 if even or 1 if odd
Xy       % Identity matrix of that size. Gives either 1 or empty array
G|       % Absolute value of input
to-      % Subtract 1 if odd
:"       % For loop: repeat that many times
  TTYa   %   Add a frame of zeros in the two dimensions
  Q      %   Add 1 to all elements
]        % End for
G        % Push input again
0>       % is it negative?
?        % If so
  G      %   Push input again
  +      %   Add
  q      %   Subtract 1
  |      %   Absolute value
         % End if implicitly
         % Display implicitly
</code>```

Title: Create a pyramidal matrix

Body:
MATL, <s>26</s> 24 bytes

oXyG|to-:"TTYaQ]G0<?G+q|

Try it online! Or verify all test cases (slightly modified code to serve as test suite).

Explanation

The code first builds the output array assuming positive input n. The array is initiallized as 1 for odd input or as the empty array for even input (this is created as an identity matrix with size equal to the parity of the input). Then the following is repeated n times for even input, and n-1 times for odd input: extend the array with a frame containing 0, and add 1 to all elements.

For example, the steps for input n are:

Initial array:

1

Extend with frame:

0 0 0
0 1 0
0 0 0

Add 1:

1 1 1
1 2 1
1 1 1

Extend with frame:

0 0 0 0 0
0 1 1 1 0
0 1 2 1 0
0 1 1 1 0
0 0 0 0 0

Add 1:

1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1

This gives the correct output for positive input. If the input is negative, the array needs to be modified by adding the input minus 1 and taking the absolute value:

    3 3 3 3 3
    3 2 2 2 3
    3 2 1 2 3
    3 2 2 2 3
    3 3 3 3 3

You can watch the array growing (modified code to show intermediate steps) at MATL Online! The interpreter is still a beta. If it doesn't work press "Run" again or reload the page.

Commented code

o        % Take input implicitly and push 0 if even or 1 if odd
Xy       % Identity matrix of that size. Gives either 1 or empty array
G|       % Absolute value of input
to-      % Subtract 1 if odd
:"       % For loop: repeat that many times
  TTYa   %   Add a frame of zeros in the two dimensions
  Q      %   Add 1 to all elements
]        % End for
G        % Push input again
0>       % is it negative?
?        % If so
  G      %   Push input again
  +      %   Add
  q      %   Subtract 1
  |      %   Absolute value
         % End if implicitly
         % Display implicitly


答:
Jelly, <s>18</s> 17 bytes

```<code>|1ŒḄfR«þ`
AÇạẋ¡CG
</code>```

Try it online! or verify all test cases.

How it works

```<code>|1ŒḄfR«þ`  Helper link. Argument: k (positive integer)

|1         Take the bitwise OR with 1. This increments k if it is even.
  ŒḄ       Bounce; yield [1, 2, ..., k | 1, ..., 2, 1].
    fR     Filter range; remove elements not in [1, ..., k] from the array.
           This results in [1, 2, ..., k, ..., 2, 1] if k is odd and in
           [1, 2, ..., k, k, ..., 2, 1] if k is even.
        `  Pass the last return value as left and right argument to:
      «þ     Minimum table; take the minimum of each pair of elements in the
             generated array, returning a 2D array.

AÇạẋ¡CG      Main link. Argument: n

A            Take the absolute value of n.
 Ç           Call the helper link on the result.
     C       Complement; yield 1 - n.
    ¡        Conditional application:
   ẋ           If repeating the return value of Ç 1 - n times results in a non-
               empty array, i.e., if n < 1:
  ạ              Take the absolute differences of the generated integers and 1 - n.
      G      Grid; join columns by spaces, rows by linefeeds.
</code>```

Title: Create a pyramidal matrix

Body:
A pyramidal matrix is a square matrix where all numbers increase or decrease from the center point, like the two matrices below:

```<code>1  1  1  1  1
1  2  2  2  1
1  2  3  2  1
1  2  2  2  1
1  1  1  1  1
</code>```

Or:

```<code>3  3  3  3  3
3  2  2  2  3
3  2  1  2  3
3  2  2  2  3
3  3  3  3  3
</code>```

Given a non-zero integer n, create a pyramidal matrix where the numbers goes from 1 to n either in increasing order (if n<0), or decreasing order (if n>0) from the center. If n is even, then there will be 4 center numbers (see the examples).

As always:

Optional input and output format

Number of spaces, delimiter etc. is optional

Test cases:

```<code>1
1

-1
1

5
1  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  1
1  2  3  3  3  3  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  4  5  4  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  3  3  3  3  2  1
1  2  2  2  2  2  2  2  1
1  1  1  1  1  1  1  1  1

-5
5  5  5  5  5  5  5  5  5
5  4  4  4  4  4  4  4  5
5  4  3  3  3  3  3  4  5
5  4  3  2  2  2  3  4  5
5  4  3  2  1  2  3  4  5
5  4  3  2  2  2  3  4  5
5  4  3  3  3  3  3  4  5
5  4  4  4  4  4  4  4  5
5  5  5  5  5  5  5  5  5
</code>```

```<code>2
1  1  1  1
1  2  2  1
1  2  2  1
1  1  1  1

-2
2  2  2  2
2  1  1  2
2  1  1  2
2  2  2  2

-4
4  4  4  4  4  4  4  4
4  3  3  3  3  3  3  4
4  3  2  2  2  2  3  4
4  3  2  1  1  2  3  4
4  3  2  1  1  2  3  4
4  3  2  2  2  2  3  4
4  3  3  3  3  3  3  4
4  4  4  4  4  4  4  4
</code>```

Body:
Jelly, <s>18</s> 17 bytes

|1ŒḄfR«þ`
AÇạẋ¡CG

Try it online! or verify all test cases.

How it works

|1ŒḄfR«þ`  Helper link. Argument: k (positive integer)

|1         Take the bitwise OR with 1. This increments k if it is even.
  ŒḄ       Bounce; yield [1, 2, ..., k | 1, ..., 2, 1].
    fR     Filter range; remove elements not in [1, ..., k] from the array.
           This results in [1, 2, ..., k, ..., 2, 1] if k is odd and in
           [1, 2, ..., k, k, ..., 2, 1] if k is even.
        `  Pass the last return value as left and right argument to:
      «þ     Minimum table; take the minimum of each pair of elements in the
             generated array, returning a 2D array.

AÇạẋ¡CG      Main link. Argument: n

A            Take the absolute value of n.
 Ç           Call the helper link on the result.
     C       Complement; yield 1 - n.
    ¡        Conditional application:
   ẋ           If repeating the return value of Ç 1 - n times results in a non-
               empty array, i.e., if n < 1:
  ạ              Take the absolute differences of the generated integers and 1 - n.
      G      Grid; join columns by spaces, rows by linefeeds.