答:
Perl, <s>20</s> 19 bytes

```<code>perl -E 's//0/;say while++$_'
</code>```

Magic string increment makes this work without bigint

Title: Count up forever

Body:
Write a program that counts up forever, starting from one.

Rules:

Your program must log to STDOUT or an acceptable alternative, if STDOUT is not available.

Your program must be a full, runnable program, and not a function or snippet.

Your program must output each number with a separating character in between (a newline, space, tab or comma), but this must be consistent for all numbers.

You may print the numbers in decimal, in unary or in base 256 where each digit is represented by a byte value.

Your program must count at least as far as 2128 (inclusive) without problems and without running out of memory on a reasonable desktop PC. In particular, this means if you're using unary, you cannot store a unary representation of the current number in memory.

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

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

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

Catalogue

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
Perl, <s>20</s> 19 bytes

perl -E 's//0/;say while++$_'

Magic string increment makes this work without bigint


问:
How much more reputation do I need?
Programming Puzzles and Code Golf has graduated from beta. Soon we will get a custom site design, and with that the reputation boundaries for privileges will go up. A lot of users will lose privileges on the site. So your task is to write a program that tells us how much extra reputation we'll need to keep our privileges.

Task

Your task is to write the shortest code to find the amount of extra reputation a user will need to keep their current privileges after the site design, given the number of reputation points.

Input / Output

You can accept input and give output in any way you like, so long as it follows these rules:

Input - An integer from 1 to 250000+ inclusive. Your program or function should be able to accept numbers bigger than this, but it must accept numbers in this range.

Output - An integer representing the number of reputation points the user will need to get to keep their current privileges after the graduation.

No standard loopholes, please.

Example algorithm

Set variable i to the input

Set variable r to variable i.

While r is not in list beta:

Subtract 1 from r.

Set n to the position of r in beta.

Set r to item n of graduated.

Set variable o to the result of r - i.

If o < 0:

Set variable o to 0.

Output variable o.

Tables

Table of privileges that will change

```<code> | privilege name              | beta rep | graduation rep |
-+-----------------------------+----------+----------------+-
 | create tags                 |      150 |           1500 |
 | access review queues        |      350 |            500 |
 | cast close and reopen votes |      500 |           3000 |
 | established user            |      750 |           1000 |
 | edit questions and answers  |     1000 |           2000 |
 | create tag synonyms         |     1250 |           2500 |
 | approve tag wiki edits      |     1500 |           5000 |
 | access to moderator tools   |     2000 |          10000 |
 | protect questions           |     3500 |          15000 |
 | trusted user                |     4000 |          20000 |
 | access to site analytics    |     5000 |          25000 |
-+-----------------------------+----------+----------------+-
 | privilege name              | beta rep | graduation rep |
</code>```

Table of privileges that won't change

```<code> | privilege name               | reputation |
-+------------------------------+------------+-
 | create posts                 |          1 |
 | participate in meta          |          1 |
 | create wiki posts            |         10 |
 | remove new user restrictions |         10 |
 | vote up                      |         15 |
 | flag posts                   |         15 |
 | talk in chat                 |         20 |
 | comment everywhere           |         50 |
 | set bounties                 |         75 |
 | create chatrooms             |        100 |
 | edit community wiki          |        100 |
 | vote down                    |        125 |
-+------------------------------+------------+-
 | privilege name               | reputation |
</code>```

Testcases

```<code>wizzwizz4                |   750 |  2250
cat                      |  2004 |  7996
Dennis ♦                 | 72950 |     0
Dr Green Eggs and Ham DJ |  4683 | 15317
New User                 |     1 |     0
</code>```

Not all reputation counts are correct at time of writing

If you want your past or present reputation count here, just comment below and I'll maybe add it.

答:
CJam, 38 bytes

```<code>0000000: 72 69 5f 35 30 2f 22 64 50 46 28 1e 0a 03 22 66  ri_50/"dPF(..."f
0000010: 3c 3a 2b 22 fa c8 96 64 32 1e 0f 00 22 3d 69 65  <:+"...d2..."=ie
0000020: 32 5c 2d 55 65 3e                                2\-Ue>
</code>```

Try it online! or verify all test cases.1

How it works

```<code>ri                        Read an integer n from STDIN.
  _50/                    Push a copy and divide it by 50.
     "…"                  Push the string with code points [100 80 70 40 30 10 3].
        f<                Compare each code point with n / 50.
          :+              Add the resulting Booleans.
            "…"           Push the string with code points
                          [250 200 150 100 50 30 15 0].
               =          Select the one at the index of the sum.
                i         Convert from character to integer.
                 e2       Multiply by 100.
                   \-     Subtract n from the product.
                     Ue>  Take the maximum of the difference and 0.
</code>```

1 Note that the code contains a null byte, which causes problems in some browsers.

ContentLicense: CC BY-SA 3.0

Title: How much more reputation do I need?

Body:
CJam, 38 bytes

0000000: 72 69 5f 35 30 2f 22 64 50 46 28 1e 0a 03 22 66  ri_50/"dPF(..."f
0000010: 3c 3a 2b 22 fa c8 96 64 32 1e 0f 00 22 3d 69 65  <:+"...d2..."=ie
0000020: 32 5c 2d 55 65 3e                                2\-Ue>

Try it online! or verify all test cases.1

How it works

ri                        Read an integer n from STDIN.
  _50/                    Push a copy and divide it by 50.
     "…"                  Push the string with code points [100 80 70 40 30 10 3].
        f<                Compare each code point with n / 50.
          :+              Add the resulting Booleans.
            "…"           Push the string with code points
                          [250 200 150 100 50 30 15 0].
               =          Select the one at the index of the sum.
                i         Convert from character to integer.
                 e2       Multiply by 100.
                   \-     Subtract n from the product.
                     Ue>  Take the maximum of the difference and 0.

1 Note that the code contains a null byte, which causes problems in some browsers.


问:
Count up forever
Write a program that counts up forever, starting from one.

Rules:

Your program must log to STDOUT or an acceptable alternative, if STDOUT is not available.

Your program must be a full, runnable program, and not a function or snippet.

Your program must output each number with a separating character in between (a newline, space, tab or comma), but this must be consistent for all numbers.

You may print the numbers in decimal, in unary or in base 256 where each digit is represented by a byte value.

Your program must count at least as far as 2128 (inclusive) without problems and without running out of memory on a reasonable desktop PC. In particular, this means if you're using unary, you cannot store a unary representation of the current number in memory.

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

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

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

Catalogue

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Retina, 20 bytes

```<code><empty line>
39$*0
+:T`9d`d`.9*$
</code>```

Can count to 10**39-1.

Try it online!

Without leading zeroes (can count beyond 10**39): 23 bytes

```<code>+:(T`9d`d`.9*$
^0*$
1$&
</code>```

Try it online!

13 bytes if pre-initialized with input as 39 "0"s:

```<code>+:T`9d`d`.9*$
</code>```

Try it online!

Title: Count up forever

Body:
Retina, 20 bytes

<empty line>
39$*0
+:T`9d`d`.9*$

Can count to 10**39-1.

Try it online!

Without leading zeroes (can count beyond 10**39): 23 bytes

+:(T`9d`d`.9*$
^0*$
1$&

Try it online!

13 bytes if pre-initialized with input as 39 "0"s:

+:T`9d`d`.9*$

Try it online!


答:
UGL, 14 bytes

```<code>cul$oucuuu$*O:
</code>```

Try it online!

How it works:

```<code>cul$oucuuu$*O:
cu              #i=1
  l          :  #while i:
   $o           #    print(i)
     u          #    i++
      cuuu$*O   #    print(chr(9))
</code>```

Title: Count up forever

Body:
UGL, 14 bytes

cul$oucuuu$*O:

Try it online!

How it works:

cul$oucuuu$*O:
cu              #i=1
  l          :  #while i:
   $o           #    print(i)
     u          #    i++
      cuuu$*O   #    print(chr(9))


问:
The Versatile Integer Printer
Write a piece of code that is executable in at least three different languages. The code must output the integer 1 in language number one, 2 in language number two, 3 in language number three etc.

Rules:

The output must be only the integer, but trailing newlines are OK.

The code can't take input of any kind

Different major versions of the same language are considered unique. So, your code can be executable in Python 2 and Python 3, however Python 2.5 and Python 2.7 are not considered unique.

You may use a new language if and only if it has an esolang/wiki article, available interpreter and documentation, and has been used by at least two users on PPCG prior to using it in this challenge. It must also adhere to these 4 rules.

The score of your submission is the number of bytes in your code divided by the number of languages it can run in cubed. So, a 54 byte solution that is executable in 3 languages will have a score of 2:

```<code>54 / 3^3 = 2
</code>```

Lower score is better.

答:
14 languages, 73 bytes, score = (73/14^3) = 0.02660349854

```<code>#Y2(3`5n~thneo e        ;n@0d c
#   -[>+<"9"L-----]>+.
14
print(int(15/2))+3
</code>```

I can add some more langs, but I think I'll add what I have here.

1. Brainbool ; Try it online!

The relevant code:

```<code>    [>+<         ]>+.

               +
</code>```

This is really just +.+, which outputs 1.

2. Jolf ; Try it here!

The ( char stops interpreting the source code, so the relavent code is:

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

This is equivalent to (in JavaScript)

```<code>var Y = []; toHex(Y); alert(2);
</code>```

Which outputs 2.

3. Element ; Try it online!

The relevant code:

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

This captures 3 and prints it.

4. Brainfuck ; Try it online!

The relevant code is:

```<code>-[>+<    -----]>+.

  -    -      +
</code>```

Which is the standard way of generating 4's char code and outputting it, and some other stuff after it.

5. Reng ; Try it here!

~ terminates the program, so the relevant code here is:

```<code>#Y2(3`5n~
</code>```

# redefines Y to be the TOS, in this case, 0. 2 pushes 2; ( rotates the stack N times, popping N from the stack; 3` pushes -3; and finally, 5n prints 5.

6. ETA ; Try it online!

ETA only reads the letters E, T, A, O, I, N, S, H, so the code only executed is this:

```<code>       n thneo e         n

  int int
</code>```

Super-relevant code:

```<code>       n thneo
</code>```

Or, equivalently: nthne o. n...e is a base-7 literal, and thn is the base-7 number for 54. o outputs this character. The submission errors out, but I don't know why.

7. Python 3

What it sees:

```<code># comment
# comment
14
print(int(15/2))+3
</code>```

15/2 yields 7.5, as / is float division. int(...) makes the number an int, which is then printed. The program errors out when +3 is encountered.

8. Julia

Julia sees:

```<code>    [>+<         ]>+.

               +
</code>```0

Instead of truncating 15/2, Julia rounds it up, yielding 8. It prints this, then errors out on encountering +3.

9. Fission ; Try it online!

Relevant code:

```<code>    [>+<         ]>+.

               +
</code>```1

I got this idea from Martin's Fission portion (more like stole it). L begins a left-facing thing, captures 9, and ends with <.

10. Whitespace ; Try it here!

The relevant code, translating spaces into S and tabs into T:

```<code>    [>+<         ]>+.

               +
</code>```2

It pushes 10 to the stack and outputs it as a number (T\nST).

11. Python 2

Python 2 sees this:

```<code># comment
# comment
14
print(int(15/2))+3
</code>```

(int(15/2))+3 is evaluated to be 11, and that's printed.

12. Gol><> ; Try it here!

Relevant code:

```<code>#                      ;n@0d c
</code>```

This uses the trick used in Martin's answer that @ rotates different directions in ><> and Gol><>. # mirrors, c pushes 12, d pushes 13, 0 pushes 0, and @ brings c to the top of the stack, then being outted and printed with ;n.

13. ><> ; Try it online!

Relevant code:

```<code>#                      ;n@0d c
</code>```

Again using that @ rotates different directions in ><> and Gol><>. # mirrors, c pushes 12, d pushes 13, 0 pushes 0, and @ brings d to the top of the stack, then being outted and printed with ;n.

14. Golfscript ; Try it online!

What it sees:

```<code># comment
# comment
    14
print(-int(-15/2))+3
</code>```

It pushes 14, prints it, and errors. <s>Stolen</s> inspired by Sp3000's answer.

ContentLicense: CC BY-SA 4.0

Title: The Versatile Integer Printer

Body:
14 languages, 73 bytes, score = (73/14^3) = 0.02660349854

#Y2(3`5n~thneo e        ;n@0d c
#   -[>+<"9"L-----]>+.
14
print(int(15/2))+3

I can add some more langs, but I think I'll add what I have here.

1. Brainbool ; Try it online!

The relevant code:

    [>+<         ]>+.

               +

This is really just +.+, which outputs 1.

2. Jolf ; Try it here!

The ( char stops interpreting the source code, so the relavent code is:

#Y2

This is equivalent to (in JavaScript)

var Y = []; toHex(Y); alert(2);

Which outputs 2.

3. Element ; Try it online!

The relevant code:

    3`

This captures 3 and prints it.

4. Brainfuck ; Try it online!

The relevant code is:

-[>+<    -----]>+.

  -    -      +

Which is the standard way of generating 4's char code and outputting it, and some other stuff after it.

5. Reng ; Try it here!

~ terminates the program, so the relevant code here is:

#Y2(3`5n~

# redefines Y to be the TOS, in this case, 0. 2 pushes 2; ( rotates the stack N times, popping N from the stack; 3` pushes -3; and finally, 5n prints 5.

6. ETA ; Try it online!

ETA only reads the letters E, T, A, O, I, N, S, H, so the code only executed is this:

       n thneo e         n

  int int

Super-relevant code:

       n thneo

Or, equivalently: nthne o. n...e is a base-7 literal, and thn is the base-7 number for 54. o outputs this character. The submission errors out, but I don't know why.

7. Python 3

What it sees:

# comment
# comment
14
print(int(15/2))+3

15/2 yields 7.5, as / is float division. int(...) makes the number an int, which is then printed. The program errors out when +3 is encountered.

8. Julia

Julia sees:

# comment
# comment
14
print(int(15/2))+3

Instead of truncating 15/2, Julia rounds it up, yielding 8. It prints this, then errors out on encountering +3.

9. Fission ; Try it online!

Relevant code:

        <"9"L

I got this idea from Martin's Fission portion (more like stole it). L begins a left-facing thing, captures 9, and ends with <.

10. Whitespace ; Try it here!

The relevant code, translating spaces into S and tabs into T:

SSSTSTS
T
ST

It pushes 10 to the stack and outputs it as a number (T\nST).

11. Python 2

Python 2 sees this:

# comment
# comment
14
print(int(15/2))+3

(int(15/2))+3 is evaluated to be 11, and that's printed.

12. Gol><> ; Try it here!

Relevant code:

#                      ;n@0d c

This uses the trick used in Martin's answer that @ rotates different directions in ><> and Gol><>. # mirrors, c pushes 12, d pushes 13, 0 pushes 0, and @ brings c to the top of the stack, then being outted and printed with ;n.

13. ><> ; Try it online!

Relevant code:

#                      ;n@0d c

Again using that @ rotates different directions in ><> and Gol><>. # mirrors, c pushes 12, d pushes 13, 0 pushes 0, and @ brings d to the top of the stack, then being outted and printed with ;n.

14. Golfscript ; Try it online!

What it sees:

# comment
# comment
    14
print(-int(-15/2))+3

It pushes 14, prints it, and errors. <s>Stolen</s> inspired by Sp3000's answer.


问:
Convert a Forsyth-Edwards Notation string to ASCII art
In chess, Forsyth-Edwards Notation, more commonly called "FEN", is a textual way of transcribing boards. It describes each of the board's eight rows (called "ranks" in chess) from top to bottom from White's perspective. The pieces are written as K (king), Q (queen), R (rook), B (bishop), N (knight), and P (pawn). Black pieces use these letters in lowercase, and white pieces use these letters in uppercase. Empty spaces are indicated by a number from 1 to 8 indicating how many consecutive empty spaces there are. A completely empty rank would be 8, a single black rook in the rightmost column (called "files" in chess) would be 7r, and two white pawns on each end of a row would be PP4PP. Ranks are separated by a /. There is normally other information added, indicating which side is to move, castling and en passant rights, move number, and halfmove clock, but we will ignore them for the purposes of this challenge.

Input

A FEN string, from the command line or STDIN, as you please. You may assume that this string is always valid.

Output

Write to STDOUT a simple ASCII art representation of the board as it would actually appear:

Pieces are represented by their character in FEN

Empty squares are represented by spaces

Pieces and squares are separated by a pipe | and there are pipes on each side of the board

So an empty board, written as 8/8/8/8/8/8/8/8 in FEN, would appear as

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

The starting position of a chess game is written as rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR, and would appear as

```<code>|r|n|b|q|k|b|n|r|
|p|p|p|p|p|p|p|p|
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
|P|P|P|P|P|P|P|P|
|R|N|B|Q|K|B|N|R|
</code>```

The final position of Anderssen-Kieseritzky 1851, called "The Immortal Game" in the chess community, is written as r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1, and your program when fed that input would output:

```<code>|r| |b|k| | | |r|
|p| | |p|B|p|N|p|
|n| | | | |n| | |
| |p| |N|P| | |P|
| | | | | | |P| |
| | | |P| | | | |
|P| |P| |K| | | |
|q| | | | | |b| |
</code>```

答:
JavaScript (ES6), <s>69</s> <s>67</s> 62 bytes

```<code>s=>[,...s.replace(/[/-8]/g,c=>+c?' '.repeat(c):`
`),,].join`|`
</code>```

The extra commas create empty values in the outer split which creates the beginning and ending | characters. You need two trailing commas because trailing commas are optional at the end of lists, so the first one is still part of the previous item.

Edit: Saved 5 bytes thanks to @user81655.

Body:
JavaScript (ES6), <s>69</s> <s>67</s> 62 bytes

s=>[,...s.replace(/[/-8]/g,c=>+c?' '.repeat(c):`
`),,].join`|`

The extra commas create empty values in the outer split which creates the beginning and ending | characters. You need two trailing commas because trailing commas are optional at the end of lists, so the first one is still part of the previous item.

Edit: Saved 5 bytes thanks to @user81655.


问:
Polynomialception
Given two polynomials f,g of arbitrary degree over the integers, your program/function should evaluate the first polynomial in the second polynomial. f(g(x)) (a.k.a. the composition (fog)(x) of the two polynomials)

Details

Builtins are allowed. You can assume any reasonable formatting as input/output, but the input and output format should match. E.g. formatting as a string

```<code>x^2+3x+5
</code>```

or as as list of coefficients:

```<code>[1,3,5] or alternatively [5,3,1]
</code>```

Furthermore the input polynomials can be assumed to be fully expanded, and the outputs are also expected to be fully expanded.

Examples

```<code>A(x) = x^2 + 3x + 5, B(y) = y+1
A(B(y)) = (y+1)^2 + 3(y+1) + 5 = y^2 + 5y + 9

A(x) = x^6 + x^2 + 1, B(y) = y^2 - y
A(B(y))= y^12 - 6y^11 + 15y^10 - 20y^9 + 15y^8 - 6y^7 + y^6 + y^4 - 2 y^3 + y^2 + 1

A(x) = 24x^3 - 144x^2 + 288x - 192, B(y) = y + 2
A(B(y)) = 24y^3

A(x) = 3x^4 - 36x^3 + 138x^2 - 180x + 27, B(y) = 2y + 3
A(B(y)) = 48y^4 - 96y^2
</code>```

答:
Python 2, 138 <s>156 162</s> bytes

The inputs are expected to be integer lists with smallest powers first.

def c(a,b):
 g=lambda p,q:q>[]and q[0]+p*g(p,q[1:]);B=99**len(`a+b`);s=g(g(B,b),a);o=[]
 while s:o+=(s+B/2)%B-B/2,;s=(s-o[-1])/B
 return o
```
<p>Ungolfed:</p>
<pre class="lang-py prettyprint-override"><code>def c(a,b):
 B=sum(map(abs,a+b))**len(a+b)**2
 w=sum(B**i*x for i,x in enumerate(b))
 s=sum(w**i*x for i,x in enumerate(a))
 o=[]
 while s:o+=min(s%B,s%B-B,key=abs),; s=(s-o[-1])/B
 return o
</code>```

In this computation, the polynomial coefficients are seen as digits (which may be negative) of a number in a very large base. After polynomials are in this format, multiplication or addition is a single integer operation. As long as the base is sufficiently large, there won't be any carries that spill over into neighboring digits.

-18 from improving bound on B as suggested by @xnor.

Title: Polynomialception

Body:
Python 2, 138 <s>156 162</s> bytes

The inputs are expected to be integer lists with smallest powers first.

def c(a,b):
 g=lambda p,q:q>[]and q[0]+p*g(p,q[1:]);B=99**len(`a+b`);s=g(g(B,b),a);o=[]
 while s:o+=(s+B/2)%B-B/2,;s=(s-o[-1])/B
 return o

Ungolfed:

def c(a,b):
 B=sum(map(abs,a+b))**len(a+b)**2
 w=sum(B**i*x for i,x in enumerate(b))
 s=sum(w**i*x for i,x in enumerate(a))
 o=[]
 while s:o+=min(s%B,s%B-B,key=abs),; s=(s-o[-1])/B
 return o

In this computation, the polynomial coefficients are seen as digits (which may be negative) of a number in a very large base. After polynomials are in this format, multiplication or addition is a single integer operation. As long as the base is sufficiently large, there won't be any carries that spill over into neighboring digits.

-18 from improving bound on B as suggested by @xnor.


问:
m-nomial coefficient
While the binomial coefficient are the coefficients of \$(1+x)^n\$, m-nomial coefficients are the coefficients of \$(1+x+x^2+...+x^{m-1})^n\$.

For example, \$m(3,5,6)\$ is the coefficient of \$x^6\$ in the expansion of \$(1+x+x^2)^5\$.

Write a program/function that takes 3 numbers as input and outputs the corresponding m-nomial coefficient.

Details

Input can be taken via any reasonable method.

Everything out of range is \$0\$, for example \$m(2,0,-1) = m(2,5,6) = 0\$

The first argument will be positive.

The second argument will not be negative.

All three arguments will be integers.

Testcases

Inputs:

```<code>[1,0,0]
[2,5,6]
[3,5,6]
[4,5,-1]
</code>```

Outputs:

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

Scoring

This is code-golf. Shortest solution in bytes wins.

答:
Perl, <s>63</s> <s>60</s> <s>59</s> 57 bytes

Includes +2 for -pa

Give input parameters on STDIN

```<code>mnomial.pl <<< "3 5 6"

#!/usr/bin/perl -pa
$_=/-/^($_--,1x$F[2])=~/^(1{0,$_}){$F[1]}$(??{++$;})/+$
</code>```

As a perl programmer I just know that every problem is really a regex in disguise...

Explanation:

m(3,5,6) can be seen as the number of ways you can get 6 by adding 5 integers in the range [0..2]. You can write a regex matching such a partition using:

```<code>1 x 6 = /^(1{0,2}){5}$/
</code>```

However once a single solution is found the regex stops. We need to fail the found solution to get the regex to backtrack to the next solution and count the failures. In perl this can be done by extending the regex at runtime with something that is sure to fail, e.g. by demanding that something comes after the end of the string:

```<code> 1 x 6 = /^(1{0,2}){5}$(??{++$n})/
</code>```

$n will count the number of failed attempts

My solution is basically this with two modifications:

Output the counter in such a way that you get 0 instead of the empty string if there is no valid partition and the counter never gets incremented

If the third argument is negative it would work if negative string lengths existed, but 1 x -5 is the empty string and 0 can be written exactly one way as sum of zeros, so that would output 1 instead of 0. I xor with the result of /-/to change the 1 back to 0

Without the need to handle a negative third argument this 49 byte solution would be good enough (give one parameter of m(x,y,z) on each line of STDIN in order y \n z \n x \n):

```<code>#!/usr/bin/perl -pa
$_=(1x<>)=~/^(1{0,@{[<>-1]}}){@F}$(??{++$;})/+$
</code>```

Title: m-nomial coefficient

Body:
Perl, <s>63</s> <s>60</s> <s>59</s> 57 bytes

Includes +2 for -pa

Give input parameters on STDIN

mnomial.pl <<< "3 5 6"

#!/usr/bin/perl -pa
$_=/-/^($_--,1x$F[2])=~/^(1{0,$_}){$F[1]}$(??{++$;})/+$

As a perl programmer I just know that every problem is really a regex in disguise...

Explanation:

m(3,5,6) can be seen as the number of ways you can get 6 by adding 5 integers in the range [0..2]. You can write a regex matching such a partition using:

1 x 6 = /^(1{0,2}){5}$/

However once a single solution is found the regex stops. We need to fail the found solution to get the regex to backtrack to the next solution and count the failures. In perl this can be done by extending the regex at runtime with something that is sure to fail, e.g. by demanding that something comes after the end of the string:

 1 x 6 = /^(1{0,2}){5}$(??{++$n})/

$n will count the number of failed attempts

My solution is basically this with two modifications:

Output the counter in such a way that you get 0 instead of the empty string if there is no valid partition and the counter never gets incremented

If the third argument is negative it would work if negative string lengths existed, but 1 x -5 is the empty string and 0 can be written exactly one way as sum of zeros, so that would output 1 instead of 0. I xor with the result of /-/to change the 1 back to 0

Without the need to handle a negative third argument this 49 byte solution would be good enough (give one parameter of m(x,y,z) on each line of STDIN in order y \n z \n x \n):

#!/usr/bin/perl -pa
$_=(1x<>)=~/^(1{0,@{[<>-1]}}){@F}$(??{++$;})/+$


问:
Javascript left-pad golf

Introduction

In the wake of the left-pad npm package fallout, let's have a code golf for implementing left-pad.

The left-pad function consists of 2 default arguments and 1 additional argument, in the form string, length, (padchar). If the padchar is not given, this is standardized to a space character. Let's take an example with two arguments:

```<code>left_pad("abc", 6)
</code>```

First, we observe the length of the string, which is 3. After this, we need to pad this string in the left until the length of the full string has reached the length given in the function. In this case 6. Since the padchar is not given, we need to pad this with spaces:

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

This is a string with 3 spaces and the initial string, resulting into a string with length 6. Here is an example with the padchar given:

```<code>left_pad("abc", 6, "-")
</code>```

We just do the same as the example above, but replace the spaces with the padchar. In this case, the hyphen:

```<code>---abc
</code>```

The Task

Given the string, length, and maybe the additional argument padchar, output the left-padded string. You can assume that the length number is equal or greater than the length of the string. The padchar will always consist of 1 character.

Test cases

```<code>left_pad("string", length, ("padchar")) === "left-padded string"

left_pad("foo", 5) === "  foo"
left_pad("foobar", 6) === "foobar"
left_pad("1", 2, "0") === "01"
left_pad("1", 2, "-") === "-1"
</code>```

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

答:
JavaScript ES6, 38 bytes

```<code>(s,l,c=" ")=>(c.repeat(l)+s).slice(-l)
</code>```

An alternate solution.

Title: Javascript left-pad golf

Body:
JavaScript ES6, 38 bytes

(s,l,c=" ")=>(c.repeat(l)+s).slice(-l)

An alternate solution.


答:
Jelly, 6 bytes

```<code>ṗ’S€ċ⁵
</code>```

This is a full program that accepts m, n and the exponent as separate command line arguments.

Try it online!

How it works

The problem boils down to counting the number of ways we can express the exponent as an ordered sum of exactly n integers between 0 and m - 1 (both inclusive).

```<code>ṗ’S€ċ⁵  Main link. Arguments: m, n, k

ṗ       Cartesian product; yield the array of all lists of exactly n elements of
        [1, ..., m].
 ’      Decrement all integers in the resulting 2D list.
  S€    Compute the sum of each individual list.
     ⁵  Yield k.
    ċ   Count the number of times k appears in the list of sums.
</code>```

Title: m-nomial coefficient

Body:
While the binomial coefficient are the coefficients of \$(1+x)^n\$, m-nomial coefficients are the coefficients of \$(1+x+x^2+...+x^{m-1})^n\$.

For example, \$m(3,5,6)\$ is the coefficient of \$x^6\$ in the expansion of \$(1+x+x^2)^5\$.

Write a program/function that takes 3 numbers as input and outputs the corresponding m-nomial coefficient.

Details

Input can be taken via any reasonable method.

Everything out of range is \$0\$, for example \$m(2,0,-1) = m(2,5,6) = 0\$

The first argument will be positive.

The second argument will not be negative.

All three arguments will be integers.

Testcases

Inputs:

```<code>[1,0,0]
[2,5,6]
[3,5,6]
[4,5,-1]
</code>```

Outputs:

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

Scoring

This is code-golf. Shortest solution in bytes wins.

Body:
Jelly, 6 bytes

ṗ’S€ċ⁵

This is a full program that accepts m, n and the exponent as separate command line arguments.

Try it online!

How it works

The problem boils down to counting the number of ways we can express the exponent as an ordered sum of exactly n integers between 0 and m - 1 (both inclusive).

ṗ’S€ċ⁵  Main link. Arguments: m, n, k

ṗ       Cartesian product; yield the array of all lists of exactly n elements of
        [1, ..., m].
 ’      Decrement all integers in the resulting 2D list.
  S€    Compute the sum of each individual list.
     ⁵  Yield k.
    ċ   Count the number of times k appears in the list of sums.


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

答:
string literals are special

I never realised this before, but "strings" are rather special to the parser.

```<code>"asd""abc"
</code>```

is equivalent to:

```<code>"asd" "abc"
</code>```

and

```<code>URL" a"split
</code>```

is the same as

```<code>URL" a" split
</code>```

This is perhaps the only time whitespace isn't necessary in Factor, and also works for URL" ", DLL" ", P" ", SBUF" " and the others handled by parse-string, as pointed out by @fedes. in the comments.

Note well that the opening quote-like marker must be preceded by whitespace.

The following are considered one word:

```<code>filter"asdasd"map
filter"asdasd"
</code>```

And you will get a No word <blah> found in current vocabulary search path error.

Title: Tips for golfing in Factor

Body:
string literals are special

I never realised this before, but "strings" are rather special to the parser.

"asd""abc"

is equivalent to:

"asd" "abc"

and

URL" a"split

is the same as

URL" a" split

This is perhaps the only time whitespace isn't necessary in Factor, and also works for URL" ", DLL" ", P" ", SBUF" " and the others handled by parse-string, as pointed out by @fedes. in the comments.

Note well that the opening quote-like marker must be preceded by whitespace.

The following are considered one word:

filter"asdasd"map
filter"asdasd"

And you will get a No word <blah> found in current vocabulary search path error.


答:
MATLAB with Symbolic Toolbox, 28 bytes

```<code>@(f,g)collect(subs(f,'x',g))
</code>```

This is an anonymous function. To call it assign it to a variable or use ans.  Inputs are strings with the format (spaces are optional)

```<code>x^2 + 3*x + 5
</code>```

Example run:

```<code>>> @(f,g)collect(subs(f,'x',g))
ans =
    @(f,g)collect(subs(f,'x',g))
>> ans('3*x^4 - 36*x^3 + 138*x^2 - 180*x + 27','2*x + 3')
ans =
48*x^4 - 96*x^2
</code>```

Title: Polynomialception

Body:
Given two polynomials f,g of arbitrary degree over the integers, your program/function should evaluate the first polynomial in the second polynomial. f(g(x)) (a.k.a. the composition (fog)(x) of the two polynomials)

Details

Builtins are allowed. You can assume any reasonable formatting as input/output, but the input and output format should match. E.g. formatting as a string

```<code>x^2+3x+5
</code>```

or as as list of coefficients:

```<code>[1,3,5] or alternatively [5,3,1]
</code>```

Furthermore the input polynomials can be assumed to be fully expanded, and the outputs are also expected to be fully expanded.

Examples

```<code>A(x) = x^2 + 3x + 5, B(y) = y+1
A(B(y)) = (y+1)^2 + 3(y+1) + 5 = y^2 + 5y + 9

A(x) = x^6 + x^2 + 1, B(y) = y^2 - y
A(B(y))= y^12 - 6y^11 + 15y^10 - 20y^9 + 15y^8 - 6y^7 + y^6 + y^4 - 2 y^3 + y^2 + 1

A(x) = 24x^3 - 144x^2 + 288x - 192, B(y) = y + 2
A(B(y)) = 24y^3

A(x) = 3x^4 - 36x^3 + 138x^2 - 180x + 27, B(y) = 2y + 3
A(B(y)) = 48y^4 - 96y^2
</code>```

Body:
MATLAB with Symbolic Toolbox, 28 bytes

@(f,g)collect(subs(f,'x',g))

This is an anonymous function. To call it assign it to a variable or use ans.  Inputs are strings with the format (spaces are optional)

x^2 + 3*x + 5

Example run:

>> @(f,g)collect(subs(f,'x',g))
ans =
    @(f,g)collect(subs(f,'x',g))
>> ans('3*x^4 - 36*x^3 + 138*x^2 - 180*x + 27','2*x + 3')
ans =
48*x^4 - 96*x^2


答:
Haskell, <s>86</s> 72 bytes

u!c=foldr1((.u).zipWith(+).(++[0,0..])).map c
o g=(0:)!((<$>g).(*))!pure
```

<p>Defines a function <code>o</code> such that <code>o g f</code> computes the composition f ∘ g.  Polynomials are represented by a nonempty list of coefficients starting at the constant term.</p>

<h2>Demo</h2>

```*Main> o [1,1] [5,3,1]
[9,5,1]
*Main> o [0,-1,1] [1,0,1,0,0,0,1]
[1,0,1,-2,1,0,1,-6,15,-20,15,-6,1]
*Main> o [2,1] [-192,288,-144,24]
[0,0,0,24]
*Main> o [3,2] [27,-180,138,-36,3]
[0,0,-96,0,48]
```

How it works

No polynomial-related builtins or libraries.  Observe the similar recurrences

f(x) = a + f₁(x)x ⇒ f(x)g(x) = a g(x) + f₁(x)g(x)x,

f(x) = a + f₁(x)x ⇒ f(g(x)) = a + f₁(g(x))g(x),

for polynomial multiplication and composition, respectively.  They both take the form

f(x) = a + f₁(x)x ⇒ W(f)(x) = C(a)(x) + U(W(f₁))(x).

The operator ! solves a recurrence of this form for W given U and C, using zipWith(+).(++[0,0..]) for polynomial addition (assuming the second argument is longer—for our purposes, it always will be).  Then,

(0:) multiplies a polynomial argument by x (by prepending a zero coefficient);

(<$>g).(*) multiplies a scalar argument by the polynomial g;

(0:)!((<$>g).(*)) multiplies a polynomial argument by the polynomial g;

pure lifts a scalar argument to a constant polynomial (singleton list);

(0:)!((<$>g).(*))!pure composes a polynomial argument with the polynomial g.

Title: Polynomialception

Body:
Haskell, <s>86</s> 72 bytes

u!c=foldr1((.u).zipWith(+).(++[0,0..])).map c
o g=(0:)!((<$>g).(*))!pure

Defines a function o such that o g f computes the composition f ∘ g.  Polynomials are represented by a nonempty list of coefficients starting at the constant term.

Demo

*Main> o [1,1] [5,3,1]
[9,5,1]
*Main> o [0,-1,1] [1,0,1,0,0,0,1]
[1,0,1,-2,1,0,1,-6,15,-20,15,-6,1]
*Main> o [2,1] [-192,288,-144,24]
[0,0,0,24]
*Main> o [3,2] [27,-180,138,-36,3]
[0,0,-96,0,48]

How it works

No polynomial-related builtins or libraries.  Observe the similar recurrences

f(x) = a + f₁(x)x ⇒ f(x)g(x) = a g(x) + f₁(x)g(x)x,

f(x) = a + f₁(x)x ⇒ f(g(x)) = a + f₁(g(x))g(x),

for polynomial multiplication and composition, respectively.  They both take the form

f(x) = a + f₁(x)x ⇒ W(f)(x) = C(a)(x) + U(W(f₁))(x).

The operator ! solves a recurrence of this form for W given U and C, using zipWith(+).(++[0,0..]) for polynomial addition (assuming the second argument is longer—for our purposes, it always will be).  Then,

(0:) multiplies a polynomial argument by x (by prepending a zero coefficient);

(<$>g).(*) multiplies a scalar argument by the polynomial g;

(0:)!((<$>g).(*)) multiplies a polynomial argument by the polynomial g;

pure lifts a scalar argument to a constant polynomial (singleton list);

(0:)!((<$>g).(*))!pure composes a polynomial argument with the polynomial g.


问:
Generate 100 Java Tuple classes
Write a script that writes to standard output, or your language's equivalent, 100 lines of (valid) Java code that begins with:

```<code>class Tuple1 {public Object _0;}
class Tuple2 {public Object _0,_1;}
class Tuple3 {public Object _0,_1,_2;}
class Tuple4 {public Object _0,_1,_2,_3;}
class Tuple5 {public Object _0,_1,_2,_3,_4;}
class Tuple6 {public Object _0,_1,_2,_3,_4,_5;}
class Tuple7 {public Object _0,_1,_2,_3,_4,_5,_6;}
class Tuple8 {public Object _0,_1,_2,_3,_4,_5,_6,_7;}
class Tuple9 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8;}
class Tuple10 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8,_9;}
class Tuple11 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10;}
class Tuple12 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11;}
</code>```

The last line should begin with class Tuple100.

This is code-golf, so the shortest code in bytes wins!

答:
Pip, <s>53</s> 51 bytes

```<code>LhP["class Tuple"++i" {public Object "'_.,iJ',";}"]
</code>```

Try it online!

Explanation:

```<code>                        h is preinitialized to 100 and i to 0 (implicit)
L h                     Loop 100 times:
 P [                    Print the following list (with trailing newline):
    "class Tuple"
    ++i                 Increment i here so that its values run from 1 to 100
    " {public Object "
    ('_ . ,i) J ',      Range(i), concatenate "_" before each element, join on ","
    ";}"
   ]                    By default, lists are concatenated when printed
</code>```

Title: Generate 100 Java Tuple classes

Body:
Pip, <s>53</s> 51 bytes

LhP["class Tuple"++i" {public Object "'_.,iJ',";}"]

Try it online!

Explanation:

                        h is preinitialized to 100 and i to 0 (implicit)
L h                     Loop 100 times:
 P [                    Print the following list (with trailing newline):
    "class Tuple"
    ++i                 Increment i here so that its values run from 1 to 100
    " {public Object "
    ('_ . ,i) J ',      Range(i), concatenate "_" before each element, join on ","
    ";}"
   ]                    By default, lists are concatenated when printed


Title: Polynomialception

Body:
PARI/GP, 19 bytes

(a,b)->subst(a,x,b)

which lets you do

%(x^2+1,x^2+x-1)

to get

%2 = x^4 + 2*x^3 - x^2 - 2*x + 2


答:
Julia, <s>50</s> 45 bytes

```<code>f(m,n,k)=n>0?sum(t->f(m,n-1,k-t),0:m-1):0^k^2
</code>```

Try it online!

If digits supported unary, the following approach would be 1 byte shorter.

```<code>g(m,n,k)=sum(t->k==sum(digits(t,m)),0:m^n-1)
</code>```

Title: m-nomial coefficient

Body:
Julia, <s>50</s> 45 bytes

f(m,n,k)=n>0?sum(t->f(m,n-1,k-t),0:m-1):0^k^2

Try it online!

If digits supported unary, the following approach would be 1 byte shorter.

g(m,n,k)=sum(t->k==sum(digits(t,m)),0:m^n-1)


答:
Sage, 24 bytes

lambda A,B:A(B).expand()
```

As of Sage 6.9 (the version that runs on http://sagecell.sagemath.org), function calls without explicit argument assignment (f(2) rather than f(x=2)) causes an annoying and unhelpful message to be printed to STDERR. Because STDERR can be ignored by default in code golf, this is still valid.

This is very similar to Dennis's SymPy answer because Sage is a) built on Python, and b) uses Maxima, a computer algebra system very similar to SymPy in many ways. However, Sage is much more powerful than Python with SymPy, and thus is a different enough language that it merits its own answer.

Verify all test cases online

Title: Polynomialception

Body:
Sage, 24 bytes

lambda A,B:A(B).expand()

As of Sage 6.9 (the version that runs on http://sagecell.sagemath.org), function calls without explicit argument assignment (f(2) rather than f(x=2)) causes an annoying and unhelpful message to be printed to STDERR. Because STDERR can be ignored by default in code golf, this is still valid.

This is very similar to Dennis's SymPy answer because Sage is a) built on Python, and b) uses Maxima, a computer algebra system very similar to SymPy in many ways. However, Sage is much more powerful than Python with SymPy, and thus is a different enough language that it merits its own answer.

Verify all test cases online


问:
Create a Boolean parser (continued)
Continuation of this challenge because the author is gone and the question is closed.

What you need to do is create a Boolean parser.

Boolean expressions, in case you haven't heard of them yet, have two inputs and one output.

There are four "gates" in boolean arithmetic, namely:

OR (represented by |) (binary operator, between arguments)

AND (represented by &) (binary operator, between arguments)

XOR (represented by ^) (binary operator, between arguments)

NOT (represented by !) (unary operator, argument on right)

These gates operate on their inputs which are either true (represented by 1) or false (represented by 0). We can list the possible inputs (A and B in this case) and the outputs (O) using a truth table as follows:

```<code>XOR
A|B|O
-----
0|0|0
0|1|1
1|0|1
1|1|0

OR
A|B|O
-----
0|0|0
0|1|1
1|0|1
1|1|1

AND
A|B|O
-----
0|0|0
0|1|0
1|0|0
1|1|1

NOT
A|O
---
0|1
1|0
</code>```

An example input would be 1^((1|0&0)^!(1&!0&1)), which would evaluate to:

```<code> 1^((1|0&0)^!(1&!0&1))
=1^(( 1 &0)^!(1&!0&1))
=1^(   0   ^!(1&!0&1))
=1^(   0   ^!(1& 1&1))
=1^(   0   ^!(  1 &1))
=1^(   0   ^!    1   )
=1^(   0   ^    0    )
=1^0
=1
</code>```

The output would be 1.

Details

As seen in the example, there is no order of prevalence. All are evaluated from left to right, except when inside parentheses, which should be evaluated first.

The input will only contain ()!^&|01.

You can choose any 8-byte character to replace the 8 characters above, but they must have a 1-to-1 mapping and must be stated.

Specifically, the function eval is not allowed to be used on any string derived from the input. Specifically, the function input (or the equivalent in the language) and any function that calls it cannot be used by eval. You also cannot concatenate the input into your string inside the eval.

Scoring

This is code-golf. Shortest solution in bytes wins.

答:
grep + shell utils, 131 bytes

```<code>rev|grep -cP '^(((0|R((?9)(x(?1)|a(?4))|(?2)([oxa](?4)|a(?1)|))L|(1|R(?1)L)!)(!!)*)[xo](?1)|(1|R(?1)L|(?2)!)([ao](?1)|[xo](?4)|))$'
</code>```

The following chars are renamed:

```<code>( -> L
) -> R
| -> o
& -> a
^ -> x
</code>```

I started trying to write a grep solution, but discovered that it did not work well with the left-associative infix operators. I needed to have a pattern like (chain of operators) = (chain of operators) (binary op) (single operand), but this contains a possible infinite recursion, so grep refuses to execute it. But I noticed that I could parse right-associative operators. This made the ! operator a pain, but it was still possible. So I made a regex for calculating backwards boolean expressions, and sent the input through rev. The regex itself, which matches true expressions, is 116 bytes.

TODO: choose different characters for the input so that I can distinguish all the used groups of operators with built-in character classes.

Title: Create a Boolean parser (continued)

Body:
grep + shell utils, 131 bytes

rev|grep -cP '^(((0|R((?9)(x(?1)|a(?4))|(?2)([oxa](?4)|a(?1)|))L|(1|R(?1)L)!)(!!)*)[xo](?1)|(1|R(?1)L|(?2)!)([ao](?1)|[xo](?4)|))$'

The following chars are renamed:

( -> L
) -> R
| -> o
& -> a
^ -> x

I started trying to write a grep solution, but discovered that it did not work well with the left-associative infix operators. I needed to have a pattern like (chain of operators) = (chain of operators) (binary op) (single operand), but this contains a possible infinite recursion, so grep refuses to execute it. But I noticed that I could parse right-associative operators. This made the ! operator a pain, but it was still possible. So I made a regex for calculating backwards boolean expressions, and sent the input through rev. The regex itself, which matches true expressions, is 116 bytes.

TODO: choose different characters for the input so that I can distinguish all the used groups of operators with built-in character classes.


答:
Sage, 71 bytes

lambda a,b,c:(c>=0and(sum(x^i for i in range(a))^b).list()[c:]or[0])[0]
```

Verify all test cases online

The unnamed lambda function constructs the polynomial and returns the specified coefficient if c is not negative and less than or equal to the degree of the polynomial, else 0.

Title: m-nomial coefficient

Body:
Sage, 71 bytes

lambda a,b,c:(c>=0and(sum(x^i for i in range(a))^b).list()[c:]or[0])[0]

Verify all test cases online

The unnamed lambda function constructs the polynomial and returns the specified coefficient if c is not negative and less than or equal to the degree of the polynomial, else 0.


答:
Julia, 62 bytes

s->split("|"join(replace(s,r"\d",d->" "^parse(d)),"|")"|","/")
```

This is an anonymous function that accepts a string and returns an array of strings. To call it, assign it to a variable.

The approach is the same as in QPaysTaxes' clever Ruby answer. We replace each digit in the input with that many spaces, place | between each character, tack | onto the front and back, and split into an array on /.

Try it online!

Title: Convert a Forsyth-Edwards Notation string to ASCII art

Body:
In chess, Forsyth-Edwards Notation, more commonly called "FEN", is a textual way of transcribing boards. It describes each of the board's eight rows (called "ranks" in chess) from top to bottom from White's perspective. The pieces are written as K (king), Q (queen), R (rook), B (bishop), N (knight), and P (pawn). Black pieces use these letters in lowercase, and white pieces use these letters in uppercase. Empty spaces are indicated by a number from 1 to 8 indicating how many consecutive empty spaces there are. A completely empty rank would be 8, a single black rook in the rightmost column (called "files" in chess) would be 7r, and two white pawns on each end of a row would be PP4PP. Ranks are separated by a /. There is normally other information added, indicating which side is to move, castling and en passant rights, move number, and halfmove clock, but we will ignore them for the purposes of this challenge.

Input

A FEN string, from the command line or STDIN, as you please. You may assume that this string is always valid.

Output

Write to STDOUT a simple ASCII art representation of the board as it would actually appear:

Pieces are represented by their character in FEN

Empty squares are represented by spaces

Pieces and squares are separated by a pipe | and there are pipes on each side of the board

So an empty board, written as 8/8/8/8/8/8/8/8 in FEN, would appear as

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

The starting position of a chess game is written as rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR, and would appear as

```<code>|r|n|b|q|k|b|n|r|
|p|p|p|p|p|p|p|p|
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
|P|P|P|P|P|P|P|P|
|R|N|B|Q|K|B|N|R|
</code>```

The final position of Anderssen-Kieseritzky 1851, called "The Immortal Game" in the chess community, is written as r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1, and your program when fed that input would output:

```<code>|r| |b|k| | | |r|
|p| | |p|B|p|N|p|
|n| | | | |n| | |
| |p| |N|P| | |P|
| | | | | | |P| |
| | | |P| | | | |
|P| |P| |K| | | |
|q| | | | | |b| |
</code>```

Body:
Julia, 62 bytes

s->split("|"join(replace(s,r"\d",d->" "^parse(d)),"|")"|","/")

This is an anonymous function that accepts a string and returns an array of strings. To call it, assign it to a variable.

The approach is the same as in QPaysTaxes' clever Ruby answer. We replace each digit in the input with that many spaces, place | between each character, tack | onto the front and back, and split into an array on /.

Try it online!


答:
Python, 210 bytes

```<code>from operator import*;
def t(o):c=o.pop(0);return ord(c)-48if c in"01"else[p(o),o.pop(0)][0]if"("==c else 1-t(o)
def p(o):
 v=t(o)
 while o and")"!=o[0]:v=[xor,or_,and_]["^|&".index(o.pop(0))](v,t(o))
 return v
</code>```

Really bad recursive descent, I expect this to be beaten in a heartbeat.

Title: Create a Boolean parser (continued)

Body:
Continuation of this challenge because the author is gone and the question is closed.

What you need to do is create a Boolean parser.

Boolean expressions, in case you haven't heard of them yet, have two inputs and one output.

There are four "gates" in boolean arithmetic, namely:

OR (represented by |) (binary operator, between arguments)

AND (represented by &) (binary operator, between arguments)

XOR (represented by ^) (binary operator, between arguments)

NOT (represented by !) (unary operator, argument on right)

These gates operate on their inputs which are either true (represented by 1) or false (represented by 0). We can list the possible inputs (A and B in this case) and the outputs (O) using a truth table as follows:

```<code>XOR
A|B|O
-----
0|0|0
0|1|1
1|0|1
1|1|0

OR
A|B|O
-----
0|0|0
0|1|1
1|0|1
1|1|1

AND
A|B|O
-----
0|0|0
0|1|0
1|0|0
1|1|1

NOT
A|O
---
0|1
1|0
</code>```

An example input would be 1^((1|0&0)^!(1&!0&1)), which would evaluate to:

```<code> 1^((1|0&0)^!(1&!0&1))
=1^(( 1 &0)^!(1&!0&1))
=1^(   0   ^!(1&!0&1))
=1^(   0   ^!(1& 1&1))
=1^(   0   ^!(  1 &1))
=1^(   0   ^!    1   )
=1^(   0   ^    0    )
=1^0
=1
</code>```

The output would be 1.

Details

As seen in the example, there is no order of prevalence. All are evaluated from left to right, except when inside parentheses, which should be evaluated first.

The input will only contain ()!^&|01.

You can choose any 8-byte character to replace the 8 characters above, but they must have a 1-to-1 mapping and must be stated.

Specifically, the function eval is not allowed to be used on any string derived from the input. Specifically, the function input (or the equivalent in the language) and any function that calls it cannot be used by eval. You also cannot concatenate the input into your string inside the eval.

Scoring

This is code-golf. Shortest solution in bytes wins.

Body:
Python, 210 bytes

from operator import*;
def t(o):c=o.pop(0);return ord(c)-48if c in"01"else[p(o),o.pop(0)][0]if"("==c else 1-t(o)
def p(o):
 v=t(o)
 while o and")"!=o[0]:v=[xor,or_,and_]["^|&".index(o.pop(0))](v,t(o))
 return v

Really bad recursive descent, I expect this to be beaten in a heartbeat.


答:
Pyth, <s>51</s> 34 bytes

```<code>AQsM.t*LVG.usM.t.e+*]0k*LbHN0tG]1Z
</code>```

Test suite.

Title: Polynomialception

Body:
Pyth, <s>51</s> 34 bytes

AQsM.t*LVG.usM.t.e+*]0k*LbHN0tG]1Z

Test suite.


答:
C, 252 bytes

i=-1,j,s=1,x;C(char*n){while(n[++i])s+=isdigit(n[i])?n[i]*2+1:2;char*m=(char*)malloc(s);for(i=j=-1;n[++i]&(m[++j]='|');)if(n[i]=='/')m[++j]='\n';else if(isdigit(n[i]))for(x=n[i]-'0';x;--x&&(m[++j]='|'))m[++j]=' ';else m[++j]=n[i];m[++j]='\0';return m;}
```

<p><strong>Detailed</strong> <em>try online</em></p>

<pre class="lang-c prettyprint-override"><code>// input-string, input-string-size
char* C(char*n)
{
    int i=-1,j,s=1,x;

    // figure out required grid size
    while(n[++i])s+=isdigit(n[i])?n[i]*2+1:2;
    char*m=(char*)malloc(s);

    i=j=-1;
    while(n[++i]) // while not end of string
    {
        m[++j]='|'; // seperator

        if (n[i]=='/') // end of row
            m[++j]='\n';
        else if (isdigit(n[i])) // fill spaces
            for(x=n[i]-'0';x;--x&&(m[++j]='|')) m[++j]=' ';
        else
            m[++j]=n[i]; // single literals
    }

    m[++j]='|';
    m[++j]='\0';
    return m;
}
</code>```

Body:
C, 252 bytes

i=-1,j,s=1,x;C(char*n){while(n[++i])s+=isdigit(n[i])?n[i]*2+1:2;char*m=(char*)malloc(s);for(i=j=-1;n[++i]&(m[++j]='|');)if(n[i]=='/')m[++j]='\n';else if(isdigit(n[i]))for(x=n[i]-'0';x;--x&&(m[++j]='|'))m[++j]=' ';else m[++j]=n[i];m[++j]='\0';return m;}

Detailed try online

// input-string, input-string-size
char* C(char*n)
{
    int i=-1,j,s=1,x;

    // figure out required grid size
    while(n[++i])s+=isdigit(n[i])?n[i]*2+1:2;
    char*m=(char*)malloc(s);

    i=j=-1;
    while(n[++i]) // while not end of string
    {
        m[++j]='|'; // seperator

        if (n[i]=='/') // end of row
            m[++j]='\n';
        else if (isdigit(n[i])) // fill spaces
            for(x=n[i]-'0';x;--x&&(m[++j]='|')) m[++j]=' ';
        else
            m[++j]=n[i]; // single literals
    }

    m[++j]='|';
    m[++j]='\0';
    return m;
}


问:
How many 14ers did I climb?
In mountaineering terminology, a "14er" is any mountain with an elevation of 14 000 feet or more. However, there is another distinction. For a peak to count as a 14er, it must also have a "geographic prominence" of 300 or more feet. This means that to move from one 14er to another, you must first descend at least 300 feet before rising again. Take this example. Line 1 counts as 14 000 feet, and each line counts as 100 feet.

```<code>  /\__/\
 /      \
/        \
</code>```

Now, both of these peaks have enough elevation to count, but there isn't enough drop in elevation between them to count as two separate peaks. Therefore, one of these counts as a 14er, and the other one is just a "partial peak". Here is an example where the two peaks count as two separate 14er:

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

There can also be a partial peak on the decline between two 14ers. Here's a slightly modified version of the last mountain range:

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

This mountain range also counts as two 14ers.

You must write a program or function that takes an ascii-art representation of a mountain range, and return how many 14ers are in the range. You can take input in whatever format is most convenient for you, be it 2D array of characters, a string with newline, or a string with some other delimiter. You can assume that all inputs will only contain the characters /\_, and that the length of each line will be the same (including trailing spaces). You can also assume that the mountain range starts on the bottom left corner with either a / or a _.

If the last section of a mountain is not on the bottom line, you can assume that the mountain only decreases after that, e.g.

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

Counts as a single 14er.

You do not have to handle invalid mountain ranges.

Here is some sample I/O:

```<code>         /\___/\_
        /        \    /\
       /          \  /  \
   _/\/            \/    \
  /                       \
 /                         \
/                           \_

2

                  /\    /\
         /\      /  \  /
  /\    /  \    /    \/
 /  \  /    \  /
/    \/      \/

4

       /\
 _/\__/  \
/         \

1

      /\
     /  \   /\
    /    \_/  \
   /           \
  /             \
 /               \
/                 \

1

              /\
    /\_/\    /  \_
   /     \  /     \     /\
  /       \/       \   /
 /                  \_/
/

3
</code>```

答:
JavaScript (ES6), 154 bytes

```<code>s=>s.split`\n`.map((s,i)=>s.replace(/\S/g,(c,j)=>{e[j]=i+(c!='\\');e[j+1]=i+(c>'/')}),e=[])&&e.map(n=>h-n+d?h-n-d*3?0:(c++,d=-d,h=n):h=n,h=e[0],c=d=1)|c>>1
</code>```

Where \n represents the literal newline character. Ungolfed:

```<code>function climb(string) {
    var heights = [];
    // Split the array into lines so that we know the offset of each char
    var array = string.split("\n");
    // Calculate the height (actually depth) before and after each char
    for (var i = 0; i < array.length; i++) {
        for (var j = 0; j < string.length; j++) {
            switch (array[i][j]) {
            case '\':
                heights[j] = i;
                heights[j+1] = i + 1;
                break;
            case '_':
                heights[j] = i + 1;
                heights[j+1] = i + 1;
                break;
            case '/':
                heights[j] = i + 1;
                heights[j+1] = i;
                break;
        }
    }
    var count = 1;
    // Start by looking for an upward direction
    var direction = 1;
    var height = heights[0];
    for (var k = 1; k < heights.length; k++) {
        if (heights[i] == height - direction * 3) { // peak or trough
            direction *= -1;
            count++; // we're counting changes of direction = peaks * 2
            height = heights[i];
        } else if (heights[i] == height + direction) {
            // Track the current peak or trough to the tip or base
            height = heights[i];
        }
    }
    return count >> 1;
}
</code>```

Title: How many 14ers did I climb?

Body:
JavaScript (ES6), 154 bytes

s=>s.split`\n`.map((s,i)=>s.replace(/\S/g,(c,j)=>{e[j]=i+(c!='\\');e[j+1]=i+(c>'/')}),e=[])&&e.map(n=>h-n+d?h-n-d*3?0:(c++,d=-d,h=n):h=n,h=e[0],c=d=1)|c>>1

Where \n represents the literal newline character. Ungolfed:

function climb(string) {
    var heights = [];
    // Split the array into lines so that we know the offset of each char
    var array = string.split("\n");
    // Calculate the height (actually depth) before and after each char
    for (var i = 0; i < array.length; i++) {
        for (var j = 0; j < string.length; j++) {
            switch (array[i][j]) {
            case '\':
                heights[j] = i;
                heights[j+1] = i + 1;
                break;
            case '_':
                heights[j] = i + 1;
                heights[j+1] = i + 1;
                break;
            case '/':
                heights[j] = i + 1;
                heights[j+1] = i;
                break;
        }
    }
    var count = 1;
    // Start by looking for an upward direction
    var direction = 1;
    var height = heights[0];
    for (var k = 1; k < heights.length; k++) {
        if (heights[i] == height - direction * 3) { // peak or trough
            direction *= -1;
            count++; // we're counting changes of direction = peaks * 2
            height = heights[i];
        } else if (heights[i] == height + direction) {
            // Track the current peak or trough to the tip or base
            height = heights[i];
        }
    }
    return count >> 1;
}


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

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

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

Task

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

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

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

Input

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

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

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

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

Output

Output has to be written to STDOUT or closest alternative.

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

The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation.

Additional rules

This is not about finding the language with the shortest approach for prime testing, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted.

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

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

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

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

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

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

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

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

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
UGL, 26 bytes

```<code>id?u:cuul^^/_c=?_=ocd$:_u:
</code>```

Try it online!

How it works:

```<code>id?u:cuul^^/_c=?_=ocd$:_u:
id?u:                       int i = input(); if i==1: i=0;
     cuu                    int test = 2;
        l              _u:  while test != -1:
         ^^/_c=?                if i % test == 0:
                _=o                 print(i==test);
                   cd$              test = -1;
</code>```

Title: Is this number a prime?

Body:
UGL, 26 bytes

id?u:cuul^^/_c=?_=ocd$:_u:

Try it online!

How it works:

id?u:cuul^^/_c=?_=ocd$:_u:
id?u:                       int i = input(); if i==1: i=0;
     cuu                    int test = 2;
        l              _u:  while test != -1:
         ^^/_c=?                if i % test == 0:
                _=o                 print(i==test);
                   cd$              test = -1;


答:
Python 2, 239 232 223 bytes

r=range
e=reduce
a=lambda*l:map(lambda x,y:(x or 0)+(y or 0),*l)
m=lambda p,q:[sum((p+k*[0])[i]*(q+k*[0])[k-i]for i in r(k+1))for k in r(len(p+q)-1)]
o=lambda f,g:e(a,[e(m,[[c]]+[g]*k)for k,c in enumerate(f)])
```

A 'proper' implementation that does not abuse bases. Least significant coefficient first.

a is polynomial addition, m is polynomial multiplication, and o is composition.

Title: Polynomialception

Body:
Given two polynomials f,g of arbitrary degree over the integers, your program/function should evaluate the first polynomial in the second polynomial. f(g(x)) (a.k.a. the composition (fog)(x) of the two polynomials)

Details

Builtins are allowed. You can assume any reasonable formatting as input/output, but the input and output format should match. E.g. formatting as a string

```<code>x^2+3x+5
</code>```

or as as list of coefficients:

```<code>[1,3,5] or alternatively [5,3,1]
</code>```

Furthermore the input polynomials can be assumed to be fully expanded, and the outputs are also expected to be fully expanded.

Examples

```<code>A(x) = x^2 + 3x + 5, B(y) = y+1
A(B(y)) = (y+1)^2 + 3(y+1) + 5 = y^2 + 5y + 9

A(x) = x^6 + x^2 + 1, B(y) = y^2 - y
A(B(y))= y^12 - 6y^11 + 15y^10 - 20y^9 + 15y^8 - 6y^7 + y^6 + y^4 - 2 y^3 + y^2 + 1

A(x) = 24x^3 - 144x^2 + 288x - 192, B(y) = y + 2
A(B(y)) = 24y^3

A(x) = 3x^4 - 36x^3 + 138x^2 - 180x + 27, B(y) = 2y + 3
A(B(y)) = 48y^4 - 96y^2
</code>```

Body:
Python 2, 239 232 223 bytes

r=range
e=reduce
a=lambda*l:map(lambda x,y:(x or 0)+(y or 0),*l)
m=lambda p,q:[sum((p+k*[0])[i]*(q+k*[0])[k-i]for i in r(k+1))for k in r(len(p+q)-1)]
o=lambda f,g:e(a,[e(m,[[c]]+[g]*k)for k,c in enumerate(f)])

A 'proper' implementation that does not abuse bases. Least significant coefficient first.

a is polynomial addition, m is polynomial multiplication, and o is composition.


答:
Java 7, <s>190</s> 184 bytes

```<code>String Z(int c){String m="";if(c==47)m+="|\n";else if(c>57)m+="|"+c;else while(c-->48)m+="| ";return m;}String C(String n){String m="";for(char x:n.toCharArray())m+=Z(x);return m+"|";}
</code>```

Detailed try online

```<code>public static String Z(char c)
{
    String m="";
    if(c=='/')m+="|\n";
    else if(c>'9')m+="|"+c;
    else while(c-->'0')m+="| ";
    return m;
}

public static String C(String n)
{
    String m="";
    for(char x:n.toCharArray())m+=Z(x);
    return m+"|";
}
</code>```

Body:
Java 7, <s>190</s> 184 bytes

String Z(int c){String m="";if(c==47)m+="|\n";else if(c>57)m+="|"+c;else while(c-->48)m+="| ";return m;}String C(String n){String m="";for(char x:n.toCharArray())m+=Z(x);return m+"|";}

Detailed try online

public static String Z(char c)
{
    String m="";
    if(c=='/')m+="|\n";
    else if(c>'9')m+="|"+c;
    else while(c-->'0')m+="| ";
    return m;
}

public static String C(String n)
{
    String m="";
    for(char x:n.toCharArray())m+=Z(x);
    return m+"|";
}


答:
Perl, <s>55</s> 51 bytes

Includes +2 for -pa

Same basic idea as my other Perl answer, finding partitions of an integer but with a completely different implementation. This version is shorter, but only because I don't have to special case a negative third argument.This version is also totally boring...

Give input for m(x,y,z) on STDIN with a line for each argument in order z, x, y. E.g. to calculate m(3,5,6):

```<code> mnomial.pl
 6
 3
 5
 ^D
</code>```

mnomial.pl:

```<code>#!/usr/bin/perl -pa
$"=",";$_=grep"@F"==eval,glob"+{@{[0..<>-1]}}"x<>
</code>```

Title: m-nomial coefficient

Body:
While the binomial coefficient are the coefficients of \$(1+x)^n\$, m-nomial coefficients are the coefficients of \$(1+x+x^2+...+x^{m-1})^n\$.

For example, \$m(3,5,6)\$ is the coefficient of \$x^6\$ in the expansion of \$(1+x+x^2)^5\$.

Write a program/function that takes 3 numbers as input and outputs the corresponding m-nomial coefficient.

Details

Input can be taken via any reasonable method.

Everything out of range is \$0\$, for example \$m(2,0,-1) = m(2,5,6) = 0\$

The first argument will be positive.

The second argument will not be negative.

All three arguments will be integers.

Testcases

Inputs:

```<code>[1,0,0]
[2,5,6]
[3,5,6]
[4,5,-1]
</code>```

Outputs:

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

Scoring

This is code-golf. Shortest solution in bytes wins.

Body:
Perl, <s>55</s> 51 bytes

Includes +2 for -pa

Same basic idea as my other Perl answer, finding partitions of an integer but with a completely different implementation. This version is shorter, but only because I don't have to special case a negative third argument.This version is also totally boring...

Give input for m(x,y,z) on STDIN with a line for each argument in order z, x, y. E.g. to calculate m(3,5,6):

 mnomial.pl
 6
 3
 5
 ^D

mnomial.pl:

#!/usr/bin/perl -pa
$"=",";$_=grep"@F"==eval,glob"+{@{[0..<>-1]}}"x<>


答:
JavaScript (ES6), 118 bytes

```<code>(m,n,k)=>[...Array(n)].reduce(a=>a.map(x=>t+=x,t=0),[...Array(m*n+1)].map((_,i)=>i%m?0:i?x=-x*(n+1-i/m)*m/i:x=1))[k]|0
</code>```

Works by calculating (xm-1)n/(x-1)n. (xm-1)n is calculated by the binomial theorem and the result is then repeatedly divided by x-1.

Edit: Saved 24 bytes by using a different binomial calculation. Saved 4 bytes by switching to reduce (yay!).

Title: m-nomial coefficient

Body:
JavaScript (ES6), 118 bytes

(m,n,k)=>[...Array(n)].reduce(a=>a.map(x=>t+=x,t=0),[...Array(m*n+1)].map((_,i)=>i%m?0:i?x=-x*(n+1-i/m)*m/i:x=1))[k]|0

Works by calculating (xm-1)n/(x-1)n. (xm-1)n is calculated by the binomial theorem and the result is then repeatedly divided by x-1.

Edit: Saved 24 bytes by using a different binomial calculation. Saved 4 bytes by switching to reduce (yay!).


Title: Create a Boolean parser (continued)

Body:
JavaScript (ES6) 116 bytes

edit thx @user81655 for 3 bytes saved and a bug found

s=>[...s].map(x=>x<2?v=m[x]:x<6?m=[,,m[1]+m[0],0+v,v+1,v+(1^v)][x]:x>6?v=o.pop()[v]:m=o.push(m)&&a,o=[v=a=m='01'])|v

Probably not the best approach, but no eval and no boolean operators, just truth tables.

Character used:

! -> 2

& -> 3

| -> 4

^ -> 5

( -> 6

) -> 7

Test

f=s=>[...s].map(x=>x<2?v=m[x]:x<6?m=[,,m[1]+m[0],0+v,v+1,v+(1^v)][x]:x>6?v=o.pop()[v]:m=o.push(m)&&a,o=[v=a=m='01'])|v

console.log=(...x)=>O.textContent+=x+'\n'

test=[ ["1^((1|0&0)^!(1&!0&1))",1]
// be more careful, step by step
,["0&0",0],["0&1",0],["1&0",0],["1&1",1]
,["0|0",0],["0|1",1],["1|0",1],["1|1",1]
,["0^0",0],["0^1",1],["1^0",1],["1^1",0]
,["0&!0",0],["0&!1",0],["1&!0",1],["1&!1",0]
,["0|!0",1],["0|!1",0],["1|!0",1],["1|!1",1]
,["0^!0",1],["0^!1",0],["1^!0",0],["1^!1",1]
,["!0&0",0],["!0&1",1],["!1&0",0],["!1&1",0]
,["!0|0",1],["!0|1",1],["!1|0",0],["!1|1",1]
,["!0^0",1],["!0^1",0],["!1^0",0],["!1^1",1]
// nand, nor
,["!(0&0)",1],["!(0&1)",1],["!(1&0)",1],["!(1&1)",0]
,["!(0|0)",1],["!(0|1)",0],["!(1|0)",0],["!(1|1)",0]
     ]

test.forEach(([x,check]) => {
  // remap operators (each one on its line, just to be clear)
  var t = x.replace(/!/g,"2")
  t = t.replace(/&/g,"3")
  t = t.replace(/\|/g,"4")
  t = t.replace(/\^/g,"5")
  t = t.replace(/\(/g,"6")
  t = t.replace(/\)/g,"7")
  r = f(t)
  console.log((r==check?'OK':'KO')+' '+x +' '+r)
})

<pre id=O></pre>


答:
Perl 6, 13 bytes

```<code>.say for 0..*
</code>```

Perl 6 has lazy/infinite arrays, so I'm abusing that to create an infinite range. This will never run out of memory.

Note: as explained >." rel="nofollow noreferrer">in the Perl 6 docs, (0..*)>>.say would print out of order.

Title: Count up forever

Body:
Write a program that counts up forever, starting from one.

Rules:

Your program must log to STDOUT or an acceptable alternative, if STDOUT is not available.

Your program must be a full, runnable program, and not a function or snippet.

Your program must output each number with a separating character in between (a newline, space, tab or comma), but this must be consistent for all numbers.

You may print the numbers in decimal, in unary or in base 256 where each digit is represented by a byte value.

Your program must count at least as far as 2128 (inclusive) without problems and without running out of memory on a reasonable desktop PC. In particular, this means if you're using unary, you cannot store a unary representation of the current number in memory.

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

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

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

Catalogue

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
Perl 6, 13 bytes

.say for 0..*

Perl 6 has lazy/infinite arrays, so I'm abusing that to create an infinite range. This will never run out of memory.

Note: as explained in the Perl 6 docs, (0..*)>>.say would print out of order.


答:
Labyrinth, 21 bytes

```<code>?
:
}()"{
{: *}{:*{%!
</code>```

Terminates with an error, with the error message going to STDERR.

Try it online!

Explanation

This uses the same approach based on Wilson's theorem as Sp3000's answer, but I managed to decompose his 3x3 loop into two 2x2 loops which is generally better for golfing Labyrinth.

Labyrinth primer:

Labyrinth has two stacks of arbitrary-precision integers, main and aux(iliary), which are initially filled with an (implicit) infinite amount of zeros.

The source code resembles a maze, where the instruction pointer (IP) follows corridors when it can (even around corners). The code starts at the first valid character in reading order, i.e. in the top left corner in this case. When the IP comes to any form of junction (i.e. several adjacent cells in addition to the one it came from), it will pick a direction based on the top of the main stack. The basic rules are: turn left when negative, keep going ahead when zero, turn right when positive. And when one of these is not possible because there's a wall, then the IP will take the opposite direction. The IP also turns around when hitting dead ends.

Now we can look at the code. The program starts with a short linear (vertical) bit:

```<code>?   Read input N as an integer and push onto main.
:   Duplicate N.
}   Move one copy over to aux.
</code>```

The IP is now at a junction, and in fact the small 2x2 block acts as a loop which is traversed in clockwise order:

```<code>(   Decrement N. If it hits zero, we exit the loop.
:   Duplicate N.
{}  Move a value over from aux and push it back. Together this does nothing.
</code>```

So this loop leaves all the numbers from N-1 down to 0 on the main stack. Now there's the single ), which increments that 0 back up to 1, such that all the non-zero numbers on top of the stack will multiply together to (N-1)! (including the special case of 0! == 1).

The next 2x2 block is a loop which performs this multiplication and its traversed in counter-clockwise order. The tricky part is that we need to check the value below the product to see if we're done, otherwise we'd end up losing the product by multiplying it with an implicit 0 below.

```<code>"   No-op, does nothing.
*   Multiply the top two values on main.
}   Move the product over to aux, exposing the value below. If that's zero,
    we exit the loop.
{   Pull the product back onto main for the next iteration.
</code>```

Now the main stack is empty and the aux stack contains (N-1)! on top of N. Time to wrap things up:

```<code>{   Pull (N-1)! over from aux.
:*  Duplicate and multiply, squaring the factorial.
{   Pull N over from aux.
%   Take modulo, computing (N-1)!^2 % N.
!   Output the result.
</code>```

Now the IP hits a dead end and has to turn around. The next thing it tries to execute is % but that would now attempt to compute 0 % 0 which terminates with a division-by-zero error.

Title: Is this number a prime?

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

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

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

Task

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

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

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

Input

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

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

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

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

Output

Output has to be written to STDOUT or closest alternative.

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

The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation.

Additional rules

This is not about finding the language with the shortest approach for prime testing, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted.

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

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

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

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

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

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

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

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

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
Labyrinth, 21 bytes

?
:
}()"{
{: *}{:*{%!

Terminates with an error, with the error message going to STDERR.

Try it online!

Explanation

This uses the same approach based on Wilson's theorem as Sp3000's answer, but I managed to decompose his 3x3 loop into two 2x2 loops which is generally better for golfing Labyrinth.

Labyrinth primer:

Labyrinth has two stacks of arbitrary-precision integers, main and aux(iliary), which are initially filled with an (implicit) infinite amount of zeros.

The source code resembles a maze, where the instruction pointer (IP) follows corridors when it can (even around corners). The code starts at the first valid character in reading order, i.e. in the top left corner in this case. When the IP comes to any form of junction (i.e. several adjacent cells in addition to the one it came from), it will pick a direction based on the top of the main stack. The basic rules are: turn left when negative, keep going ahead when zero, turn right when positive. And when one of these is not possible because there's a wall, then the IP will take the opposite direction. The IP also turns around when hitting dead ends.

Now we can look at the code. The program starts with a short linear (vertical) bit:

?   Read input N as an integer and push onto main.
:   Duplicate N.
}   Move one copy over to aux.

The IP is now at a junction, and in fact the small 2x2 block acts as a loop which is traversed in clockwise order:

(   Decrement N. If it hits zero, we exit the loop.
:   Duplicate N.
{}  Move a value over from aux and push it back. Together this does nothing.

So this loop leaves all the numbers from N-1 down to 0 on the main stack. Now there's the single ), which increments that 0 back up to 1, such that all the non-zero numbers on top of the stack will multiply together to (N-1)! (including the special case of 0! == 1).

The next 2x2 block is a loop which performs this multiplication and its traversed in counter-clockwise order. The tricky part is that we need to check the value below the product to see if we're done, otherwise we'd end up losing the product by multiplying it with an implicit 0 below.

"   No-op, does nothing.
*   Multiply the top two values on main.
}   Move the product over to aux, exposing the value below. If that's zero,
    we exit the loop.
{   Pull the product back onto main for the next iteration.

Now the main stack is empty and the aux stack contains (N-1)! on top of N. Time to wrap things up:

{   Pull (N-1)! over from aux.
:*  Duplicate and multiply, squaring the factorial.
{   Pull N over from aux.
%   Take modulo, computing (N-1)!^2 % N.
!   Output the result.

Now the IP hits a dead end and has to turn around. The next thing it tries to execute is % but that would now attempt to compute 0 % 0 which terminates with a division-by-zero error.


答:
Mathematica, <s>139</s> 129 bytes

```<code>a=StringPartition;StringReplace[#,{"(0)0&00&11&00|00^01^1"~a~3|"!1"->"0","(1)1&10|11|01|10^11^0"~a~3|"!0"->"1"},1]&~FixedPoint~#&
</code>```

A simple string-replacement solution scores far better than I hoped for.

Title: Create a Boolean parser (continued)

Body:
Continuation of this challenge because the author is gone and the question is closed.

What you need to do is create a Boolean parser.

Boolean expressions, in case you haven't heard of them yet, have two inputs and one output.

There are four "gates" in boolean arithmetic, namely:

OR (represented by |) (binary operator, between arguments)

AND (represented by &) (binary operator, between arguments)

XOR (represented by ^) (binary operator, between arguments)

NOT (represented by !) (unary operator, argument on right)

These gates operate on their inputs which are either true (represented by 1) or false (represented by 0). We can list the possible inputs (A and B in this case) and the outputs (O) using a truth table as follows:

```<code>XOR
A|B|O
-----
0|0|0
0|1|1
1|0|1
1|1|0

OR
A|B|O
-----
0|0|0
0|1|1
1|0|1
1|1|1

AND
A|B|O
-----
0|0|0
0|1|0
1|0|0
1|1|1

NOT
A|O
---
0|1
1|0
</code>```

An example input would be 1^((1|0&0)^!(1&!0&1)), which would evaluate to:

```<code> 1^((1|0&0)^!(1&!0&1))
=1^(( 1 &0)^!(1&!0&1))
=1^(   0   ^!(1&!0&1))
=1^(   0   ^!(1& 1&1))
=1^(   0   ^!(  1 &1))
=1^(   0   ^!    1   )
=1^(   0   ^    0    )
=1^0
=1
</code>```

The output would be 1.

Details

As seen in the example, there is no order of prevalence. All are evaluated from left to right, except when inside parentheses, which should be evaluated first.

The input will only contain ()!^&|01.

You can choose any 8-byte character to replace the 8 characters above, but they must have a 1-to-1 mapping and must be stated.

Specifically, the function eval is not allowed to be used on any string derived from the input. Specifically, the function input (or the equivalent in the language) and any function that calls it cannot be used by eval. You also cannot concatenate the input into your string inside the eval.

Scoring

This is code-golf. Shortest solution in bytes wins.

Body:
Mathematica, <s>139</s> 129 bytes

a=StringPartition;StringReplace[#,{"(0)0&00&11&00|00^01^1"~a~3|"!1"->"0","(1)1&10|11|01|10^11^0"~a~3|"!0"->"1"},1]&~FixedPoint~#&

A simple string-replacement solution scores far better than I hoped for.


答:
Haskell, 110 Bytes

```<code>p '/'="\n"
p c|'1'<=c&&c<='8'=replicate(read[c])' '
p c=[c]
main=getLine>>=putStrLn.('|':).(>>=(:"|")).(>>=p)
</code>```

Ungolfed:

```<code>p c | c=='/'           = "\n"
    | '1'<=c && c<='8' = replicate (read [c]) ' '
    | otherwise        = [c]
addPipes string = "|" ++ concatMap (\c -> [c] ++ "|") string
main = getLine >>= putStrLn . addPipes . concatMap p
</code>```

Body:
In chess, Forsyth-Edwards Notation, more commonly called "FEN", is a textual way of transcribing boards. It describes each of the board's eight rows (called "ranks" in chess) from top to bottom from White's perspective. The pieces are written as K (king), Q (queen), R (rook), B (bishop), N (knight), and P (pawn). Black pieces use these letters in lowercase, and white pieces use these letters in uppercase. Empty spaces are indicated by a number from 1 to 8 indicating how many consecutive empty spaces there are. A completely empty rank would be 8, a single black rook in the rightmost column (called "files" in chess) would be 7r, and two white pawns on each end of a row would be PP4PP. Ranks are separated by a /. There is normally other information added, indicating which side is to move, castling and en passant rights, move number, and halfmove clock, but we will ignore them for the purposes of this challenge.

Input

A FEN string, from the command line or STDIN, as you please. You may assume that this string is always valid.

Output

Write to STDOUT a simple ASCII art representation of the board as it would actually appear:

Pieces are represented by their character in FEN

Empty squares are represented by spaces

Pieces and squares are separated by a pipe | and there are pipes on each side of the board

So an empty board, written as 8/8/8/8/8/8/8/8 in FEN, would appear as

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

The starting position of a chess game is written as rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR, and would appear as

```<code>|r|n|b|q|k|b|n|r|
|p|p|p|p|p|p|p|p|
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
|P|P|P|P|P|P|P|P|
|R|N|B|Q|K|B|N|R|
</code>```

The final position of Anderssen-Kieseritzky 1851, called "The Immortal Game" in the chess community, is written as r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1, and your program when fed that input would output:

```<code>|r| |b|k| | | |r|
|p| | |p|B|p|N|p|
|n| | | | |n| | |
| |p| |N|P| | |P|
| | | | | | |P| |
| | | |P| | | | |
|P| |P| |K| | | |
|q| | | | | |b| |
</code>```

Body:
Haskell, 110 Bytes

p '/'="\n"
p c|'1'<=c&&c<='8'=replicate(read[c])' '
p c=[c]
main=getLine>>=putStrLn.('|':).(>>=(:"|")).(>>=p)

Ungolfed:

p c | c=='/'           = "\n"
    | '1'<=c && c<='8' = replicate (read [c]) ' '
    | otherwise        = [c]
addPipes string = "|" ++ concatMap (\c -> [c] ++ "|") string
main = getLine >>= putStrLn . addPipes . concatMap p