答:
JavaScript (ES6), <s>185</s> <s>177</s> ... 171 bytes

f=(a,s='')=>(a=(a[0]?a:[...(m='25455')+m+m].map((m,i)=>(a-=(k=a/(v/=m)|0)*v,k*16+i),v=1E9).sort((a,b)=>b-a)).map(n=>n>15&&(s+='SVTILAMCOPYBGRW'[n&15],n-16)),s&&f(a)+`
`+s)
```

<h3>Formatted and commented</h3>

<pre class="lang-js prettyprint-override"><code>(a, s = '') => (                           // a = bankroll OR array of chip stacks
  a = (                                    // s = string of chip initials for this iteration
    a[0] ?                                 // if 'a' already is an array:
      a                                    // use it as-is
    :                                      // else, 'a' is the bankroll:
      [...(m = '25455') + m + m]           // for each 'm' in [ 2, 5, 4, 5, 5, ... ] (x3)
      .map((m, i) =>                       // v = current chip value = previous value / m
        (                                  // k = floor(a / v) = number of these chips
          a -= (k = a / (v /= m) | 0) * v, // update remaining bankroll: a = a - k * v
          k * 16 + i                       // saved in array: chip index in bits 0-3
        ),                                 // and number of chips in bits 4+
        v = 1E9                            // initial chip value = 1 billion
      )                                    // (1B / 2 -> 500M, 500M / 5 -> 100M, etc.)
      .sort((a, b) => b - a)               // sort the chip stacks
  )                                        //
  .map(n =>                                // for each chip stack:
    n > 15 &&                              // if there's at least one remaining chip of
    (                                      // this kind:
      s += 'SVTILAMCOPYBGRW'[n & 15],      // append its initial to the string
      n - 16                               // decrement the number of chips in this stack
    )                                      //
  ),                                       // process recursive call if there was at least
  s && f(a) + '\n' + s                     // one non-empty chip stack (the next lines are
)                                          // appended at the beginning of the final string)
</code>```

Demo

let f=(a,s='')=>(a=(a[0]?a:[...(m='25455')+m+m].map((m,i)=>(a-=(k=a/(v/=m)|0)*v,k*16+i),v=1E9).sort((a,b)=>b-a)).map(n=>n>15&&(s+='SVTILAMCOPYBGRW'[n&15],n-16)),s&&f(a)+`
`+s)

function update() {
  document.getElementById('o').innerHTML = f(+document.getElementById('i').value);
}
update();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="i" value="1342185143" oninput="update()"><pre id="o">``````

Body:
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:
JavaScript (ES6), <s>185</s> <s>177</s> ... 171 bytes

f=(a,s='')=>(a=(a[0]?a:[...(m='25455')+m+m].map((m,i)=>(a-=(k=a/(v/=m)|0)*v,k*16+i),v=1E9).sort((a,b)=>b-a)).map(n=>n>15&&(s+='SVTILAMCOPYBGRW'[n&15],n-16)),s&&f(a)+`
`+s)

Formatted and commented

(a, s = '') => (                           // a = bankroll OR array of chip stacks
  a = (                                    // s = string of chip initials for this iteration
    a[0] ?                                 // if 'a' already is an array:
      a                                    // use it as-is
    :                                      // else, 'a' is the bankroll:
      [...(m = '25455') + m + m]           // for each 'm' in [ 2, 5, 4, 5, 5, ... ] (x3)
      .map((m, i) =>                       // v = current chip value = previous value / m
        (                                  // k = floor(a / v) = number of these chips
          a -= (k = a / (v /= m) | 0) * v, // update remaining bankroll: a = a - k * v
          k * 16 + i                       // saved in array: chip index in bits 0-3
        ),                                 // and number of chips in bits 4+
        v = 1E9                            // initial chip value = 1 billion
      )                                    // (1B / 2 -> 500M, 500M / 5 -> 100M, etc.)
      .sort((a, b) => b - a)               // sort the chip stacks
  )                                        //
  .map(n =>                                // for each chip stack:
    n > 15 &&                              // if there's at least one remaining chip of
    (                                      // this kind:
      s += 'SVTILAMCOPYBGRW'[n & 15],      // append its initial to the string
      n - 16                               // decrement the number of chips in this stack
    )                                      //
  ),                                       // process recursive call if there was at least
  s && f(a) + '\n' + s                     // one non-empty chip stack (the next lines are
)                                          // appended at the beginning of the final string)

Demo

let f=(a,s='')=>(a=(a[0]?a:[...(m='25455')+m+m].map((m,i)=>(a-=(k=a/(v/=m)|0)*v,k*16+i),v=1E9).sort((a,b)=>b-a)).map(n=>n>15&&(s+='SVTILAMCOPYBGRW'[n&15],n-16)),s&&f(a)+`
`+s)

function update() {
  document.getElementById('o').innerHTML = f(+document.getElementById('i').value);
}
update();

<input id="i" value="1342185143" oninput="update()"><pre id="o"></pre>


问:
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>```

答:
Scala, 94 bytes

```<code>a=>a.zipWithIndex.filter(p=>a.zipWithIndex.exists(x=>x._1==Math.abs(p._2-x._2))).unzip._1.max
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Scala, 94 bytes

a=>a.zipWithIndex.filter(p=>a.zipWithIndex.exists(x=>x._1==Math.abs(p._2-x._2))).unzip._1.max


问:
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.

答:
Jelly, 11 bytes

```<code>,’fR_2ß€So1
</code>```

Try it online! or verify all test cases.

How it works

```<code>,’fR_2ß€So1  Main link. Argument: n

 ’           Decrement; yield n - 1.
,            Pair; yield [n, n - 1].
   R         Range; yield [1, ..., n].
  f          Filter; keep the elements that are common to both lists.
             This yields [n, n - 1] if n > 1, [1] if n = 1, and [] if n < 1.
    _2       Subtract 2 from both elements, yielding [n - 2, n - 3], [-1], or [].
      ß€     Recursively call the main link for each integer in the list.
        S    Take the sum of the resulting return values.
         o1  Logical OR with 1; correct the result if n < 1.
</code>```

Title: Checkmate (aka the urinal problem)

Body:
Jelly, 11 bytes

,’fR_2ß€So1

Try it online! or verify all test cases.

How it works

,’fR_2ß€So1  Main link. Argument: n

 ’           Decrement; yield n - 1.
,            Pair; yield [n, n - 1].
   R         Range; yield [1, ..., n].
  f          Filter; keep the elements that are common to both lists.
             This yields [n, n - 1] if n > 1, [1] if n = 1, and [] if n < 1.
    _2       Subtract 2 from both elements, yielding [n - 2, n - 3], [-1], or [].
      ß€     Recursively call the main link for each integer in the list.
        S    Take the sum of the resulting return values.
         o1  Logical OR with 1; correct the result if n < 1.


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:
PHP, 128 Bytes

<?foreach(($i=$_GET[i])as$k=>$v){$k-$v<0?:!($i[$k-$v]>$m)?:$m=$i[$k-$v];if($k+$v<count($i))if($i[$k+$v]>$m)$m=$i[$k+$v];}echo$m;


问:
Hate/love conundrum

Challenge description

In this challenge, we only consider love and hate as feelings. If we want to utter a feeling expression of order N, we alternate between these two (starting with hate):

```<code>order | expression

1       I hate it.
2       I hate that I love it.
3       I hate that I love that I hate it.
4       I hate that I love that I hate that I love it.
</code>```

The pattern follows for every positive integer N. Given N, output the correspoinding feeling expression of order N.

Notes

Full stop (.) at the end of the expression is mandatory,

Trailing and leading whitespaces (including newlines) are permitted,

Output for a non-positive or non-integer N is undefined,

This is a code-golf challenge, so make your code as short as possible!

答:
Julia, 91 Bytes

Thought I add a julia solution:

```<code>f(N)=string("I hate ",join(["that I love that I hate " for _ in 1:N-1])[1:12*(N-1)],"it."))
</code>```

Title: Hate/love conundrum

Body:
Julia, 91 Bytes

Thought I add a julia solution:

f(N)=string("I hate ",join(["that I love that I hate " for _ in 1:N-1])[1:12*(N-1)],"it."))


问:
Close-Knit Words

Introduction

According to Rand Al'Thor's post in the Puzzling SE, a close-knit word is any word that contains three alphabetically consecutive letters (in any order).

Words like education, foghorn and cabaret are all considered close-knit words whereas words like learning, klaxon and perform are not close-knit words.

Challenge

The challenge is to code-golf a program capable of taking a single word as input (assumed lower case, for all intents and purposes) and to return output that (if available) lists all consecutive letter sets (also in lower case) if it is a close-knit word, and empty output if it is not a close-knit word.

Examples

```<code>Input: education
Output: cde

Input: foghorn
Output: fgh

Input: cabaret
Output: abc

Input: hijacking
Output: ghi, hij, ijk

Input: pneumonia
Output: mno, nop

Input: klaxon
Output: <<no output>>

Input: perform
Output: <<no output>>

Input: learning
Output: <<no output>>
</code>```

Rules

Whereas input is to be assumed to be a single lower-case word and output must be lower-case, the nature of the output will vary according to the choice of your coding language. Please select a form of output that will best suit the nature of the challenge, whether it be STDOUT, file output, array, etc.

Because this is code-golf, it will be a case of lowest number of bytes being the clear winner.

No silly loopholes.

I will not accept answers that have the consecutive letters in non-alphabetical order... So cab will not be deemed a suitable output for cabaret, for example.

Special note, while the "triplets" don't necessarily have to be in alphabetical order, but the characters within the triplets must be... so in the case of the word "performance", for example, the output mno,nop will be accepted, as will nop,mno. In the case of the word "hijacking", there are six ways that the triplets of ghi, hij and ijk could be arranged in a list, and all six permutations are acceptable as output.

Other than that, on your marks, get set, golf!

答:
Scala, 59 bytes

```<code>(s:Set[Char])=>'a'to'z'sliding 3 filter{_.toSet subsetOf s}
</code>```

Ungolfed:

```<code>(s:Set[Char]) => ('a' to 'z').sliding(3).filter{threeChars => threeChars.toSet.subsetOf(s)}
</code>```

Explanation:

```<code>(s:Set[Char])=>             //define a function with a Set of Chars called s as an argument
'a' to 'z'                  //create a Range of characters 'a' to 'z'
sliding 3                   //create an Iterator(Seq(a, b, c), Seq(b, c, d), Seq(c, d, e), ... , Seq(x, y, z))
filter{_.toSet subSetOf s}  //keep only the triplets which are a subset of s
</code>```

Title: Close-Knit Words

Body:
Scala, 59 bytes

(s:Set[Char])=>'a'to'z'sliding 3 filter{_.toSet subsetOf s}

Ungolfed:

(s:Set[Char]) => ('a' to 'z').sliding(3).filter{threeChars => threeChars.toSet.subsetOf(s)}

Explanation:

(s:Set[Char])=>             //define a function with a Set of Chars called s as an argument
'a' to 'z'                  //create a Range of characters 'a' to 'z'
sliding 3                   //create an Iterator(Seq(a, b, c), Seq(b, c, d), Seq(c, d, e), ... , Seq(x, y, z))
filter{_.toSet subSetOf s}  //keep only the triplets which are a subset of s


答:
Perl, 45 bytes

Includes +2 for -ap

Give numbers on a line on STDIN:

```<code>largest.pl <<< "5 12 2 5 4 7 3 3 6 2 10 5 5 5 4 1 8 5"
</code>```

largest.pl:

```<code>#!/usr/bin/perl -ap
($_)=sort{$b-$a}map@F[$^P=$n-$_,$n+++$_],@F
</code>```

One more byte can be gained by replacing ^P by the literal control character, but that leads to a warning on STDERR on recent perls.

Assumes largest number + array length < 2^32

Body:
Perl, 45 bytes

Includes +2 for -ap

Give numbers on a line on STDIN:

largest.pl <<< "5 12 2 5 4 7 3 3 6 2 10 5 5 5 4 1 8 5"

largest.pl:

#!/usr/bin/perl -ap
($_)=sort{$b-$a}map@F[$^P=$n-$_,$n+++$_],@F

One more byte can be gained by replacing ^P by the literal control character, but that leads to a warning on STDERR on recent perls.

Assumes largest number + array length < 2^32


问:
Emulate a 7-segment display

Task

The task is to display any of the 128 possible states of a
7-segment display.

Your program should accept a string of 7 characters ("bits") that are either 0 or 1.
First bit of input corresponds to segment A of the following illustration, the
second to B, etc (ignore dp):

How you represent the display is up to you -- a single Unicode or ASCII symbol,
ASCII art, grafically, or whatever you can come up with. However, each
input must have it's own distinct output. If you come up with something fancy I'm sure you can harvest upvotes by showing off some examples.

All 128 possible states of the display are:

Rules

Codegolf

As I said, any kind of output is allowed, but it would be nice if you specified it.

Input can be stdin or command line argument.

Examples

Input

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

Output

As ASCII/Unicode:

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

Different kinds of ASCII art (I'm not too good at this)

```<code> _   ╺┓  ╒╗   ---
 _|  ┏┛  ╔╝     |
|_   ┗╸  ╚╛   ---
              |
              ---
</code>```

Title: Emulate a 7-segment display

Body:
J (51)

1 2 1#"1[5 3$' #'{~,|:>0;(88707#:~7#7){>".&.>1!:1[1

output:

1101101
 ##
   #
 ##
#
 ##


问:
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.

答:
Python 2.7, <s>282</s> <s>248</s> 238 bytes

c=input();L=[]
for i in range(15):m=[5,1,25,5,1][i%5]*10**int("886665533322000"[i]);L+=[[c/m,i,"SVTILAMCOPYBGRW"[i]]];c%=m
L.sort();S=[]
while L[~1][0]:
 s=""
 for X in L[::-1]:
  if X[0]>0:X[0]-=1;s+=X[2]
 S+=[s]
for s in S[::-1]:print s
```

Explanation:

Fill list L with elements [quanity, chip_order, chip_character] indicating the quantity of each type of chip , where chip_order ensures chips of equal quantity get sorted in reverse order (higher value chips first). Take chips from L in reverse to build strings for each line. Print lines in reverse to get smallest lines on top.

Thanks to Blue for some of the improvements.

Body:
Python 2.7, <s>282</s> <s>248</s> 238 bytes

c=input();L=[]
for i in range(15):m=[5,1,25,5,1][i%5]*10**int("886665533322000"[i]);L+=[[c/m,i,"SVTILAMCOPYBGRW"[i]]];c%=m
L.sort();S=[]
while L[~1][0]:
 s=""
 for X in L[::-1]:
  if X[0]>0:X[0]-=1;s+=X[2]
 S+=[s]
for s in S[::-1]:print s

Explanation:

Fill list L with elements [quanity, chip_order, chip_character] indicating the quantity of each type of chip , where chip_order ensures chips of equal quantity get sorted in reverse order (higher value chips first). Take chips from L in reverse to build strings for each line. Print lines in reverse to get smallest lines on top.

Thanks to Blue for some of the improvements.


问:
Golf all the 16 logic gates with 2 inputs and 1 output!
For example, the gate A and B is a logic gate with 2 inputs and 1 output.

There are exactly 16 of them, because:

each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs

of the 4 possible inputs, each can have an output of truthy and falsey

therefore, there are 2^4 possible logic gates, which is 16.

Your task is to write 16 programs/functions which implement all of them separately.

Your functions/programs must be independent.

They are valid as long as they output truthy/falsey values, meaning that you can implement A or B in Python as lambda a,b:a+b, even if 2 is produced for A=True and B=True.

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

0,0,1,0 (A and not B)

0,0,1,1 (A)

0,1,0,0 (not A and B)

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

1,0,1,1 (B implies A)

1,1,0,0 (not A)

1,1,0,1 (A implies B)

1,1,1,0 (nand)

1,1,1,1 (true)

Where the first number is the output for A=false, B=false,
the second number is the output for A=false, B=true,
the third number is the output for A=true, B=false,
the fourth number is the output for A=true, B=true.

Leaderboard

var QUESTION_ID=82938,OVERRIDE_USER=48934;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+(?:\.\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

```

答:
Go (game), 33 stones, 73 intersections

If domino and chess are acceptable, then this. It can't be too golfy on a full 19x19 Go board. So I used small rectangular boards. The input is whether the stones marked 1 and 2 are present. The output is whether black wins. It uses area scoring, 0.5 komi, situational superko, no suicide. All black to play. Some are given multiple solutions.

White wins (2, 1x5):

```<code>➊━━━➋
</code>```

1 and 2 (3, 2x3):

```<code>➊◯➋
┗┷┛
</code>```

1 and not 2 (2, 1x5):

```<code>╺➊━➁╸
</code>```

1 (2, 1x5):

```<code>╺➊➁━╸
╺➊━━➁
➀━➁━╸
</code>```

Not 1 and 2 (2, 1x5):

```<code>╺➋━➀╸
</code>```

2 (2, 1x5):

```<code>╺➋➀━╸
</code>```

1 xor 2 (2, 2x3):

```<code>➀┯➁
┗┷┛
</code>```

1 or 2 (2, 1x5):

```<code>╺➊━➋╸
➀━━━➁
</code>```

1 nor 2 (2, 1x4):

```<code>➊━━➋
╺➀➁╸
</code>```

1 = 2 (2, 1x7):

```<code>╺━➀━➁━╸
</code>```

Not 2 (2, 1x3):

```<code>➊◯➋
┗┷┛
</code>```0

1 or not 2 (2, 1x4):

```<code>➊◯➋
┗┷┛
</code>```1

Not 1 (2, 1x3)

```<code>➊◯➋
┗┷┛
</code>```2

Not 1 or 2 (2, 1x4):

```<code>➁➀━╸
</code>```

1 nand 2 (2, 1x3):

```<code>➊━➋
</code>```

Black wins (2, 1x3):

```<code>➊➋╸
➀━➁
➊━➁
</code>```

This page helped me a bit: http://www.mathpuzzle.com/go.html

Maybe someone could find a 2 stone solution for 1 and 2 on a 1x9 board...

Body:
Go (game), 33 stones, 73 intersections

If domino and chess are acceptable, then this. It can't be too golfy on a full 19x19 Go board. So I used small rectangular boards. The input is whether the stones marked 1 and 2 are present. The output is whether black wins. It uses area scoring, 0.5 komi, situational superko, no suicide. All black to play. Some are given multiple solutions.

White wins (2, 1x5):

➊━━━➋

1 and 2 (3, 2x3):

➊◯➋
┗┷┛

1 and not 2 (2, 1x5):

╺➊━➁╸

1 (2, 1x5):

╺➊➁━╸
╺➊━━➁
➀━➁━╸

Not 1 and 2 (2, 1x5):

╺➋━➀╸

2 (2, 1x5):

╺➋➀━╸

1 xor 2 (2, 2x3):

➀┯➁
┗┷┛

1 or 2 (2, 1x5):

╺➊━➋╸
➀━━━➁

1 nor 2 (2, 1x4):

➊━━➋
╺➀➁╸

1 = 2 (2, 1x7):

╺━➀━➁━╸

Not 2 (2, 1x3):

➀➁╸

1 or not 2 (2, 1x4):

➀➁━╸
➀━➁╸
╺➊➁╸
➋➊━╸
➋━➊╸

Not 1 (2, 1x3)

➁➀╸

Not 1 or 2 (2, 1x4):

➁➀━╸

1 nand 2 (2, 1x3):

➊━➋

Black wins (2, 1x3):

➊➋╸
➀━➁
➊━➁

This page helped me a bit: http://www.mathpuzzle.com/go.html

Maybe someone could find a 2 stone solution for 1 and 2 on a 1x9 board...


问:
Wave-Particle Duality Laterally Programmatically
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:

. →  .

 . →   .

  . →    .

   . →     .

    . →      .

     . →       .

      . →        .

       . →         .

In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

/ → /\

\ → \/

/\ → /\/

\/ → \/\

/\/ → /\/\

\/\ → \/\/

/\/\ → /\/\/

\/\/ → \/\/\

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

The shortest code in bytes wins.

答:
Turtlèd, 32 bytes (noncompeting)

```<code>l!-[*+.r_]l(/r'\r)(\r'/)(." .")$
</code>```

Explanation:

```<code>[implicit]                       first cell is an asterisk

l                                move left, off the asterisk, so the '[*+.r_]' loop runs
 !                               take input into string var, char pointer=0, 1st char
  -                              decrement char pointer, mod length input

   [*    ]                       while current cell isn't *:
     +.                          increment string pointer, and write the pointed char
       r_                        move right, write * if pointed char is last char, else " "

          l                      move left

           (/    )               if the current cell is /
             r'\r                move right, write /, move right

                  (\   )         If the current cell is \
                    r'/          move right, write /

                        (.    )  If the current cell is .
                          " ."   Write " .", the first space overwriting the existing '.'

                               $ Program won't remove leading spaces when printing

    [implicit]                   Program prints grid after finishing execution
</code>```

Body:
Turtlèd, 32 bytes (noncompeting)

l!-[*+.r_]l(/r'\r)(\r'/)(." .")$

Explanation:

[implicit]                       first cell is an asterisk

l                                move left, off the asterisk, so the '[*+.r_]' loop runs
 !                               take input into string var, char pointer=0, 1st char
  -                              decrement char pointer, mod length input

   [*    ]                       while current cell isn't *:
     +.                          increment string pointer, and write the pointed char
       r_                        move right, write * if pointed char is last char, else " "

          l                      move left

           (/    )               if the current cell is /
             r'\r                move right, write /, move right

                  (\   )         If the current cell is \
                    r'/          move right, write /

                        (.    )  If the current cell is .
                          " ."   Write " .", the first space overwriting the existing '.'

                               $ Program won't remove leading spaces when printing

    [implicit]                   Program prints grid after finishing execution


答:
AnyDice, 51 bytes

```<code>function:A{ifA<3{result:(A+2)/2}result:[A-2]+[A-3]}
</code>```

There should be more AnyDice answers around here.

My solution defines a recursive function that calculates a(n)=a(n-2)+a(n-3). It returns a(0)=a(1)=1 and a(2)=2 using some integer division magic.

Try it online

Note: the output may look weird, and that's because it's usually used to output dice probabilities. Just look at the number to the left of the bar chart.

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:
AnyDice, 51 bytes

function:A{ifA<3{result:(A+2)/2}result:[A-2]+[A-3]}

There should be more AnyDice answers around here.

My solution defines a recursive function that calculates a(n)=a(n-2)+a(n-3). It returns a(0)=a(1)=1 and a(2)=2 using some integer division magic.

Try it online

Note: the output may look weird, and that's because it's usually used to output dice probabilities. Just look at the number to the left of the bar chart.


问:
Connect the pixels
Given a text like this:

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

Output the same text but by connecting the pixels with the characters ─│┌┐└┘├┤┬┴┼. If a pixel doesn't have any neighbours, don't change it.

So the output of the last text is:

```<code>│ ─┬── ┌─ │
└─ │  ┌┘  │
   └──┘  ─┘
</code>```

You can take input as a boolean array.

The input will always contain at least 1 pixel.

You can count box-drawing chars as 1 byte.

You can assume the input is padded with spaces.

Test cases

```<code>## #
=>
── #
</code>```

```<code>###
 #
=>
─┬─
 │
</code>```

```<code>##### ##
 # #  #
########
=>
─┬─┬─ ┌─
 │ │  │
─┴─┴──┴─
</code>```

```<code> # #
#####
 # #
=>
 │ │
─┼─┼─
 │ │
</code>```

```<code># # # # #
 # # # #
# # # # #
 # # # #
# # # # #
=>
# # # # #
 # # # #
# # # # #
 # # # #
# # # # #
</code>```

```<code>#####
#####
#####
#####
#####
=>
┌┬┬┬┐
├┼┼┼┤
├┼┼┼┤
├┼┼┼┤
└┴┴┴┘
</code>```

Since this is code-golf, the shortest code wins.

答:
Perl, <s>89</s> 88 bytes

Includes +2 for -0p. The special characters are counted as 1 byte, but to make them actually display as single characters it's best to also add the -C option.

Give input on STDIN with the lines space padded so they all have the same length:

```<code>perl -C connect.pl
# #### ## #
## #  ##  #
   ####  ##
^D
</code>```

connect.pl:

```<code>#!/usr/bin/perl -0p
/
/;$n=".{@-}";s%#%substr"#───│└┘┴│┌┐┬│├┤┼",/\G##/+2*/#\G/+4*/#$n\G/s+8*/\G#$n#/s,1%eg
</code>```

Title: Connect the pixels

Body:
Perl, <s>89</s> 88 bytes

Includes +2 for -0p. The special characters are counted as 1 byte, but to make them actually display as single characters it's best to also add the -C option.

Give input on STDIN with the lines space padded so they all have the same length:

perl -C connect.pl
# #### ## #
## #  ##  #
   ####  ##
^D

connect.pl:

#!/usr/bin/perl -0p
/
/;$n=".{@-}";s%#%substr"#───│└┘┴│┌┐┬│├┤┼",/\G##/+2*/#\G/+4*/#$n\G/s+8*/\G#$n#/s,1%eg


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

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

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

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

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

The program must not write anything to STDERR.

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

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

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

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

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

Standard loopholes are not allowed.

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

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

Catalogue

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
S.I.L.O.S, 9 bytes

```<code>:a
GOTO a
</code>```

Try it online!

Body:
S.I.L.O.S, 9 bytes

:a
GOTO a

Try it online!


答:
J, <s>31</s> <s>27</s> 23 bytes

Saved 4 bytes thanks to miles!

```<code>0{]_&(]}.,+/@}:)1 1 2"_
</code>```

An explanation is to come soon.

Old solution

```<code>(>.1&^)`(-&3+&$:-&2)@.(2&<)
</code>```

This is an agenda. The LHS is a gerund composed of two verbs: >.1&^ and -&3+&$:-&2. The first one is used if the condition (2&<) fails. That means the fork >.1&^ is activated over the argument. Observe:

```<code>   1 ^ 0 1 2
1 1 1
   (1&^) 0 1 2
1 1 1
   0 1 2 >. (1&^) 0 1 2
1 1 2
   (>.1&^) 0 1 2
1 1 2
</code>```

Here, >. takes the max of two values. Thus, it yields 1, 1, and 2 as the initial terms.

The second verb in the gerund is a fork:

```<code>-&3 +&$: -&2
</code>```

The left and right tines are applied to the verb, subtracting 3 and 2 respectively; then the middle verb is called with left and right arguments equal to those. $: calls the verb on each argument, and + adds those two. It's basically equivalent to ($: arg - 3) + ($: arg - 2)

Test cases

```<code>   f =: (>.1&^)`(-&3+&$:-&2)@.(2&<)
   f 0
1
   f 2
2
   f 4
3
   f 6
5
   f 8
9
   F =: f"0         NB. for tables
   F i.13
1 1 2 2 3 4 5 7 9 12 16 21 28
   i.13
0 1 2 3 4 5 6 7 8 9 10 11 12
   (,. F) i.13
 0  1
 1  1
 2  2
 3  2
 4  3
 5  4
 6  5
 7  7
 8  9
 9 12
10 16
11 21
12 28
</code>```

Title: Checkmate (aka the urinal problem)

Body:
J, <s>31</s> <s>27</s> 23 bytes

Saved 4 bytes thanks to miles!

0{]_&(]}.,+/@}:)1 1 2"_

An explanation is to come soon.

Old solution

(>.1&^)`(-&3+&$:-&2)@.(2&<)

This is an agenda. The LHS is a gerund composed of two verbs: >.1&^ and -&3+&$:-&2. The first one is used if the condition (2&<) fails. That means the fork >.1&^ is activated over the argument. Observe:

   1 ^ 0 1 2
1 1 1
   (1&^) 0 1 2
1 1 1
   0 1 2 >. (1&^) 0 1 2
1 1 2
   (>.1&^) 0 1 2
1 1 2

Here, >. takes the max of two values. Thus, it yields 1, 1, and 2 as the initial terms.

The second verb in the gerund is a fork:

-&3 +&$: -&2

The left and right tines are applied to the verb, subtracting 3 and 2 respectively; then the middle verb is called with left and right arguments equal to those. $: calls the verb on each argument, and + adds those two. It's basically equivalent to ($: arg - 3) + ($: arg - 2)

Test cases

   f =: (>.1&^)`(-&3+&$:-&2)@.(2&<)
   f 0
1
   f 2
2
   f 4
3
   f 6
5
   f 8
9
   F =: f"0         NB. for tables
   F i.13
1 1 2 2 3 4 5 7 9 12 16 21 28
   i.13
0 1 2 3 4 5 6 7 8 9 10 11 12
   (,. F) i.13
 0  1
 1  1
 2  2
 3  2
 4  3
 5  4
 6  5
 7  7
 8  9
 9 12
10 16
11 21
12 28


答:
ALPACA, 414 + 2 = 416  bytes

```<code>neighbourhoodV(^ v < >);states" ";statep"#"toA when4inV p,toB when3inV p andvs,toC when3inV p and^s,toD when3inV p and>s,toE when3inV p and<s,toF when2inV p and>s andvs,toG when2inV p andvs and<s,toH when2inV p and<s and^s,toI when2inV p and^s and>s,toJ when^p orvp,toK when<p or>p;stateA"┼";stateB"┴";stateC"┬";stateD"┤";stateE"├";stateF"┘";stateG"└";stateH"┌";stateI"┐";stateJ"│";stateK"─".
</code>```

Requires the -fI flags.

This solution uses a very large number of bytes, but it is unique in that it uses a cellular automaton. ALPACA is usually used as a metalanguage, but here I'm using it as a programming language.

Ungolfed version:

```<code>neighbourhood V (^ v < >);
state s " ";
state p "#" to A when 4 in V p,
to B when 3 in V p and v s,
to C when 3 in V p and ^ s,
to D when 3 in V p and > s,
to E when 3 in V p and < s,
to F when 2 in V p and > s and v s,
to G when 2 in V p and v s and < s,
to H when 2 in V p and < s and ^ s,
to I when 2 in V p and ^ s and > s,
to J when ^ p or v p,
to K when < p or > p;
state A "┼";
state B "┴";
state C "┬";
state D "┤";
state E "├";
state F "┘";
state G "└";
state H "┌";
state I "┐";
state J "│";
state K "─".
</code>```

Title: Connect the pixels

Body:
Given a text like this:

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

Output the same text but by connecting the pixels with the characters ─│┌┐└┘├┤┬┴┼. If a pixel doesn't have any neighbours, don't change it.

So the output of the last text is:

```<code>│ ─┬── ┌─ │
└─ │  ┌┘  │
   └──┘  ─┘
</code>```

You can take input as a boolean array.

The input will always contain at least 1 pixel.

You can count box-drawing chars as 1 byte.

You can assume the input is padded with spaces.

Test cases

```<code>## #
=>
── #
</code>```

```<code>###
 #
=>
─┬─
 │
</code>```

```<code>##### ##
 # #  #
########
=>
─┬─┬─ ┌─
 │ │  │
─┴─┴──┴─
</code>```

```<code> # #
#####
 # #
=>
 │ │
─┼─┼─
 │ │
</code>```

```<code># # # # #
 # # # #
# # # # #
 # # # #
# # # # #
=>
# # # # #
 # # # #
# # # # #
 # # # #
# # # # #
</code>```

```<code>#####
#####
#####
#####
#####
=>
┌┬┬┬┐
├┼┼┼┤
├┼┼┼┤
├┼┼┼┤
└┴┴┴┘
</code>```

Since this is code-golf, the shortest code wins.

Body:
ALPACA, 414 + 2 = 416  bytes

neighbourhoodV(^ v < >);states" ";statep"#"toA when4inV p,toB when3inV p andvs,toC when3inV p and^s,toD when3inV p and>s,toE when3inV p and<s,toF when2inV p and>s andvs,toG when2inV p andvs and<s,toH when2inV p and<s and^s,toI when2inV p and^s and>s,toJ when^p orvp,toK when<p or>p;stateA"┼";stateB"┴";stateC"┬";stateD"┤";stateE"├";stateF"┘";stateG"└";stateH"┌";stateI"┐";stateJ"│";stateK"─".

Requires the -fI flags.

This solution uses a very large number of bytes, but it is unique in that it uses a cellular automaton. ALPACA is usually used as a metalanguage, but here I'm using it as a programming language.

Ungolfed version:

neighbourhood V (^ v < >);
state s " ";
state p "#" to A when 4 in V p,
to B when 3 in V p and v s,
to C when 3 in V p and ^ s,
to D when 3 in V p and > s,
to E when 3 in V p and < s,
to F when 2 in V p and > s and v s,
to G when 2 in V p and v s and < s,
to H when 2 in V p and < s and ^ s,
to I when 2 in V p and ^ s and > s,
to J when ^ p or v p,
to K when < p or > p;
state A "┼";
state B "┴";
state C "┬";
state D "┤";
state E "├";
state F "┘";
state G "└";
state H "┌";
state I "┐";
state J "│";
state K "─".


问:
print 1 to 100 without using recursion and conditions
can we print 1 to 100 without using any if conditions and loops in c&c++?

Conditon:
main point is you must not use recursion...and doesnt hardcode code in it
for e.g

print(1 2 3..etc);

答:
MATLAB/Octave, (5 chars)

```<code>1:100
</code>```

Body:
MATLAB/Octave, (5 chars)

1:100


问:
Bake a slice of Pi
Write a program or function that prints or outputs this exact text (consisting of 142 characters):

```<code>()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|
</code>```

Your program must take no input (except in languages where this is impossible, such as sed), and produce the above text (and only the above text) as output. A trailing newline is acceptable.

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

答:
Jelly, 83 bytes

surely still quite golfabale

```<code>7Ḷ⁶ẋ;€“\::\”“|:\”ṭṙ7
⁾()ẋ6⁷⁾|\8ØPæp”|⁷8RUR€µ“⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’Dṁ;€”|ż@¢Y⁷ø⁶ẋ7“\__\|”
</code>```

TryItOnline

How?

```<code>7Ḷ⁶ẋ;€“\::\”“|:\”ṭṙ7 - Link 1, left side padding and filling
7Ḷ                   - lowered range of 7 ([0,1,2,3,4,5,6])
      “\::\”         - filling ("\::\")
  ⁶ẋ;€               - space character repeated that many times and concatenate for each
            “|:\”    - top crust edge filling ("|:\")
                 ṭ   - tack (append to the end)
                  ṙ7 - rotate to the left by 7 (move top crust filling to the top)

⁾()ẋ6⁷⁾|\8ØPæp”|⁷8RUR€µ - Main Link (divided into two for formatting)
⁾()ẋ6⁷                  - "()" repeated 6 times and a line feed
      ⁾|\               - "|\"
          ØP            - pi
         8  æp          - round to 8 significant figures (top edge of the glaze)
              ”|⁷       - "|" and a line feed
                 8R     - range of 8 ([1,2,3,4,5,6,7,8])
                   U    - reverse ([8,7,6,5,4,3,2,1])
                    R€  - range for each ([[1,2,..8],[1,2,..7],...,[1,2],[1]])
                      µ - monadic chain separation

“⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’Dṁ;€”|ż@¢Y⁷ø⁶ẋ7“\__\|” - Main link (continued)
“⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’                       - base 250 representation of the rest of the digits
                 D                      - decimalise (makes it a list)
                  ṁ                     - mould (into the shape of the array formed above)
                     ”|                 - "|"
                   ;€                   - concatenate for each
                         ¢              - call last link (1) as a nilad
                       ż@               - zip (with reversed operands)
                          Y⁷            - join with line feeds, and another line feed
                            ø           - niladic chain separation
                             ⁶ẋ7        - space character repeated 7 times
                                “\__\|” - "\__\|" the very bottom of the pie wedge
</code>```

Title: Bake a slice of Pi

Body:
Jelly, 83 bytes

surely still quite golfabale

7Ḷ⁶ẋ;€“\::\”“|:\”ṭṙ7
⁾()ẋ6⁷⁾|\8ØPæp”|⁷8RUR€µ“⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’Dṁ;€”|ż@¢Y⁷ø⁶ẋ7“\__\|”

TryItOnline

How?

7Ḷ⁶ẋ;€“\::\”“|:\”ṭṙ7 - Link 1, left side padding and filling
7Ḷ                   - lowered range of 7 ([0,1,2,3,4,5,6])
      “\::\”         - filling ("\::\")
  ⁶ẋ;€               - space character repeated that many times and concatenate for each
            “|:\”    - top crust edge filling ("|:\")
                 ṭ   - tack (append to the end)
                  ṙ7 - rotate to the left by 7 (move top crust filling to the top)

⁾()ẋ6⁷⁾|\8ØPæp”|⁷8RUR€µ - Main Link (divided into two for formatting)
⁾()ẋ6⁷                  - "()" repeated 6 times and a line feed
      ⁾|\               - "|\"
          ØP            - pi
         8  æp          - round to 8 significant figures (top edge of the glaze)
              ”|⁷       - "|" and a line feed
                 8R     - range of 8 ([1,2,3,4,5,6,7,8])
                   U    - reverse ([8,7,6,5,4,3,2,1])
                    R€  - range for each ([[1,2,..8],[1,2,..7],...,[1,2],[1]])
                      µ - monadic chain separation

“⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’Dṁ;€”|ż@¢Y⁷ø⁶ẋ7“\__\|” - Main link (continued)
“⁾ḅ|Za"~ṅỵþȷ^ṇ⁷Ċ’                       - base 250 representation of the rest of the digits
                 D                      - decimalise (makes it a list)
                  ṁ                     - mould (into the shape of the array formed above)
                     ”|                 - "|"
                   ;€                   - concatenate for each
                         ¢              - call last link (1) as a nilad
                       ż@               - zip (with reversed operands)
                          Y⁷            - join with line feeds, and another line feed
                            ø           - niladic chain separation
                             ⁶ẋ7        - space character repeated 7 times
                                “\__\|” - "\__\|" the very bottom of the pie wedge


答:
Actually, 25 bytes

This seems a little long for a simple f(n) = f(n-2) + f(n-3) recurrence relation. Golfing suggestions welcome. Try it online!

```<code>╗211╜¬`);(+)`nak╜2╜2<I@E
</code>```

Ungolfing

```<code>         Implicit input n.
╗        Save n to register 0.
211      Stack: 1, 1, 2. Call them a, b, c.
╜¬       Push n-2.
`...`n   Run the following function n-2 times.
  );       Rotate b to TOS and duplicate.
  (+       Rotate a to TOS and add to b.
  )        Rotate a+b to BOS. Stack: b, c, a+b
         End function.
ak       Invert the resulting stack and wrap it in a list. Stack: [b, c, a+b]
╜        Push n.
2        Push 2.
╜2<      Push 2 < n.
I        If 2<n, then 2, else n.
@E       Grab the (2 or n)th index of the stack list.
         Implicit return.
</code>```

Title: Checkmate (aka the urinal problem)

Body:
Actually, 25 bytes

This seems a little long for a simple f(n) = f(n-2) + f(n-3) recurrence relation. Golfing suggestions welcome. Try it online!

╗211╜¬`);(+)`nak╜2╜2<I@E

Ungolfing

         Implicit input n.
╗        Save n to register 0.
211      Stack: 1, 1, 2. Call them a, b, c.
╜¬       Push n-2.
`...`n   Run the following function n-2 times.
  );       Rotate b to TOS and duplicate.
  (+       Rotate a to TOS and add to b.
  )        Rotate a+b to BOS. Stack: b, c, a+b
         End function.
ak       Invert the resulting stack and wrap it in a list. Stack: [b, c, a+b]
╜        Push n.
2        Push 2.
╜2<      Push 2 < n.
I        If 2<n, then 2, else n.
@E       Grab the (2 or n)th index of the stack list.
         Implicit return.


问:
Compute the Carmichael function

Task description

In number theory, the Carmichael function λ takes a positive integer n and returns the least positive integer k so that the k-th power of each integer coprime to n equals 1 modulo n.

Given a positive integer n, your solution must compute λ(n). The shortest code in bytes wins.

Your program should theoretically work for arbitrarily large inputs, but doesn’t need to be efficient.

Tips

The sequence of all λ(n) is OEIS A002322.

An ungolfed Python implementation would look like

```<code>from fractions import gcd

def carmichael(n):
    coprimes = [x for x in range(1, n) if gcd(x, n) == 1]
    k = 1
    while not all(pow(x, k, n) == 1 for x in coprimes):
        k += 1
    return k
</code>```

(In Python, pow(A, B, C) efficiently computes pow(A, B) % C.)

Test cases

```<code>Input    Output
1        1
2        1
3        2
10       4
35       12
101      100
530      52
3010     84
6511     3056
10000    500
</code>```

答:
C, <s>278 276 272 265 256 243 140 134</s> 125 bytes

k,x,a,b,t,d;l(n){for(k=d=1;d;)for(d=x=0;++x<n;d=a<2&t>1?k++:d){for(a=x,b=n;t=b;a=t)b=a%b;for(t=1,b=k;b--;t=t*x%n);}return k;}
```
<p>This uses a slow modular exponentiation algorithm, computes the GCD too often and no longer leaks memory!</p>
<p>Ungolfed:</p>
```int gcd( int a, int b ) {
  int t;
  while( b ) {
    t = b;
    b = a%b;
    a = t;
  }
  return a;
}
int pw(int a,int b,int c){
  int t=1;
  for( int e=0; e<b; e++ ) {
    t=(t*a)%c;
  }
  return t;
}
int carmichael(int n) {
  int k = 1;
  for( ;; ) {
    int done = 1;
    for( int x=1; x<n; x++ ) {
      if( gcd(x,n)==1 && pw(x,k,n) != 1 ) {
        done = 0;
        k++;
      }
    }
    if( done ) break;
  }
  return k;
}
```

Try it on Ideone

Title: Compute the Carmichael function

Body:
C, <s>278 276 272 265 256 243 140 134</s> 125 bytes

k,x,a,b,t,d;l(n){for(k=d=1;d;)for(d=x=0;++x<n;d=a<2&t>1?k++:d){for(a=x,b=n;t=b;a=t)b=a%b;for(t=1,b=k;b--;t=t*x%n);}return k;}

This uses a slow modular exponentiation algorithm, computes the GCD too often and no longer leaks memory!

Ungolfed:

int gcd( int a, int b ) {
  int t;
  while( b ) {
    t = b;
    b = a%b;
    a = t;
  }
  return a;
}
int pw(int a,int b,int c){
  int t=1;
  for( int e=0; e<b; e++ ) {
    t=(t*a)%c;
  }
  return t;
}
int carmichael(int n) {
  int k = 1;
  for( ;; ) {
    int done = 1;
    for( int x=1; x<n; x++ ) {
      if( gcd(x,n)==1 && pw(x,k,n) != 1 ) {
        done = 0;
        k++;
      }
    }
    if( done ) break;
  }
  return k;
}

Try it on Ideone


答:
Pyth, <s>56</s> <s>55</s> 52 bytes

The code contains some unprintables, so here's a reversible xxd hexdump.

```<code>00000000: 3d48 516a 5f2e 745f 2023 6c44 2a56 2e22  =HQj_.t_ #lD*V."
00000010: 4159 261c 0c24 2087 0c86 1e22 6d68 412e  AY&..$ ...."mhA.
00000020: 4448 645f 2e75 2a4e 5950 2a33 6a37 3733  DHd_.u*NYP*3j773
00000030: 3620 362f                                6 6/
</code>```

Try it online. Test suite.

Pro tip: to golf  1 in the end of a program accepting a nonzero number in Q, just add /. /QQ, which in Python would be Q // Q, is 1 for nonzero Q.

Without compression and unprintables (55 bytes):

```<code>=HQj_.t_ #lD*V"SVTILAMCOPYBGRW"mhA.DHd_.u*NYP*3j7736 6/
</code>```

Title: Make An ASCII Poker Chip Stack Arrangement

Body:
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:
Pyth, <s>56</s> <s>55</s> 52 bytes

The code contains some unprintables, so here's a reversible xxd hexdump.

00000000: 3d48 516a 5f2e 745f 2023 6c44 2a56 2e22  =HQj_.t_ #lD*V."
00000010: 4159 261c 0c24 2087 0c86 1e22 6d68 412e  AY&..$ ...."mhA.
00000020: 4448 645f 2e75 2a4e 5950 2a33 6a37 3733  DHd_.u*NYP*3j773
00000030: 3620 362f                                6 6/

Try it online. Test suite.

Pro tip: to golf  1 in the end of a program accepting a nonzero number in Q, just add /. /QQ, which in Python would be Q // Q, is 1 for nonzero Q.

Without compression and unprintables (55 bytes):

=HQj_.t_ #lD*V"SVTILAMCOPYBGRW"mhA.DHd_.u*NYP*3j7736 6/


问:
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>```

答:
dc + od, 65 bytes

od -tuC|dc -e'?dsN0sT[lNrdsNr-d*vdD[26-]sS<Sd*vlT+sTd0<R]dsRxlTp'
```

<p><strong>Explanation:</strong></p>

<p>Because in <em>dc</em> you can't access a string's characters, I used <em>od</em> to get the ASCII values. These will be processed in reverse order from the stack (LIFO container) like so:</p>

<pre class="lang-dc prettyprint-override"><code>dsN0sT             # initialize N (neighbor) = top ASCII value, and T (total) = 0
[lNrdsNr-          # loop 'R': calculate difference between current value and N,
                   #updating N (on the first iteration the difference is 0)
   d*vdD[26-]sS<S  # get absolute value (d*v), push 13 (D) and call 'S' to subtract
                   #26 if the difference is greater than 13
   d*vlT+sT        # get absolute value again and add it to T
d0<R]dsR           # repeat loop for the rest of the ASCII values
xlTp               # the main: call 'R' and print T at the end
</code>```

Run:

echo -n "golf" | ./string_distance.sh
```

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

<pre class="lang-sh prettyprint-override"><code>17
</code>```

Title: String Distance

Body:
dc + od, 65 bytes

od -tuC|dc -e'?dsN0sT[lNrdsNr-d*vdD[26-]sS<Sd*vlT+sTd0<R]dsRxlTp'

Explanation:

Because in dc you can't access a string's characters, I used od to get the ASCII values. These will be processed in reverse order from the stack (LIFO container) like so:

dsN0sT             # initialize N (neighbor) = top ASCII value, and T (total) = 0
[lNrdsNr-          # loop 'R': calculate difference between current value and N,
                   #updating N (on the first iteration the difference is 0)
   d*vdD[26-]sS<S  # get absolute value (d*v), push 13 (D) and call 'S' to subtract
                   #26 if the difference is greater than 13
   d*vlT+sT        # get absolute value again and add it to T
d0<R]dsR           # repeat loop for the rest of the ASCII values
xlTp               # the main: call 'R' and print T at the end

Run:

echo -n "golf" | ./string_distance.sh

Output:

17


答:
Java 7, 76 bytes

```<code>String c(String i){return i.contains(".")?" "+i:i+(i.endsWith("/")?92:'/');}
</code>```

Pretty straightforward.

Ungolfed & test code:

Try it here.

```<code>class M{
  static String c(String i){
    return i.contains(".")
            ? " " + i
            : i + (i.endsWith("/")
                    ? 92
                    : '/');
  }

  public static void main(String[] a){
    System.out.println(c(" ."));
    System.out.println(c("  ."));
    System.out.println(c("   ."));
    System.out.println(c("    ."));
    System.out.println(c("     ."));
    System.out.println(c("      ."));
    System.out.println(c("       ."));
    System.out.println(c("        ."));
    System.out.println(c("/"));
    System.out.println(c("\\"));
    System.out.println(c("/\\"));
    System.out.println(c("\\/"));
    System.out.println(c("/\\/"));
    System.out.println(c("\\/\\"));
    System.out.println(c("/\\/\\"));
    System.out.println(c("\\/\\/"));
  }
}
</code>```

Output:

```<code>  .
   .
    .
     .
      .
       .
        .
         .
/\
\/
/\/
\/\
/\/\
\/\/
/\/\/
\/\/\
</code>```

Title: Wave-Particle Duality Laterally Programmatically

Body:
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:

. →  .

 . →   .

  . →    .

   . →     .

    . →      .

     . →       .

      . →        .

       . →         .

In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

/ → /\

\ → \/

/\ → /\/

\/ → \/\

/\/ → /\/\

\/\ → \/\/

/\/\ → /\/\/

\/\/ → \/\/\

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

The shortest code in bytes wins.

Body:
Java 7, 76 bytes

String c(String i){return i.contains(".")?" "+i:i+(i.endsWith("/")?92:'/');}

Pretty straightforward.

Ungolfed & test code:

Try it here.

class M{
  static String c(String i){
    return i.contains(".")
            ? " " + i
            : i + (i.endsWith("/")
                    ? 92
                    : '/');
  }

  public static void main(String[] a){
    System.out.println(c(" ."));
    System.out.println(c("  ."));
    System.out.println(c("   ."));
    System.out.println(c("    ."));
    System.out.println(c("     ."));
    System.out.println(c("      ."));
    System.out.println(c("       ."));
    System.out.println(c("        ."));
    System.out.println(c("/"));
    System.out.println(c("\\"));
    System.out.println(c("/\\"));
    System.out.println(c("\\/"));
    System.out.println(c("/\\/"));
    System.out.println(c("\\/\\"));
    System.out.println(c("/\\/\\"));
    System.out.println(c("\\/\\/"));
  }
}

Output:

  .
   .
    .
     .
      .
       .
        .
         .
/\
\/
/\/
\/\
/\/\
\/\/
/\/\/
\/\/\


答:
Jelly, 9 bytes

```<code>Jạþ`=ḅa¹Ṁ
</code>```

Try it online! or verify all test cases.

How it works

```<code>Jạþ`=ḅa¹Ṁ  Main link. Argument: A (array)

J          Indices; yield [1, ..., len(A)].
   `       Use the previous return value as left and right argument:
 ạþ        Absolute difference table; take the absolute value of the difference
           of each pair of indices, yielding a 2D array.
    =      Compare each absolute difference with the corresponding item of A.
     ḅ     Base; convert each Boolean list from base i to integer, where i is the
           corresponding item of A. The value of i is not important; we only care
           if the list contains a 1, which will result in a non-zero integer.
       ¹   Identity; yield A.
      a    Logical AND; replace non-zero values with the corresponding items of A.
        Ṁ  Take the maximum.
</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:
Jelly, 9 bytes

Jạþ`=ḅa¹Ṁ

Try it online! or verify all test cases.

How it works

Jạþ`=ḅa¹Ṁ  Main link. Argument: A (array)

J          Indices; yield [1, ..., len(A)].
   `       Use the previous return value as left and right argument:
 ạþ        Absolute difference table; take the absolute value of the difference
           of each pair of indices, yielding a 2D array.
    =      Compare each absolute difference with the corresponding item of A.
     ḅ     Base; convert each Boolean list from base i to integer, where i is the
           corresponding item of A. The value of i is not important; we only care
           if the list contains a 1, which will result in a non-zero integer.
       ¹   Identity; yield A.
      a    Logical AND; replace non-zero values with the corresponding items of A.
        Ṁ  Take the maximum.


答:
Java 7, <s>125</s> 123 bytes

```<code>int c(int[]a){int r=0,i=0,l=a.length,x;for(;i<l;r=l>(x=i+a[i])?a[x]>r?a[x]:r:r,r=(x=i-a[i++])>0?a[x]>r?a[x]:r:r);return r;}
</code>```

2 bytes saved thanks to @mrco.

Ungolfed (sort of) & test code:

Try it here.

```<code>class M{
  static int c(int[] a){
    int r = 0,
        i = 0,
        l = a.length,
        x;
    for(; i < l; r = l > (x = i + a[i])
                      ? a[x] > r
                         ? a[x]
                         : r
                      : r,
                 r = (x = i - a[i++]) > 0
                      ? a[x] > r
                         ? a[x]
                         : r
                      : r);
    return r;
  }

  public static void main(String[] a){
    System.out.println(c(new int[]{ 1, 13 }));
    System.out.println(c(new int[]{ 2, 9, 8, 3, 72, 2 }));
    System.out.println(c(new int[]{ 5, 28, 14, 5, 6, 3, 4, 7 }));
    System.out.println(c(new int[]{ 1, 3, 5, 15, 4, 1, 2, 6, 7, 7 }));
    System.out.println(c(new int[]{ 5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3 }));
    System.out.println(c(new int[]{ 5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5 }));
  }
}
</code>```

Output:

```<code>13
8
14
7
5
10
</code>```

Body:
Java 7, <s>125</s> 123 bytes

int c(int[]a){int r=0,i=0,l=a.length,x;for(;i<l;r=l>(x=i+a[i])?a[x]>r?a[x]:r:r,r=(x=i-a[i++])>0?a[x]>r?a[x]:r:r);return r;}

2 bytes saved thanks to @mrco.

Ungolfed (sort of) & test code:

Try it here.

class M{
  static int c(int[] a){
    int r = 0,
        i = 0,
        l = a.length,
        x;
    for(; i < l; r = l > (x = i + a[i])
                      ? a[x] > r
                         ? a[x]
                         : r
                      : r,
                 r = (x = i - a[i++]) > 0
                      ? a[x] > r
                         ? a[x]
                         : r
                      : r);
    return r;
  }

  public static void main(String[] a){
    System.out.println(c(new int[]{ 1, 13 }));
    System.out.println(c(new int[]{ 2, 9, 8, 3, 72, 2 }));
    System.out.println(c(new int[]{ 5, 28, 14, 5, 6, 3, 4, 7 }));
    System.out.println(c(new int[]{ 1, 3, 5, 15, 4, 1, 2, 6, 7, 7 }));
    System.out.println(c(new int[]{ 5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3 }));
    System.out.println(c(new int[]{ 5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5 }));
  }
}

Output:

13
8
14
7
5
10


答:
CJam, 20 bytes

```<code>1_2_{2$2$+}ri*;;;o];
</code>```

Try it online!

Explanation

This uses the recurrence relationship shown in the OEIS page.

```<code>1_2_                   e# Push 1, 1, 2, 2 as initial values of the sequence
           ri          e# Read input
    {     }  *         e# Repeat block that many times
     2$2$              e# Copy the second and third elements from the top
         +             e# Add them
              ;;;      e# Discard the last three elements
                 o     e# Output
                  ];   e# Discard the rest to avoid implicit display
</code>```

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:
CJam, 20 bytes

1_2_{2$2$+}ri*;;;o];

Try it online!

Explanation

This uses the recurrence relationship shown in the OEIS page.

1_2_                   e# Push 1, 1, 2, 2 as initial values of the sequence
           ri          e# Read input
    {     }  *         e# Repeat block that many times
     2$2$              e# Copy the second and third elements from the top
         +             e# Add them
              ;;;      e# Discard the last three elements
                 o     e# Output
                  ];   e# Discard the rest to avoid implicit display


问:
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.

答:
Julia, 88 Bytes

```<code>f(l,A,B)=reduce(+,map(abs,map(sum,[zip(-l,reverse(l))...][1:fld(end,2)])))*min([A,B]...)
</code>```

Explained:

If I am not mistaken, all we have to do is either grow all necessary plants or shrink them (depending on which operations is less expensive)

zip input list with a reverse of itself (align corresponding heights)

only look at first half of the list (floor when length is odd)

sum the differences

multiply with minimum cost (A or B)

Example

```<code>f([1,6,2,3,4],1,2) -> 6   (grow plant 1 and 4, yields [4,6,2,6,4])
f([1,6,2,3,4],3,2) -> 12   (shrink plant 2 and 5, yields [1,3,2,3,1])
</code>```

Note:

As there is still a discussion about the input format, I disregarded it for the moment.

Update:

Updated to output energy, as I think that outputing the actual palindrome is more challenging I attach my previous code here (76 Bytes):

```<code>f(l,A,B)=reduce(hcat,map(x->sort([x...]),[zip(l,reverse(l))...]))[A>B?1:2,:]
</code>```

Title: Alexa and the Tea Plantation

Body:
Julia, 88 Bytes

f(l,A,B)=reduce(+,map(abs,map(sum,[zip(-l,reverse(l))...][1:fld(end,2)])))*min([A,B]...)

Explained:

If I am not mistaken, all we have to do is either grow all necessary plants or shrink them (depending on which operations is less expensive)

zip input list with a reverse of itself (align corresponding heights)

only look at first half of the list (floor when length is odd)

sum the differences

multiply with minimum cost (A or B)

Example

f([1,6,2,3,4],1,2) -> 6   (grow plant 1 and 4, yields [4,6,2,6,4])
f([1,6,2,3,4],3,2) -> 12   (shrink plant 2 and 5, yields [1,3,2,3,1])

Note:

As there is still a discussion about the input format, I disregarded it for the moment.

Update:

Updated to output energy, as I think that outputing the actual palindrome is more challenging I attach my previous code here (76 Bytes):

f(l,A,B)=reduce(hcat,map(x->sort([x...]),[zip(l,reverse(l))...]))[A>B?1:2,:]


问:
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>```

答:
MATL, 15 bytes

```<code>:"G:@Z^t!XsG=Y)
</code>```

Try it online!

Explanation

Given input n, this computes the Cartesian power with increasing exponents k from 1 to n; and for each exponent k selects the tuples that have a sum equal to the input.

```<code>:       % Take input n implicitly and push range [1 2 ... n]
"       % For each k in that range
  G:    %   Push [1 2 ... n] again
  @     %   Push k
  Z^    %   Cartesian power. Gives 2D array, say A, with each k-tuple in a row.
  t     %   Duplicate
  !     %   Transpose
  Xs    %   Sum of each column. Gives a row vector
  G=    %   True for entries that equal the input
  Y)    %   Use as logical vector into the rows of array A
        % End implicitly
        % Display stack implicitly
</code>```

Title: List all ordered partitions of n

Body:
MATL, 15 bytes

:"G:@Z^t!XsG=Y)

Try it online!

Explanation

Given input n, this computes the Cartesian power with increasing exponents k from 1 to n; and for each exponent k selects the tuples that have a sum equal to the input.

:       % Take input n implicitly and push range [1 2 ... n]
"       % For each k in that range
  G:    %   Push [1 2 ... n] again
  @     %   Push k
  Z^    %   Cartesian power. Gives 2D array, say A, with each k-tuple in a row.
  t     %   Duplicate
  !     %   Transpose
  Xs    %   Sum of each column. Gives a row vector
  G=    %   True for entries that equal the input
  Y)    %   Use as logical vector into the rows of array A
        % End implicitly
        % Display stack implicitly


答:
05AB1E, 20 bytes

```<code>WU|vy#Â‚ø€¥˜Ä2ä`OX*,
</code>```

Explanation

```<code>WU                    # store minimum cost in X
  |v                  # for each testcase
    y#                # convert to list split on spaces
      Â‚ø             # zip with its own reverse
         €¥           # deltas of each pair
           ˜Ä         # deep flatten and take absolute value
             2ä       # split into 2 pieces
               `      # flatten (leaves the smaller piece on top of the stack)
                O     # sum
                 X*   # multiply with minimum cost
                   ,  # print
</code>```

Try it online!

Title: Alexa and the Tea Plantation

Body:
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.

Body:
05AB1E, 20 bytes

WU|vy#Â‚ø€¥˜Ä2ä`OX*,

Explanation

WU                    # store minimum cost in X
  |v                  # for each testcase
    y#                # convert to list split on spaces
      Â‚ø             # zip with its own reverse
         €¥           # deltas of each pair
           ˜Ä         # deep flatten and take absolute value
             2ä       # split into 2 pieces
               `      # flatten (leaves the smaller piece on top of the stack)
                O     # sum
                 X*   # multiply with minimum cost
                   ,  # print

Try it online!


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

Saved 2 bytes thanks to Adnan

```<code>>G¹LNãvyO¹Q—
</code>```

Explanation

```<code>>G              # for N in range(1..input)
  ¹L            # range(1, input)
    Nã          # cartesian product with N (all combinations of length N)
      v         # for each resulting list
       yO¹Q—    # if it's sum equals the input print it
</code>```

Try it online!

The corresponding solution is 2 bytes shorter in 2sable.

2sable, 10 bytes

```<code>>GLNãvyOQ—
</code>```

Try it online!

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:
05AB1E, <s>14</s> 12 bytes

Saved 2 bytes thanks to Adnan

>G¹LNãvyO¹Q—

Explanation

>G              # for N in range(1..input)
  ¹L            # range(1, input)
    Nã          # cartesian product with N (all combinations of length N)
      v         # for each resulting list
       yO¹Q—    # if it's sum equals the input print it

Try it online!

The corresponding solution is 2 bytes shorter in 2sable.

2sable, 10 bytes

>GLNãvyOQ—

Try it online!


问:
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!

答:
PHP, 66 bytes

```<code>foreach($a=$argv as$k=>$v)$v||$m=max($m,$a[$k-1],$a[$k+1]);echo$m;
</code>```

Pretty straightforward. Iterates over the input, and when a number is 0, it sets $m to the highest number of the 2 adjacent numbers and any previous value of $m.

Run like this (-d added for aesthetics only):

```<code>php -d error_reporting=30709 -r 'foreach($a=$argv as$k=>$v)$v||$m=max($m,$a[$k-1],$a[$k+1]);echo$m;' -- -4 -6 -2 0 -9;echo
</code>```

Body:
PHP, 66 bytes

foreach($a=$argv as$k=>$v)$v||$m=max($m,$a[$k-1],$a[$k+1]);echo$m;

Pretty straightforward. Iterates over the input, and when a number is 0, it sets $m to the highest number of the 2 adjacent numbers and any previous value of $m.

Run like this (-d added for aesthetics only):

php -d error_reporting=30709 -r 'foreach($a=$argv as$k=>$v)$v||$m=max($m,$a[$k-1],$a[$k+1]);echo$m;' -- -4 -6 -2 0 -9;echo


问:
Jimmy these arrays down
My coworker, Jimmy is kinda new to C/C++. He's also kind of a slow learner. Now, to be fair, his code always compiles, but he has some really sloppy habits. For example, everybody knows that you can define an array like this:

```<code>int spam[] = {4, 8, 15, 16, 23, 42};
</code>```

Everybody that is, except for Jimmy. He is convinced that the only way to make an array is like this:

```<code>int spam[6];
spam[0] = 4;
spam[1] = 8;
spam[2] = 15;
spam[3] = 16;
spam[4] = 23;
spam[5] = 42;
</code>```

I keep fixing this for him in code-review, but he won't learn. So I need you to write a tool that automagically does this for him when he commits¹.

The challenge

I want you to write either a full program or a function that takes in a multiline string as input, and outputs the more compact version of the C array. The input will always follow this format, whitespace included:

```<code>identifier_one identifier_two[some_length];
identifier_two[0] = some_number;
identifier_two[1] = some_number;
identifier_two[2] = some_number;
...
identifier_two[some_length - 1] = some_number;
</code>```

In short, the input will always be valid and well defined C. In more detail:

All of the identifiers will be made up of just letters and underscores. The length will always be at least one, and there will never be any missing or out of bounds indexes. You may also assume that the indexes are in order. For example:

```<code>foo bar[3];
bar[0] = 1
bar[2] = 9;
</code>```

<s></s>

```<code>foo bar[1];
bar[0] = 1;
bar[1] = 3;
</code>```

and

```<code>foo bar[3];
bar[2] = 9;
bar[0] = 1
bar[1] = 3
</code>```

are all invalid inputs, and may cause undefined behavior in your submission. You may also assume that all of the numbers will be valid decimal numbers, negative or positive. The input will not have extraneous spaces. The output should always follow this format, whitespace included:

```<code>identifier_one identifier_two[] = {n1, n2, n3, ...};
</code>```

Here is some sample data:

```<code>Input:
spam eggs[10];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
eggs[4] = 3;
eggs[5] = 7;
eggs[6] = 888;
eggs[7] = 555;
eggs[8] = 0;
eggs[9] = -2;

Output:
spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};

Input:
char ans[2];
ans[0] = 52;
ans[1] = 50;

Output:
char ans[] = {52, 50};

Input:
blah_blah quux[1];
quux[0] = 105;

Output:
blah_blah quux[] = {105};
</code>```

You may take your input and output in any reasonable format, such as STDIN/STDOUT, function arguments and return value, reading and writing files etc. Standard loopholes apply. The shortest answer in bytes wins!

¹This is passive-aggressive and a terrible idea. You did not get this idea from me.

答:
Java, 106 bytes

String manipulation in Java is hell, as always.

```<code>a->a[0].join("",a).replaceAll(";\\w+\\[\\d+\\] = ",", ").replaceAll("\\d+\\], ","] = {").replace(";","};")
</code>```

This is a pure regex answer. Make a single concatenated String, then perform replaceXxx until it's ok.

Testing and ungolfed:

```<code>import java.util.function.Function;

public class Main {

  public static void main(String[] args) {
    Function<String[], String> f = a ->
        String.join("", a)                          // I think this would join. Not sure, though. Golfed into a[0].join because static members are accessible from instances.
            .replaceAll(";\\w+\\[\\d+\\] = ", ", ") // replace with regex
            .replaceAll("\\d+\\], ", "] = {")       // replace with regex
            .replace(";", "};");                    // replace no regex

    String[] spam = {
      "int spam[6];",
      "spam[0] = 4;",
      "spam[1] = 8;",
      "spam[2] = 15;",
      "spam[3] = 16;",
      "spam[4] = 23;",
      "spam[5] = 42;"
    };
    test(f, spam, "int spam[] = {4, 8, 15, 16, 23, 42};");

    String[] eggs = {
      "spam eggs[10];",
      "eggs[0] = 0;",
      "eggs[1] = 4;",
      "eggs[2] = 8;",
      "eggs[3] = -3;",
      "eggs[4] = 3;",
      "eggs[5] = 7;",
      "eggs[6] = 888;",
      "eggs[7] = 555;",
      "eggs[8] = 0;",
      "eggs[9] = -2;"
    };
    test(f, eggs, "spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};");

    String[] ans = {
      "char ans[2];",
      "ans[0] = 52;",
      "ans[1] = 50;"
    };
    test(f, ans, "char ans[] = {52, 50};");

    String[] quux = {
      "blah_blah quux[1];",
      "quux[0] = 105;"
    };
    test(f, quux, "blah_blah quux[] = {105};");

  }

  static void test(Function<String[], String> f, String[] input, String expected) {
    System.out.printf("Result:   %s%nExpected: %s%n", f.apply(input), expected);
  }
}
</code>```

Title: Jimmy these arrays down

Body:
Java, 106 bytes

String manipulation in Java is hell, as always.

a->a[0].join("",a).replaceAll(";\\w+\\[\\d+\\] = ",", ").replaceAll("\\d+\\], ","] = {").replace(";","};")

This is a pure regex answer. Make a single concatenated String, then perform replaceXxx until it's ok.

Testing and ungolfed:

import java.util.function.Function;

public class Main {

  public static void main(String[] args) {
    Function<String[], String> f = a ->
        String.join("", a)                          // I think this would join. Not sure, though. Golfed into a[0].join because static members are accessible from instances.
            .replaceAll(";\\w+\\[\\d+\\] = ", ", ") // replace with regex
            .replaceAll("\\d+\\], ", "] = {")       // replace with regex
            .replace(";", "};");                    // replace no regex

    String[] spam = {
      "int spam[6];",
      "spam[0] = 4;",
      "spam[1] = 8;",
      "spam[2] = 15;",
      "spam[3] = 16;",
      "spam[4] = 23;",
      "spam[5] = 42;"
    };
    test(f, spam, "int spam[] = {4, 8, 15, 16, 23, 42};");

    String[] eggs = {
      "spam eggs[10];",
      "eggs[0] = 0;",
      "eggs[1] = 4;",
      "eggs[2] = 8;",
      "eggs[3] = -3;",
      "eggs[4] = 3;",
      "eggs[5] = 7;",
      "eggs[6] = 888;",
      "eggs[7] = 555;",
      "eggs[8] = 0;",
      "eggs[9] = -2;"
    };
    test(f, eggs, "spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};");

    String[] ans = {
      "char ans[2];",
      "ans[0] = 52;",
      "ans[1] = 50;"
    };
    test(f, ans, "char ans[] = {52, 50};");

    String[] quux = {
      "blah_blah quux[1];",
      "quux[0] = 105;"
    };
    test(f, quux, "blah_blah quux[] = {105};");

  }

  static void test(Function<String[], String> f, String[] input, String expected) {
    System.out.printf("Result:   %s%nExpected: %s%n", f.apply(input), expected);
  }
}


答:
Mathematica, 40 bytes

```<code>Join@@Permutations/@IntegerPartitions@#&
</code>```

Mathematica's built-in for integer partitions doesn't give all ordered partitions, so we have to generate all possible permutations of each of them, and then flatten the result.

Title: List all ordered partitions of n

Body:
Mathematica, 40 bytes

Join@@Permutations/@IntegerPartitions@#&

Mathematica's built-in for integer partitions doesn't give all ordered partitions, so we have to generate all possible permutations of each of them, and then flatten the result.


答:
Brachylog, 20 bytes

```<code>~lL#++?,L:=f:{:0x}ad
</code>```

Try it online!

Explanation

This is a situation where you would think declarative languages would do well, but because of the overloading of + and the difficutly in writing a summing predicate which propagates constraints properly, they do not.

```<code>~lL                     L is a list of length Input
  L#+                   L is a list of non-negative integers
  L  +?,                The sum of the elements of L results in the Input
        L:=f            Find all values for the elements of L which satisfy those constraints
            :{:0x}a     Remove all 0s from each sublist of the result of Findall
                   d    Remove all duplicate sublists
</code>```

Title: List all ordered partitions of n

Body:
Brachylog, 20 bytes

~lL#++?,L:=f:{:0x}ad

Try it online!

Explanation

This is a situation where you would think declarative languages would do well, but because of the overloading of + and the difficutly in writing a summing predicate which propagates constraints properly, they do not.

~lL                     L is a list of length Input
  L#+                   L is a list of non-negative integers
  L  +?,                The sum of the elements of L results in the Input
        L:=f            Find all values for the elements of L which satisfy those constraints
            :{:0x}a     Remove all 0s from each sublist of the result of Findall
                   d    Remove all duplicate sublists


答:
Python, 56 bytes

f=lambda n:[x+[n-i]for i in range(n)for x in f(i)]or[[]]
```

A recursive solution: The ordered partitions of n are a partition of some smaller i with 0<=i<n, followed by the remainder n-i as the last element. For a base case, n=0 only has the empty partition.

Title: List all ordered partitions of n

Body:
Python, 56 bytes

f=lambda n:[x+[n-i]for i in range(n)for x in f(i)]or[[]]

A recursive solution: The ordered partitions of n are a partition of some smaller i with 0<=i<n, followed by the remainder n-i as the last element. For a base case, n=0 only has the empty partition.