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

```

答:
Sesos, <s>28</s> 24 bytes

```<code>0000000: 1651b8 77cd1c 345e33 c67bbe c673b8 676c38 67fe98  .Q.w..4^3.{..s.gl8g..
0000015: 70e201
</code>```

Uses trial division. Try it online! Check Debug to see the generated binary code.

How it works

The binary file above has been generated by assembling the following SASM code.

set numin     ; Switch to numeric input.
set numout    ; Switch to numeric output.

get, sub 1    ; Read an integer n from STDIN and decrement it.
              ; If n is 1, this will leave a 0 in cell 0.
jmp           ; While loop entry point; if the cell is 0, skip the loop body.
    add 1     ; Add 1 to restore n.

    ; The following is the actual primality test. To see how it works, consult the
    ; corresponding section of this answer.

    jmp, rwd 1, add 1, fwd 2, add 1, rwd 1, sub 1, jnz
    fwd 1
    jmp
        sub 1, rwd 1
        jmp, fwd 1, add 1, rwd 1, sub 1, jnz
        rwd 1
        jmp
            fwd 1, add 1, fwd 1, sub 1, fwd 1, add 1, rwd 1
            jmp, fwd 1, jnz
            fwd 1
            jmp, rwd 1, add 1, fwd 1, sub 1, jnz
            rwd 2
            jmp, rwd 1, jnz
            fwd 1, sub 1
        jnz
        fwd 3
    jnz
    rwd 1, sub 1
    jmp, rwd 1, jnz

jnz           ; While loop exit marker; since the previous instruction also sets
              ; an exit marker, the current cell will be 0 and we exit the loop.
rwd 1, put    ; Retrocede to the previous cell and print its content to STDOUT.
              ; If n > 1, this will print the result from the primality test.
              ; If n = 1, it will simply print 0.
```

<h3>Modulus computation</h3>

<p>The core of this answer is its modulus algorithm, which is based on the divmod algorithm from Esolangs. Unlike the latter, it doesn't compute a quotient and works if the divisor is <strong>1</strong>.</p>

<p>Suppose the tape in in the following state, where <strong>n</strong> and <strong>d</strong> are positive integers.</p>

<pre class="lang-lisp prettyprint-override"><code>  v
  n     0     d     0     0     0
</code>```

To compute n % d, we will decrement the third cell n times. Each time we decrement it, we also increment the fourth cell (so their sum is d at all times), and swap their contents every time the third cell reaches 0.

We have to decrement the first cell once for each iteration, and stop once it reaches 0. Since this will destroy the content of the first cell, we'll also increment the second cell once for each iteration, effectively copying n to the second cell.

Once the first cell reaches 0, the tape will be in the following state.

  v
  0     n   d-n%d  n%d    0     0
```

<p>We achieve this as follows.</p>

<pre class="lang-lisp prettyprint-override"><code>jmp           ; While the first cell is non-zero:
    fwd 1     ;     Advance to the second cell.
    add 1     ;     Increment it.
    fwd 1     ;     Advance to the third cell.
    sub 1     ;     Decrement it.
    fwd 1     ;     Advance to the fourth cell.
    add 1     ;     Increment it.
    rwd 1     ;     Retrocede to the third cell.
    jmp       ;     While the current cell in non-zero.
        fwd 1 ;         Advance to the next cell.
    jnz       ;     This will advance to the fifth cell if the third is non-zero
              ;     and stay on the third cell otherwise.
    fwd 1     ;     Advance either to the fourth or sixth cell.
    jmp       ;     While the fourth/sixth cell is non-zero:
        rwd 1 ;         Retrocede to the third/fifth cell.
        add 1 ;         Increment it.
        fwd 1 ;         Advance to the fourth/sixth cell.
        sub 1 ;         Decrement it.
    jnz       ;     This will add the fourth/sixth cell to the third/fifth cell,
              ;     zeroing the former in the process. Since the sixth cell has a
              ;     value of 0, this loop is a no-op if the third cell in 0; other-
              ;     wise, it sets the third cell to d and the fourth cell to 0.
    rwd 2     ;     Retrocede to the second/fourth cell.
    jmp       ;     While the current cell is non-zero:
        rwd 1 ;         Retrocede to the previos cell.
    jnz       ;     This places the head to the left of the first cell.
    fwd 1     ;     Advance to the first cell.
    sub 1     ;     Decrement it.
jnz           ;
</code>```

Primality test (WIP)

For input n > 1, we can use the modulus algorithm from the previous section to implement a primality test by trial division.

If n is already on the tape, we procede as follows.

Create a copy of n and decrement it to leave the tape as

                  v
      n     0     d     0     0     0
```

<p>where <strong>d = n - 1</strong>.</p></li>
<li><p>Retrocede to <strong>n</strong> and use the modulus algorithm to compute <strong>n % d</strong>, leaving the tape as follows.</p>

<pre class="lang-lisp prettyprint-override"><code>      v
      0     n   d-n%d  n%d    0     0
</code>```

Advance to the cell containing n % d.

If n % d > 0, add d - n % d to n % d to restore d, decrement it, and go back to step 2.

If n % d = 0, we found the first divisor of n (1 for primes); go to step 4.

Since n % d = 0, d - n % d = d.

We retrocede to that cell, decrement it to leave d - 1 in it (0 if and only if n is prime), and retrocede until finding the first 0 cell. This leaves the tape as

             v            V
      0      0     n     d-1   0    0     0
```

where v marks the location of the tape head if d - 1 > 0, and V the location if **d - 1 = 0.

Note that the value of the cell under the tape head will be 0 in either case. The cell to the left will contain n if n is prime, and 0 if n is composite.

Title: Is this number a prime?

Body:
Sesos, <s>28</s> 24 bytes

0000000: 1651b8 77cd1c 345e33 c67bbe c673b8 676c38 67fe98  .Q.w..4^3.{..s.gl8g..
0000015: 70e201

Uses trial division. <a href="http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKCmdldCwgc3ViIDEKam1wCiAgICBhZGQgMQogICAgam1wLCByd2QgMSwgYWRkIDEsIGZ3ZCAyLCBhZGQgMSwgcndkIDEsIHN1YiAxLCBqbnoKICAgIGZ3ZCAxCiAgICBqbXAKICAgICAgICBzdWIgMSwgcndkIDEKICAgICAgICBqbXAsIGZ3ZCAxLCBhZGQgMSwgcndkIDEsIHN1YiAxLCBqbnoKICAgICAgICByd2QgMQogICAgICAgIGptcAogICAgICAgICAgICBmd2QgMSwgYWRkIDEsIGZ3ZCAxLCBzdWIgMSwgZndkIDEsIGFkZCAxLCByd2QgMQogICAgICAgICAgICBqbXAsIGZ3ZCAxLCBqbnoKICAgICAgICAgICAgZndkIDEKICAgICAgICAgICAgam1wLCByd2QgMSwgYWRkIDEsIGZ3ZCAxLCBzdWIgMSwgam56CiAgICAgICAgICAgIHJ3ZCAyCiAgICAgICAgICAgIGptcCwgcndkIDEsIGpuegogICAgICAgICAgICBmd2QgMSwgc3ViIDEKICAgICAgICBqbnoKICAgICAgICBmd2QgMwogICAgam56CiAgICByd2QgMSwgc3ViIDEKICAgIGptcCwgcndkIDEsIGpuegpqbnoKcndkIDEsIHB1dA&input=MjUx" rel="nofollow">Try it online! Check Debug to see the generated binary code.

How it works

The binary file above has been generated by assembling the following SASM code.

set numin     ; Switch to numeric input.
set numout    ; Switch to numeric output.

get, sub 1    ; Read an integer n from STDIN and decrement it.
              ; If n is 1, this will leave a 0 in cell 0.
jmp           ; While loop entry point; if the cell is 0, skip the loop body.
    add 1     ; Add 1 to restore n.

    ; The following is the actual primality test. To see how it works, consult the
    ; corresponding section of this answer.

    jmp, rwd 1, add 1, fwd 2, add 1, rwd 1, sub 1, jnz
    fwd 1
    jmp
        sub 1, rwd 1
        jmp, fwd 1, add 1, rwd 1, sub 1, jnz
        rwd 1
        jmp
            fwd 1, add 1, fwd 1, sub 1, fwd 1, add 1, rwd 1
            jmp, fwd 1, jnz
            fwd 1
            jmp, rwd 1, add 1, fwd 1, sub 1, jnz
            rwd 2
            jmp, rwd 1, jnz
            fwd 1, sub 1
        jnz
        fwd 3
    jnz
    rwd 1, sub 1
    jmp, rwd 1, jnz

jnz           ; While loop exit marker; since the previous instruction also sets
              ; an exit marker, the current cell will be 0 and we exit the loop.
rwd 1, put    ; Retrocede to the previous cell and print its content to STDOUT.
              ; If n > 1, this will print the result from the primality test.
              ; If n = 1, it will simply print 0.

Modulus computation

The core of this answer is its modulus algorithm, which is based on the divmod algorithm from Esolangs. Unlike the latter, it doesn't compute a quotient and works if the divisor is 1.

Suppose the tape in in the following state, where n and d are positive integers.

  v
  n     0     d     0     0     0

To compute n % d, we will decrement the third cell n times. Each time we decrement it, we also increment the fourth cell (so their sum is d at all times), and swap their contents every time the third cell reaches 0.

We have to decrement the first cell once for each iteration, and stop once it reaches 0. Since this will destroy the content of the first cell, we'll also increment the second cell once for each iteration, effectively copying n to the second cell.

Once the first cell reaches 0, the tape will be in the following state.

  v
  0     n   d-n%d  n%d    0     0

We achieve this as follows.

jmp           ; While the first cell is non-zero:
    fwd 1     ;     Advance to the second cell.
    add 1     ;     Increment it.
    fwd 1     ;     Advance to the third cell.
    sub 1     ;     Decrement it.
    fwd 1     ;     Advance to the fourth cell.
    add 1     ;     Increment it.
    rwd 1     ;     Retrocede to the third cell.
    jmp       ;     While the current cell in non-zero.
        fwd 1 ;         Advance to the next cell.
    jnz       ;     This will advance to the fifth cell if the third is non-zero
              ;     and stay on the third cell otherwise.
    fwd 1     ;     Advance either to the fourth or sixth cell.
    jmp       ;     While the fourth/sixth cell is non-zero:
        rwd 1 ;         Retrocede to the third/fifth cell.
        add 1 ;         Increment it.
        fwd 1 ;         Advance to the fourth/sixth cell.
        sub 1 ;         Decrement it.
    jnz       ;     This will add the fourth/sixth cell to the third/fifth cell,
              ;     zeroing the former in the process. Since the sixth cell has a
              ;     value of 0, this loop is a no-op if the third cell in 0; other-
              ;     wise, it sets the third cell to d and the fourth cell to 0.
    rwd 2     ;     Retrocede to the second/fourth cell.
    jmp       ;     While the current cell is non-zero:
        rwd 1 ;         Retrocede to the previos cell.
    jnz       ;     This places the head to the left of the first cell.
    fwd 1     ;     Advance to the first cell.
    sub 1     ;     Decrement it.
jnz           ;

Primality test (WIP)

For input n > 1, we can use the modulus algorithm from the previous section to implement a primality test by trial division.

If n is already on the tape, we procede as follows.

Create a copy of n and decrement it to leave the tape as

                  v
      n     0     d     0     0     0

where d = n - 1.

Retrocede to n and use the modulus algorithm to compute n % d, leaving the tape as follows.

      v
      0     n   d-n%d  n%d    0     0

Advance to the cell containing n % d.

If n % d > 0, add d - n % d to n % d to restore d, decrement it, and go back to step 2.

If n % d = 0, we found the first divisor of n (1 for primes); go to step 4.

Since n % d = 0, d - n % d = d.

We retrocede to that cell, decrement it to leave d - 1 in it (0 if and only if n is prime), and retrocede until finding the first 0 cell. This leaves the tape as

             v            V
      0      0     n     d-1   0    0     0

where v marks the location of the tape head if d - 1 > 0, and V the location if **d - 1 = 0.

Note that the value of the cell under the tape head will be 0 in either case. The cell to the left will contain n if n is prime, and 0 if n is composite.


问:
Generate a Stack Exchange Favicon
Do you recognize the PPCG logo?
it looks like this, when you do an ascii art of it.

```<code>+---+
|PCG|
+---+
   v
</code>```

Now, In this Code Golf, You will make a code, that makes logos for other sites, similar to the PPCG logo.

What You should do

The "Shortened" string will be the string, with all upper case letters and numbers in the input string.(Which would be PPCG when the input string is Programming Puzzles & Code Golf)

The "Box" (

```<code>+---+
|   |
+---+
   v
</code>```

)
should fit the Shortened string perfectly.(No bigger or smaller)

Also the v part should be exactly 1 down and 1 left to the down right +.

Then output the box which has the shortened string in it.

Example

Stack Overflow:

```<code>+--+
|SO|
+--+
  v
</code>```

Area 51:

```<code>+---+
|A51|
+---+
   v
</code>```

Rules

You may assume that the input contains at least one digit or upper case letter.

Standard code-golf rules apply.

ContentLicense: CC BY-SA 3.0

Title: Generate a Stack Exchange Favicon

Body:
CJam, 41

"||"q_'[,65>A,s+--*__"+-"er_@\_,((S*]N*'v

Try it online


问:
Detriplicate a string
A lot of languages have built-in ways to get rid of duplicates, or "deduplicate" or "uniquify" a list or string. A less common task is to "detriplicate" a string. That is, for every character that appears, the first two occurrences are kept.

Here is an example where the characters that should be deleted are labelled with ^:

```<code>aaabcbccdbabdcd
  ^    ^ ^^^ ^^
aabcbcdd
</code>```

Your task is to implement exactly this operation.

Rules

Input is a single, possibly empty, string. You may assume that it only contains lowercase letters in the ASCII range.

Output should be a single string with all characters removed which have already appeared at least twice in the string (so the left-most two occurrences are kept).

Instead of strings you may work with lists of characters (or singleton strings), but the format has to be consistent between input and output.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

Every pair of lines is one test case, input followed by output.

```<code>

xxxxx
xx
abcabc
abcabc
abcdabcaba
abcdabc
abacbadcba
abacbdc
aaabcbccdbabdcd
aabcbcdd
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates a leaderboard 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 + 3 (-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

```

答:
Jelly, 6 bytes

```<code>Qx2œ&@
</code>```

Try it online! or verify all test cases.

How it works

```<code>Qx2œ&@  Main link. Argument: s (string)

Q       Unique; deduplicate s.
 x2     Repeat each character.
   œ&@  Take the multiset intersection of s and the previous result.
</code>```

Title: Detriplicate a string

Body:
Jelly, 6 bytes

Qx2œ&@

Try it online! or verify all test cases.

How it works

Qx2œ&@  Main link. Argument: s (string)

Q       Unique; deduplicate s.
 x2     Repeat each character.
   œ&@  Take the multiset intersection of s and the previous result.


答:
Python 2, 51 bytes

f=lambda s:s and f(s[:-1])+s[-1]*(s.count(s[-1])<3)
```

Test it on Ideone.

Title: Detriplicate a string

Body:
A lot of languages have built-in ways to get rid of duplicates, or "deduplicate" or "uniquify" a list or string. A less common task is to "detriplicate" a string. That is, for every character that appears, the first two occurrences are kept.

Here is an example where the characters that should be deleted are labelled with ^:

```<code>aaabcbccdbabdcd
  ^    ^ ^^^ ^^
aabcbcdd
</code>```

Your task is to implement exactly this operation.

Rules

Input is a single, possibly empty, string. You may assume that it only contains lowercase letters in the ASCII range.

Output should be a single string with all characters removed which have already appeared at least twice in the string (so the left-most two occurrences are kept).

Instead of strings you may work with lists of characters (or singleton strings), but the format has to be consistent between input and output.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

Every pair of lines is one test case, input followed by output.

```<code>

xxxxx
xx
abcabc
abcabc
abcdabcaba
abcdabc
abacbadcba
abacbdc
aaabcbccdbabdcd
aabcbcdd
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates a leaderboard 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 + 3 (-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:
Python 2, 51 bytes

f=lambda s:s and f(s[:-1])+s[-1]*(s.count(s[-1])<3)

Test it on Ideone.


答:
Python 2, 48 bytes

lambda s:reduce(lambda r,c:r+c*(r.count(c)<2),s)
```
<p><code>c[r.count(c)/2:]</code> is a same-length alternative to <code>c*(r.count(c)<2)</code> .</p>
<hr />
<p><strong>49 bytes:</strong></p>
<pre class="lang-python prettyprint-override"><code>r=''
for c in input():r+=c*(r.count(c)<2)
print r
</code>```

Title: Detriplicate a string

Body:
Python 2, 48 bytes

lambda s:reduce(lambda r,c:r+c*(r.count(c)<2),s)

c[r.count(c)/2:] is a same-length alternative to c*(r.count(c)<2) .

49 bytes:

r=''
for c in input():r+=c*(r.count(c)<2)
print r


问:
Can Mario go to the end of this map
Create a program that determines, given an input of the path, whether Mario can reach the end, denoted by E, from the start, denoted by S.

A path will look something like this:

```<code>S = E
=====
</code>```

In a path, the various symbols and what they represent are:

=: wall/floor/ceiling. Mario cannot walk through wall , and cannot fall past a floor, or jump past a ceiling (he would hit his head)

  (space): air. Mario can walk through this, and jump through it, and fall through it

S: air, except showing where Mario starts. This will always appear in the left-most column of the input, at ground level.

E: air, except showing where Mario wants to get. This will always appear in the right-most column of the input, at ground level.

The input will have spaces at every place where Mario could walk.

Mario can only move forward; in this example Mario cannot get to the goal

```<code>S
===

 ===
   E
====
</code>```

nor can he in this one

```<code>    E
   ==
==
  #==
==
   ==
==
S  ==
======
</code>```

However, he can reach the space denoted by # (which will not appear in input), because he can jump up to four cells high; Mario is superhuman. As another example of his superhumanity:

```<code>S
=
=
=
=
=
= #
= =
=
=
=
=     E
=======
</code>```

Mario can get to the E by falling the great distance, surviving, and walking calmly to E. Note that he cannot reach the #, because Mario falls straight down.

Mario can jump really high, but not very far forward by comparison.

```<code>S   E
== ==
 = =
</code>```

Mario may attempt to jump the gap, but he will fail, and fall straight in. he cannot reach the end.

Mario can reach the goal in all of these examples:

```<code> E
 =
 =
 =
S=
==
</code>```

```<code> =
 =   E
S=   =
==   =
 =   =
 =====
</code>```

```<code>S
=

=  E
====
</code>```

This is code golf, so fewest bytes wins!

答:
Snails, <s>41</s> <s>37</s> 29 bytes

Thanks to feersum for some help with avoiding overlapping paths and for saving 4 bytes.

```<code>=\S(^=d=\=u\ ,4(r!\=d.),r),\E
</code>```

Requires input to be padded to a rectangle such that there are spaces in every cell Mario needs to traverse (potentially with a leading line full of spaces).

Try it online!

Explanation

Snails was feersum's entry to our 2D pattern matching language design challenge. Like Slip it's also similar to regex, but the major difference is that a) this one supports assertions (lookarounds) and b) aside from these assertions, it's not possible to traverse any cell in the grid twice. That makes this problem a bit tricky, since there are cases where Mario needs to fall into a hole and jump back out, e.g.:

```<code>S E
= =
===
</code>```

Apart from these differences, the syntax of the two languages also differs quite a lot.

To circumvent the issue that we can't traverse a cell twice, we always alternate a horizontal step with a vertical step. However, this means that we have need to handle a fall before we step over the ledge. So falls will technically actually go through ground tiles but we'll ensure that they only happen next to open space.

```<code>=\S        Ensure that the match starts on an S, without actually matching it.
(          This group matches zero or more steps to the right (with a potential
           vertical step after each one).
  ^=         Match a non-ground cell, stepping right (on the first iteration,
             there is no step yet, so this matches the S).
  d=\=       Ensure that there's a ground tile below, so that the step ends on
             a valid position.
  u\ ,4      Match 0 to 4 spaces going up. This the optional jump.
  (          This group matches zero or more steps down, if a fall is valid here.
    r!\=       Ensure that there is no ground-tile right of the current cell.
    d.         Take one step down onto any character.
  ),
  r          Reset the direction to right for the next iteration.
),
\E        Match the exit.
</code>```

Title: Can Mario go to the end of this map

Body:
Snails, <s>41</s> <s>37</s> 29 bytes

Thanks to feersum for some help with avoiding overlapping paths and for saving 4 bytes.

=\S(^=d=\=u\ ,4(r!\=d.),r),\E

Requires input to be padded to a rectangle such that there are spaces in every cell Mario needs to traverse (potentially with a leading line full of spaces).

Try it online!

Explanation

Snails was feersum's entry to our 2D pattern matching language design challenge. Like Slip it's also similar to regex, but the major difference is that a) this one supports assertions (lookarounds) and b) aside from these assertions, it's not possible to traverse any cell in the grid twice. That makes this problem a bit tricky, since there are cases where Mario needs to fall into a hole and jump back out, e.g.:

S E
= =
===

Apart from these differences, the syntax of the two languages also differs quite a lot.

To circumvent the issue that we can't traverse a cell twice, we always alternate a horizontal step with a vertical step. However, this means that we have need to handle a fall before we step over the ledge. So falls will technically actually go through ground tiles but we'll ensure that they only happen next to open space.

=\S        Ensure that the match starts on an S, without actually matching it.
(          This group matches zero or more steps to the right (with a potential
           vertical step after each one).
  ^=         Match a non-ground cell, stepping right (on the first iteration,
             there is no step yet, so this matches the S).
  d=\=       Ensure that there's a ground tile below, so that the step ends on
             a valid position.
  u\ ,4      Match 0 to 4 spaces going up. This the optional jump.
  (          This group matches zero or more steps down, if a fall is valid here.
    r!\=       Ensure that there is no ground-tile right of the current cell.
    d.         Take one step down onto any character.
  ),
  r          Reset the direction to right for the next iteration.
),
\E        Match the exit.


答:
Brachylog, 25 bytes

```<code>.v|s.g:.z:1a
:2fl<3
he~t?
</code>```

Try it online! or verify all test cases.

Explanation

This works because s - Subset will unify with bigger subsets first, thus e.g. for "aaa" it will try "aa" before "a".

Main predicate:

```<code>  .v         input = Output = ""
|          Or
  s.         Output is an ordered subset of the input
  g:.z       Zip each character of the output with the output itself
  :1a        Apply predicate 1 on each element of the zip
</code>```

Predicate 1: Check that all characters only appear at most twice. Input = [String:Char]

```<code>:2f        Find all valid outputs of predicate 2 (i.e. one output per occurence
               of the char)
l<3        There are less than 3 occurences
</code>```

Predicate 2: Get an occurence of a character. Input = [String:Char]

```<code>he         Take a character of the string in the input
  ~t?      That character is the char of the input
</code>```

Title: Detriplicate a string

Body:
Brachylog, 25 bytes

.v|s.g:.z:1a
:2fl<3
he~t?

Try it online! or verify all test cases.

Explanation

This works because s - Subset will unify with bigger subsets first, thus e.g. for "aaa" it will try "aa" before "a".

Main predicate:

  .v         input = Output = ""
|          Or
  s.         Output is an ordered subset of the input
  g:.z       Zip each character of the output with the output itself
  :1a        Apply predicate 1 on each element of the zip

Predicate 1: Check that all characters only appear at most twice. Input = [String:Char]

:2f        Find all valid outputs of predicate 2 (i.e. one output per occurence
               of the char)
l<3        There are less than 3 occurences

Predicate 2: Get an occurence of a character. Input = [String:Char]

he         Take a character of the string in the input
  ~t?      That character is the char of the input


问:
Interquartile Mean

Task

Given (by any means) a sorted floating point dataset, return (by any means and within 1‰ of the correct value) the interquartile mean.

One possible algorithm

Discard the lowest and highest quarters of the data points.

Calculate the average (sum divided by count) of the remaining data points.

Note: If the dataset size is not evenly split-able in four, you will have to weigh the datapoints that are shared by sub-sets. See Example evaluation 2 below.

Example evaluation 1

Given {1, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 38}

Data count is 12, so we remove lowest and highest 3 datapoints:
{<s>1, 3, 4,</s> 5, 6, 6, 7, 7, 8, <s>8, 9, 38</s>}

Average of the remaining 6 datapoints:
(5 + 6 + 6 + 7 + 7 + 8) / 6 = 6.5

Example evaluation 2

Given {1, 3, 5, 7, 9, 11, 13, 15, 17}

Count is 9, so each quarter has 2¼ datapoints:
{<s>1, 2, (0.25×5),</s> (0.75×5), 7, 9, 11, (0.75×13), <s>(0.25×13), 15, 17</s>}

Average of the remaining 4.5 datapoints:
(0.75×5 + 7 + 9 + 11 + 0.75×13) / 4.5 = 9

答:
Actually, 12 bytes

```<code>4α;l¼≈;±(Htæ
</code>```

Try it online! (currently doesn't work because TIO is a few versions behind)

Explanation:

```<code>4α;l¼≈;±(Htæ
4α            repeat each element 4 times
  ;l¼≈        length divided by 4, as integer
      ;±      copy, unary negate
        (Ht   remove first and last quartiles
           æ  mean
</code>```

Title: Interquartile Mean

Body:
Actually, 12 bytes

4α;l¼≈;±(Htæ

Try it online! (currently doesn't work because TIO is a few versions behind)

Explanation:

4α;l¼≈;±(Htæ
4α            repeat each element 4 times
  ;l¼≈        length divided by 4, as integer
      ;±      copy, unary negate
        (Ht   remove first and last quartiles
           æ  mean


问:
Print 1 to 1000 in C++ without semi-colons
Following this popular question, present your solution which prints the numbers 1 to 1000 (all of them, not the string "1 to 1000" verbatim or something funny) in C++ without using any semi-colons. Unlike the original question, you may use conditionals and loops.

Solutions not requiring any compiler flags are preferred. Please mention any you use if you go against this. Undefined behaviour is allowed, so please specify the compiler and version you're using. Preference will be given to clever solutions. This is not a shortest code contest.

(I have a solution, which I'll post in 24 hours if a similar solution isn't posted before then.)

答:
The semicolon is not needed if you know the magic word. And no need to go obfuscated.

My solution has the additional fanciness that it doesn't use any comma either ;)

```<code>#include <iostream>
#define Please(x) if (x) {}

int Number(int x)
{
    if (x > 1)
        Please(Number(x-1))
    Please(std::cout << " " << x)
}

int main()
{
    Please(Number(1000))
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The semicolon is not needed if you know the magic word. And no need to go obfuscated.

My solution has the additional fanciness that it doesn't use any comma either ;)

#include <iostream>
#define Please(x) if (x) {}

int Number(int x)
{
    if (x > 1)
        Please(Number(x-1))
    Please(std::cout << " " << x)
}

int main()
{
    Please(Number(1000))
}


答:
Pyke, 16 bytes

```<code>F~kR/2<Ii?+k(K~k
</code>```

Try it here!

Title: Detriplicate a string

Body:
Pyke, 16 bytes

F~kR/2<Ii?+k(K~k

Try it here!


答:
><>, 22 bytes

```<code>i:0(?;::9g:}2(?o{1+$9p
</code>```

Try it online! Uses the codebox to keep track of counts so far.

```<code>i                       Read a char c of input
 :0(?;                  Halt if EOF
      :                 Make a copy - stack has [c c] at the top
       :9g              Get count stored at (c, 9)
          :}            Copy the count and move to bottom of stack
            2(?o        If the count is less than 2, output c
                {1+     Move the count back to the top of the stack and increment
                   $9p  Update cell at (c, 9)
                        [Instruction pointer moves to start as ><> is toroidal]
</code>```

Title: Detriplicate a string

Body:
><>, 22 bytes

i:0(?;::9g:}2(?o{1+$9p

Try it online! Uses the codebox to keep track of counts so far.

i                       Read a char c of input
 :0(?;                  Halt if EOF
      :                 Make a copy - stack has [c c] at the top
       :9g              Get count stored at (c, 9)
          :}            Copy the count and move to bottom of stack
            2(?o        If the count is less than 2, output c
                {1+     Move the count back to the top of the stack and increment
                   $9p  Update cell at (c, 9)
                        [Instruction pointer moves to start as ><> is toroidal]


答:
JavaScript (ES6), 42 <s>48</s>

Edit A whopping 6 bytes saved thx @Neil

s=>s.replace(k=/./g,c=>(k[c]+=c)[11]?'':c)
```
<p>Explanation: I use the properties 'a'...'z' of object <code>k</code> to store info for each character (object k is a regexp in this case just to save bytes).
These properties are initially <code>undefined</code>. In javascript adding a number to <code>undefined</code> gives <code>NaN</code> (quite sensible), but adding a string 'X' gives <code>"undefinedX"</code> - a string of length 10 (silly). Adding more characters you get longer strings. If the obtained string for a given character is longer than 11, that character is not copied to output.</p>
<p><strong>Test</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>F=
s=>s.replace(k=/./g,c=>(k[c]+=c)[11]?'':c)

test=`

xxxxx
xx
abcabc
abcabc
abcdabcaba
abcdabc
abacbadcba
abacbdc
aaabcbccdbabdcd
aabcbcdd`.split`\n`
for(i=0;i<test.length;)
  a=test[i++],b=test[i++],r=F(a),
  console.log(r==b?'OK':'KO',a,'->',r,b)</code>```

Title: Detriplicate a string

Body:
JavaScript (ES6), 42 <s>48</s>

Edit A whopping 6 bytes saved thx @Neil

s=>s.replace(k=/./g,c=>(k[c]+=c)[11]?'':c)

Explanation: I use the properties 'a'...'z' of object k to store info for each character (object k is a regexp in this case just to save bytes).
These properties are initially undefined. In javascript adding a number to undefined gives NaN (quite sensible), but adding a string 'X' gives "undefinedX" - a string of length 10 (silly). Adding more characters you get longer strings. If the obtained string for a given character is longer than 11, that character is not copied to output.

Test

F=
s=>s.replace(k=/./g,c=>(k[c]+=c)[11]?'':c)

test=`

xxxxx
xx
abcabc
abcabc
abcdabcaba
abcdabc
abacbadcba
abacbdc
aaabcbccdbabdcd
aabcbcdd`.split`\n`
for(i=0;i<test.length;)
  a=test[i++],b=test[i++],r=F(a),
  console.log(r==b?'OK':'KO',a,'->',r,b)


答:
Mathematica, 51 bytes

```<code>Mean@#[[(l=1+Length@#/4);;-l]]&@Sort@Join[#,#,#,#]&
</code>```

Sorts four copies of the list (to prevent issues with list length not multiples of four), takes part "1 quarter the length of resulting list plus 1" through to the "1/4 length list + 1 from the end", takes their Mean.

Title: Interquartile Mean

Body:
Task

Given (by any means) a sorted floating point dataset, return (by any means and within 1‰ of the correct value) the interquartile mean.

One possible algorithm

Discard the lowest and highest quarters of the data points.

Calculate the average (sum divided by count) of the remaining data points.

Note: If the dataset size is not evenly split-able in four, you will have to weigh the datapoints that are shared by sub-sets. See Example evaluation 2 below.

Example evaluation 1

Given {1, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 38}

Data count is 12, so we remove lowest and highest 3 datapoints:
{<s>1, 3, 4,</s> 5, 6, 6, 7, 7, 8, <s>8, 9, 38</s>}

Average of the remaining 6 datapoints:
(5 + 6 + 6 + 7 + 7 + 8) / 6 = 6.5

Example evaluation 2

Given {1, 3, 5, 7, 9, 11, 13, 15, 17}

Count is 9, so each quarter has 2¼ datapoints:
{<s>1, 2, (0.25×5),</s> (0.75×5), 7, 9, 11, (0.75×13), <s>(0.25×13), 15, 17</s>}

Average of the remaining 4.5 datapoints:
(0.75×5 + 7 + 9 + 11 + 0.75×13) / 4.5 = 9

Body:
Mathematica, 51 bytes

Mean@#[[(l=1+Length@#/4);;-l]]&@Sort@Join[#,#,#,#]&

Sorts four copies of the list (to prevent issues with list length not multiples of four), takes part "1 quarter the length of resulting list plus 1" through to the "1/4 length list + 1 from the end", takes their Mean.


问:
Theoretically output Graham's number
Graham's number G is defined in this way:

```<code>u(3,n,1) = 3^n
u(3,1,m) = 3
u(3,n,m) = u(3,u(3,n-1,m),m-1)
[Knuth's up-arrow notation]
[Conway chained arrow notation]

THEN

g1 = u(3,3,4)
g2 = u(3,3,g1)
g3 = u(3,3,g2)
...
G = u(3,3,g63)
</code>```

You are given that u(3,3,2)=7625597484987 to check your code.

Your task is to write a program/function that will output the value of G deterministically, given enough integer size and enough time.

References

Graham's number

Knuth's up-arrow notation

Conway chained arrow notation

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
PHP, 114 bytes

ignore the line breaks; they are for readability only.

```<code>function u($n,$m){return$m>1&$n>1?u(u($n-1,$m),$m-1):3**$n;}
function g($x){return u(3,$x>1?g($x-1):4);}
echo g(63);
</code>```

It is possible to integrate the second case into the first one: for n=1, 3^n equals 3.

This will save a few bytes on - as far as I can see - all existing answers; saved two bytes on my

previous version, 62+43+11=116 bytes

```<code>function u($n,$m){return$m>1?$n>1?u(u($n-1,$m),$m-1):3:3**$n;}
</code>```

PHP´s left associativity of the ternary requires parentheses ... or a specific order of tests.

This saved two bytes on the parenthesized expression.

There is probably an iterative approach, which may allow further golfing ...

but I can´t take the time for it now.

Title: Theoretically output Graham's number

Body:
PHP, 114 bytes

ignore the line breaks; they are for readability only.

function u($n,$m){return$m>1&$n>1?u(u($n-1,$m),$m-1):3**$n;}
function g($x){return u(3,$x>1?g($x-1):4);}
echo g(63);

It is possible to integrate the second case into the first one: for n=1, 3^n equals 3.

This will save a few bytes on - as far as I can see - all existing answers; saved two bytes on my

previous version, 62+43+11=116 bytes

function u($n,$m){return$m>1?$n>1?u(u($n-1,$m),$m-1):3:3**$n;}

PHP´s left associativity of the ternary requires parentheses ... or a specific order of tests.

This saved two bytes on the parenthesized expression.

There is probably an iterative approach, which may allow further golfing ...

but I can´t take the time for it now.


问:
Divisibility test

Task

Given two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

The output should be a truthy or a falsy value; truthy if n is divisible by d, and falsy otherwise.

Your code only has to handle integers it can represent natively, as long as it works for all signed 8-bit integers. However, your algorithm has to work for arbitrarily large integers.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test cases

```<code> n,  d    output

 1,  1    truthy
 2,  1    truthy
 6,  3    truthy
17, 17    truthy
22,  2    truthy
 1,  2    falsy
 2,  3    falsy
 2,  4    falsy
 3,  9    falsy
15, 16    falsy
</code>```

Leaderboard

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 + 3 (-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

```

答:
Magma, 13 bytes

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

Pretty readable, I think. Try it at the online calculator, e.g.

```<code>IsDivisibleBy(100, 50);
IsDivisibleBy(100, 54);
</code>```

gives

```<code>true
false
</code>```

Title: Divisibility test

Body:
Magma, 13 bytes

IsDivisibleBy

Pretty readable, I think. Try it at the online calculator, e.g.

IsDivisibleBy(100, 50);
IsDivisibleBy(100, 54);

gives

true
false


答:
TCC, <s>5</s> 4 bytes

```<code>$~;2
</code>```

Try it online!

```<code>     | Print (implicit)
$~   | Limit char occurence
     | of input (assumed if not given)
  ;  | seperator
   2 | to 2
</code>```

Title: Detriplicate a string

Body:
TCC, <s>5</s> 4 bytes

$~;2

Try it online!

     | Print (implicit)
$~   | Limit char occurence
     | of input (assumed if not given)
  ;  | seperator
   2 | to 2


答:
Retina, 17 bytes

```<code>(.)(?<=\1.*\1.+)

</code>```

Try it online!

Simple regex replace - match a character if it already appeared twice, and remove it.

Title: Detriplicate a string

Body:
Retina, 17 bytes

(.)(?<=\1.*\1.+)

Try it online!

Simple regex replace - match a character if it already appeared twice, and remove it.


问:
Gear Train, Rotating
Gears transfer different amount of speeds, depending on the size of the meshed gear.

Jack has a machine, that rotates a Gear Train. but you don't know the speed of the last gear.

Luckily, You are a great code golfer, so you can help him!

So, What should I do?

Each gear is represented by 2 numbers, the radius of the inner gear and the radius of the outer gears.

If gear A is [a,b] and gear B is [c,d], then the ratio between the speed of A and the speed of B would be c:b.

Given a list of gears (list of 2-tuples), output the speed of the last gear.

You can assume the speed of the first gear is 1.

Worked out example

Let's say our input is [[6,12],[3,10],[5,8]].

The first gear, [6,12], would have a speed of 1.

Then, the second gear, [3,10], would have a speed of 1*12/3 = 4.

Then, the last gear, [5,8], would have a speed of 4*10/5 = 8.

Testcases

```<code>input                    output
[[1,1],[2,2]]            0.5     (1/2)
[[1,2],[1,2],[1,2]]      4       (2/1*2/1)
[[6,12],[3,10],[5,8]]    8       (12/3*10/5)
</code>```

Rules

Basic code-golf rules apply.

答:
Pascal (FPC), 94 bytes

A recursive (had to do it..) function that takes a static 2D array and its length (no. of rows) as an input. Using some pointer math on the array.

function r(a:pdouble;n:integer):double;begin r:=a[1]/a[2];if n=2then exit;r:=r*r(a+2,n-1);end;
```
<p>Try it online!</p>
<p>Ungolfed:</p>

<pre class="lang-pascal prettyprint-override"><code>function ratio(a: pdouble; n: integer): double;
begin
  ratio := a[1] / a[2];
  if n=2 then
    Exit;
  ratio := ratio * ratio(a+2, n-1);
end;
</code>```

Title: Gear Train, Rotating

Body:
Pascal (FPC), 94 bytes

A recursive (had to do it..) function that takes a static 2D array and its length (no. of rows) as an input. Using some pointer math on the array.

function r(a:pdouble;n:integer):double;begin r:=a[1]/a[2];if n=2then exit;r:=r*r(a+2,n-1);end;

Try it online!

Ungolfed:

function ratio(a: pdouble; n: integer): double;
begin
  ratio := a[1] / a[2];
  if n=2 then
    Exit;
  ratio := ratio * ratio(a+2, n-1);
end;

ContentLicense: CC BY-SA 4.0


问:
Determine number of connected components
You are given a graph represented through an adjacency list. For example, the input

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

would correspond to the graph with nodes 1, 2, 3 and 4, where 1 is connected to 2, 2 is connected to 3, 3 is connected to 4, and 4 is connected to 1 (forming a square).

The task is to determine the number of of connected components of the graph represented by an inputted adjacency list. A "connected component" is a set of nodes from which there is no path to any other node that is not in the set.

Example:

Intput: 1-2 2-3 4-5

  Output: 2

Language of your choice - shortest code possible.

答:
Mathematica 126

With x holding the input string,

```<code>t = ToExpression;
Length@ConnectedComponents@Graph[Characters /@ ImportString[x, "Table"][[1]] /.
{a_, "-", b_} :>   UndirectedEdge[t@a, t@b]]
</code>```

If x is input instead as a list of undirected edges, in standard Mathematica format, the solution can be reduced to 34 chars:

```<code>Length@ConnectedComponents@Graph@i
</code>```

Example:

Body:
Mathematica 126

With x holding the input string,

t = ToExpression;
Length@ConnectedComponents@Graph[Characters /@ ImportString[x, "Table"][[1]] /.
{a_, "-", b_} :>   UndirectedEdge[t@a, t@b]]

If x is input instead as a list of undirected edges, in standard Mathematica format, the solution can be reduced to 34 chars:

Length@ConnectedComponents@Graph@i

Example:


答:
MATL, 8 bytes

```<code>t&=Rs3<)
</code>```

Try it online!

Explanation

```<code>t      % Input string implicitly. Push another copy
&=     % Matrix of all pairwise equality comparisons of string elements
R      % Keep only upper triangular part, making the rest of the entries zero
s      % Sum of each column. This gives a vector with number of occurrences
       % of the current character up to the current position
3<     % True for entries that are less than 3
)      % Use as logical index into initial copy of the input. Display implicitly
</code>```

Example

Assuming input 'aaababbc', the stack contains the following after the indicated statements:

t

```<code>'aaababbc'
'aaababbc'
</code>```

t&=

```<code>'aaababbc'
[ 1 1 1 0 1 0 0 0;
  1 1 1 0 1 0 0 0;
  1 1 1 0 1 0 0 0;
  0 0 0 1 0 1 1 0;
  1 1 1 0 1 0 0 0;
  0 0 0 1 0 1 1 0;
  0 0 0 1 0 1 1 0;
  0 0 0 0 0 0 0 1 ]
</code>```

t&=R

```<code>'aaababbc'
[ 1 1 1 0 1 0 0 0;
  0 1 1 0 1 0 0 0;
  0 0 1 0 1 0 0 0;
  0 0 0 1 0 1 1 0;
  0 0 0 0 1 0 0 0;
  0 0 0 0 0 1 1 0;
  0 0 0 0 0 0 1 0;
  0 0 0 0 0 0 0 1 ]
</code>```

t&=Rs

```<code>'aaababbc'
[ 1 2 3 1 4 2 3 1 ]
</code>```

t&=Rs3<

```<code>'aaababbc'
[ true true false true false true false true ]
</code>```

t&=Rs3<)

```<code>'aabbc'
</code>```

Title: Detriplicate a string

Body:
A lot of languages have built-in ways to get rid of duplicates, or "deduplicate" or "uniquify" a list or string. A less common task is to "detriplicate" a string. That is, for every character that appears, the first two occurrences are kept.

Here is an example where the characters that should be deleted are labelled with ^:

```<code>aaabcbccdbabdcd
  ^    ^ ^^^ ^^
aabcbcdd
</code>```

Your task is to implement exactly this operation.

Rules

Input is a single, possibly empty, string. You may assume that it only contains lowercase letters in the ASCII range.

Output should be a single string with all characters removed which have already appeared at least twice in the string (so the left-most two occurrences are kept).

Instead of strings you may work with lists of characters (or singleton strings), but the format has to be consistent between input and output.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

Every pair of lines is one test case, input followed by output.

```<code>

xxxxx
xx
abcabc
abcabc
abcdabcaba
abcdabc
abacbadcba
abacbdc
aaabcbccdbabdcd
aabcbcdd
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates a leaderboard 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 + 3 (-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:
MATL, 8 bytes

t&=Rs3<)

Try it online!

Explanation

t      % Input string implicitly. Push another copy
&=     % Matrix of all pairwise equality comparisons of string elements
R      % Keep only upper triangular part, making the rest of the entries zero
s      % Sum of each column. This gives a vector with number of occurrences
       % of the current character up to the current position
3<     % True for entries that are less than 3
)      % Use as logical index into initial copy of the input. Display implicitly

Example

Assuming input 'aaababbc', the stack contains the following after the indicated statements:

t

'aaababbc'
'aaababbc'

t&=

'aaababbc'
[ 1 1 1 0 1 0 0 0;
  1 1 1 0 1 0 0 0;
  1 1 1 0 1 0 0 0;
  0 0 0 1 0 1 1 0;
  1 1 1 0 1 0 0 0;
  0 0 0 1 0 1 1 0;
  0 0 0 1 0 1 1 0;
  0 0 0 0 0 0 0 1 ]

t&=R

'aaababbc'
[ 1 1 1 0 1 0 0 0;
  0 1 1 0 1 0 0 0;
  0 0 1 0 1 0 0 0;
  0 0 0 1 0 1 1 0;
  0 0 0 0 1 0 0 0;
  0 0 0 0 0 1 1 0;
  0 0 0 0 0 0 1 0;
  0 0 0 0 0 0 0 1 ]

t&=Rs

'aaababbc'
[ 1 2 3 1 4 2 3 1 ]

t&=Rs3<

'aaababbc'
[ true true false true false true false true ]

t&=Rs3<)

'aabbc'


答:
Perl, 22 bytes

21 bytes code + 1 for -p.

s/./$&x(2>${$&}++)/ge
```

<h3>Usage</h3>

<pre class="lang-sh prettyprint-override"><code>perl -pe 's/./$&x(2>${$&}++)/ge' <<< 'aaabcbccdbabdcd'
aabcbcdd
</code>```

Title: Detriplicate a string

Body:
Perl, 22 bytes

21 bytes code + 1 for -p.

s/./$&x(2>${$&}++)/ge

Usage

perl -pe 's/./$&x(2>${$&}++)/ge' <<< 'aaabcbccdbabdcd'
aabcbcdd


答:
Actually, 14 bytes

```<code>pXdX2@╪k`i/`Mπ
</code>```

Try it online! (currently not working because TIO is a few versions behind)

This program takes a flattened list as input.

Explanation:

```<code>pXdX2@╪k`i/`Mπ
pXdX            remove the first and last elements
    2@╪k        push a list where each element is a list containing every two elements of the original list (chunk into length-2 lists)
        `i/`M   map division over each sublist
             π  product
</code>```

Title: Gear Train, Rotating

Body:
Gears transfer different amount of speeds, depending on the size of the meshed gear.

Jack has a machine, that rotates a Gear Train. but you don't know the speed of the last gear.

Luckily, You are a great code golfer, so you can help him!

So, What should I do?

Each gear is represented by 2 numbers, the radius of the inner gear and the radius of the outer gears.

If gear A is [a,b] and gear B is [c,d], then the ratio between the speed of A and the speed of B would be c:b.

Given a list of gears (list of 2-tuples), output the speed of the last gear.

You can assume the speed of the first gear is 1.

Worked out example

Let's say our input is [[6,12],[3,10],[5,8]].

The first gear, [6,12], would have a speed of 1.

Then, the second gear, [3,10], would have a speed of 1*12/3 = 4.

Then, the last gear, [5,8], would have a speed of 4*10/5 = 8.

Testcases

```<code>input                    output
[[1,1],[2,2]]            0.5     (1/2)
[[1,2],[1,2],[1,2]]      4       (2/1*2/1)
[[6,12],[3,10],[5,8]]    8       (12/3*10/5)
</code>```

Rules

Basic code-golf rules apply.

Body:
Actually, 14 bytes

pXdX2@╪k`i/`Mπ

Try it online! (currently not working because TIO is a few versions behind)

This program takes a flattened list as input.

Explanation:

pXdX2@╪k`i/`Mπ
pXdX            remove the first and last elements
    2@╪k        push a list where each element is a list containing every two elements of the original list (chunk into length-2 lists)
        `i/`M   map division over each sublist
             π  product


问:
Add two numbers
Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is code-golf, answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

```<code>1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17
</code>```

Or as CSV:

```<code>a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17
</code>```

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
GAP, 2 Bytes

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

The backslash is GAP's way to turn an infix operator (and some more, there is also \[\] for indexing) to a function.

Here is an example use:

```<code>gap> \+(4,3);
7
</code>```

Title: Add two numbers

Body:
GAP, 2 Bytes

\+

The backslash is GAP's way to turn an infix operator (and some more, there is also \[\] for indexing) to a function.

Here is an example use:

gap> \+(4,3);
7


问:
Collect and place items
The goal of this challenge is to collect selected items in a list and move them to a certain location in the list.

As a visual example, take the input values (represented by black boxed integers) and a corresponding list of truthy values where true denotes the item is selected (represented by blue boxes, where T is truthy and F is falsy):

The first logical step is to separate the items marked truthy and not truthy into their corresponding lists. Note that relative order in each list must be maintained (i.e. the order of selected items must be 1,4,5, and the order of unselected items must be 2,3,6,7)!

The second logical step is given an index in the remaining list of unselected items, insert all selected items before the item at the given index. Assuming indexing starts at 0, suppose you want to insert the selection at index 3. This corresponds to the spot before the 7 box, so the selected items should be inserted before the 7.

The final solution is then 2,3,6,1,4,5,7.

Note that this logical diagram depicts one way this could be done; your program does not need to take the same logical steps as long as the output always produces the same observable result.

Input

Your program is given 3 inputs:

A list of integers representing the items. This may be an empty list. This list will always consist of unique positive integers, not necessarily in sorted order (i.e. 5 will not be in the list twice).

A list of truthy/falsy values with the same length as the list of items, where a truthy value represents that the item at the same index has been selected.

An integer representing where to insert the selection. You may choose what the index of the first item of the list is as long as it is constant in every run of your program (e.g. the first item could be index 0 or index 1). Please specify which convention your program adheres to. This index should be in the range [starting_idx, ending_idx+1], i.e. it will always be a valid index. For the case index is ending_idx+1, the selection should be inserted at the end of the list.
You may assume this integer will fit into your language's native integer type.

The input may come from any source desired (stdio, function parameter, etc.)

Output

The output is a list representing the final sequence of items. This can be to any source desired (stdio, return value, function output parameter, etc.). You are allowed to modify any of the inputs in-place (for example, given a modify-able list as a function parameter, and having your function operate in-place on that list).

Test cases

All of the following test cases assume 0-based indexing. I've used 0 and 1 to indicate falsy/truthy values respectively for the selection mask.

Test cases happen to have lists formatted as [a,b,c], but as long as your input lists represent a finite ordered sequence that's fine.

Input:

```<code>[]
[]
0
</code>```

Output:

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

Input:

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

Output:

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

Input:

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

Output:

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

Input:

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

Output:

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

Input:

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

Output:

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

Input:

```<code>[]
</code>```0

Output:

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

Input:

```<code>[]
</code>```2

Output:

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

Scoring

This is code golf; shortest answer in bytes wins. Standard loopholes are prohibited. You are allowed to use any built-ins desired.

答:
C#, 132 bytes

```<code>int[]r(int[]a,bool[]b,int l){var x=a.Where((i,j)=>!b[j]);return x.Take(l).Concat(a.Where((i,j)=>b[j])).Concat(x.Skip(l)).ToArray();}
</code>```

ungolfed:

```<code>    public static int[] r(int[] a,bool[] b,int l)
    {
        var x = a.Where((i, j) => !b[j]);
        return x.Take(l).Concat(a.Where((i, j) => b[j])).Concat(x.Skip(l)).ToArray();
    }
</code>```

improvement ideas appreciated.

Title: Collect and place items

Body:
C#, 132 bytes

int[]r(int[]a,bool[]b,int l){var x=a.Where((i,j)=>!b[j]);return x.Take(l).Concat(a.Where((i,j)=>b[j])).Concat(x.Skip(l)).ToArray();}

ungolfed:

    public static int[] r(int[] a,bool[] b,int l)
    {
        var x = a.Where((i, j) => !b[j]);
        return x.Take(l).Concat(a.Where((i, j) => b[j])).Concat(x.Skip(l)).ToArray();
    }

improvement ideas appreciated.


问:
I'm not the language you're looking for!
Isn't it annoying when you find a piece of code and you don't know what language it was written in? This challenge attempts to somewhat solve this.

Challenge

You will have to write a program that when run in two different languages, will output the string:

This program wasn't written in <language program compiled/interpreted in>, it was built for <other language the program can be run in>!

In the output, language names should have official capitalization. eg: CJam, C++

Neither program should take any input from the user.

When run in both languages, output should be to stdout or equivalent.

There should be no output to stderr in either program.

You may use comments in either language.

Two different versions of the same language count as different languages.

If this is done, the program should output the major version number, and if running on two different minor versions, should report the minor version also.

You should not use prebuilt version functions (this includes variables that have already been evaluated at runtime).

Example output:

Perl and Ruby:

Perl: This program wasn't written in Perl, it was built for Ruby!

Ruby: This program wasn't written in Ruby, it was built for Perl!

Python and C:

Python: This program wasn't written in Python, it was built for C!

C: This program wasn't written in C, it was built for Python!

Python 2 and Python 3:

Python 2: This program wasn't written in Python 2, it was built for Python 3!

Python 3: This program wasn't written in Python 3, it was built for Python 2!

Python 2.4 and Python 2.7:

Python 2.4: This program wasn't written in Python 2.4, it was built for Python 2.7!

Python 2.7: This program wasn't written in Python 2.7, it was built for Python 2.4!

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

答:
C/Java, 277 bytes

```<code>//\u000apublic class Main{static String s="This program wasn't written in Java, it was built for C!";public static void
main(//\u000aString[] a
)
{printf("This program wasn't written in C, it was built for Java!");}
//\u000astatic void printf(String a){System.out.println(s);}}
</code>```

Body:
C/Java, 277 bytes

//\u000apublic class Main{static String s="This program wasn't written in Java, it was built for C!";public static void
main(//\u000aString[] a
)
{printf("This program wasn't written in C, it was built for Java!");}
//\u000astatic void printf(String a){System.out.println(s);}}


答:
Slip, <s>38</s> <s>27</s> 25 bytes

```<code>S>(`=<<`P{1,5}>`P>`P*)+#E
</code>```

Requires input to be padded to a rectangle such that there are spaces in every cell Mario needs to traverse (potentially with a leading line full of spaces). Prints either a string representing the valid path (which includes S, E and all the = walked on except the last) or nothing if no path exists.

Test it here.

Explanation

Slip was Sp3000's entry to our 2D pattern matching language design challenge. It's a bit like a 2D-extension of regex where you can give instructions to the engine's cursor when it's allowed or required to make left or right turns. It also has a convenient feature where you can prevent the cursor from advancing, allowing you to match a single position twice in a row (with different patterns).

Slip doesn't have something comparable to lookarounds in regex, but since you can move over any position multiple times, one can just test the condition and then return. We use this to ensure that we only jump when on the ground by moving into the ground tile after each step.

```<code>S           Match the starting position S.
>           Turn right, so that the cursor points south.
(           One or more times... each repetition of this group represents
            one step to the right.
  `=          Match a = to ensure we've ended up on ground level before.
  <<          Turn left twice, so that the cursor points north.
  `P{1,5}     Match 1 to 5 non-punctuation characters (in our case, either space,
              S or E, i.e. a non-ground character). This is the jump.
  >           Turn right, so that the cursor points east.
  `P          Match another non-ground character. This is the step to the right.
  >           Turn right, so that the cursor points south.
  `P*         Match zero or more non-ground characters. This is the fall.
)+
#           Do not advance the cursor before the next match.
E           Match E, ensuring that the previous path ended on the exit.
</code>```

Title: Can Mario go to the end of this map

Body:
Create a program that determines, given an input of the path, whether Mario can reach the end, denoted by E, from the start, denoted by S.

A path will look something like this:

```<code>S = E
=====
</code>```

In a path, the various symbols and what they represent are:

=: wall/floor/ceiling. Mario cannot walk through wall , and cannot fall past a floor, or jump past a ceiling (he would hit his head)

  (space): air. Mario can walk through this, and jump through it, and fall through it

S: air, except showing where Mario starts. This will always appear in the left-most column of the input, at ground level.

E: air, except showing where Mario wants to get. This will always appear in the right-most column of the input, at ground level.

The input will have spaces at every place where Mario could walk.

Mario can only move forward; in this example Mario cannot get to the goal

```<code>S
===

 ===
   E
====
</code>```

nor can he in this one

```<code>    E
   ==
==
  #==
==
   ==
==
S  ==
======
</code>```

However, he can reach the space denoted by # (which will not appear in input), because he can jump up to four cells high; Mario is superhuman. As another example of his superhumanity:

```<code>S
=
=
=
=
=
= #
= =
=
=
=
=     E
=======
</code>```

Mario can get to the E by falling the great distance, surviving, and walking calmly to E. Note that he cannot reach the #, because Mario falls straight down.

Mario can jump really high, but not very far forward by comparison.

```<code>S   E
== ==
 = =
</code>```

Mario may attempt to jump the gap, but he will fail, and fall straight in. he cannot reach the end.

Mario can reach the goal in all of these examples:

```<code> E
 =
 =
 =
S=
==
</code>```

```<code> =
 =   E
S=   =
==   =
 =   =
 =====
</code>```

```<code>S
=

=  E
====
</code>```

This is code golf, so fewest bytes wins!

Body:
Slip, <s>38</s> <s>27</s> 25 bytes

S>(`=<<`P{1,5}>`P>`P*)+#E

Requires input to be padded to a rectangle such that there are spaces in every cell Mario needs to traverse (potentially with a leading line full of spaces). Prints either a string representing the valid path (which includes S, E and all the = walked on except the last) or nothing if no path exists.

Test it here.

Explanation

Slip was Sp3000's entry to our 2D pattern matching language design challenge. It's a bit like a 2D-extension of regex where you can give instructions to the engine's cursor when it's allowed or required to make left or right turns. It also has a convenient feature where you can prevent the cursor from advancing, allowing you to match a single position twice in a row (with different patterns).

Slip doesn't have something comparable to lookarounds in regex, but since you can move over any position multiple times, one can just test the condition and then return. We use this to ensure that we only jump when on the ground by moving into the ground tile after each step.

S           Match the starting position S.
>           Turn right, so that the cursor points south.
(           One or more times... each repetition of this group represents
            one step to the right.
  `=          Match a = to ensure we've ended up on ground level before.
  <<          Turn left twice, so that the cursor points north.
  `P{1,5}     Match 1 to 5 non-punctuation characters (in our case, either space,
              S or E, i.e. a non-ground character). This is the jump.
  >           Turn right, so that the cursor points east.
  `P          Match another non-ground character. This is the step to the right.
  >           Turn right, so that the cursor points south.
  `P*         Match zero or more non-ground characters. This is the fall.
)+
#           Do not advance the cursor before the next match.
E           Match E, ensuring that the previous path ended on the exit.


问:
Array Escape - get out of there
One day you awake only to find yourself caught in an array. You try to just walk out of there, taking one index at the time, but it seems there are other rules:

The array is completely filled with natural numbers.

If you find yourself on an index n, you go to the index array[n], except:

If you find yourself on an index n which is a prime number, you take array[n] steps back

Example:
You start on index 4, in this array (start index is 0):

```<code>array = [1,4,5,6,8,10,14,15,2,2,4,5,7];
-----------------^ you are here
</code>```

As the value of the field you are on is 8, you go to the index 8 as the first step. The field you land on contains the value 2. You then go to index 2 as your second step. As2is a prime number, you take 5 steps back, which is your third step. As there is no index -3, you successfully escaped the array in a total of 3 steps.

Your task is:

To write a program or function, which accepts an array and a start index as parameter, and outputs the amount of steps to escape the array. If you can't escape the array (e.g. [2,0,2] with start-index 2 => you constantly go from index 2 to 0), output a falsy value. You may use one-based indexing or zero-based indexing, but please specify which you use.

Test cases

Input: [2,5,6,8,1,2,3], 3

Output: 1

Input: [2, 0, 2], 2

Output: false

Input: [14,1,2,5,1,3,51,5,12,3,4,41,15,4,12,243,51,2,14,51,12,11], 5;

Output: 6

The shortest answer wins.

答:
Python, <s>161</s> 138 bytes

Credits for factorial.

g=lambda x:0**x or x*g(x-1)
f=lambda a,i,n=0,l=[]:(i<0)+(i>=len(a))and n or(0 if i in l else f(a,[a[i],i-a[i]][i and-g(i-1)%i],n+1,l+[i]))
```

Ideone it!

How it works

Wilson's theorem is used for prime checking.

Loop detection by storing seen indices to an array (l) and checking whether current index is in l.

Title: Array Escape - get out of there

Body:
Python, <s>161</s> 138 bytes

Credits for factorial.

g=lambda x:0**x or x*g(x-1)
f=lambda a,i,n=0,l=[]:(i<0)+(i>=len(a))and n or(0 if i in l else f(a,[a[i],i-a[i]][i and-g(i-1)%i],n+1,l+[i]))

Ideone it!

How it works

Wilson's theorem is used for prime checking.

Loop detection by storing seen indices to an array (l) and checking whether current index is in l.


答:
Python 3, 106 93 bytes

```<code>def f(x,y,z):
 t,f=[],[]
 for n in range(len(x)):(f,t)[y[n]].append(x[n])
 f[z:z]=t
 return f
</code>```

Older version:

```<code>def f(x,y,z):
 t,f=[],[]
 for n in range(len(x)):
  if y[n]:t+=[x[n]]
  else:f+=[x[n]]
 f[z:z]=t
 return f
</code>```

Title: Collect and place items

Body:
The goal of this challenge is to collect selected items in a list and move them to a certain location in the list.

As a visual example, take the input values (represented by black boxed integers) and a corresponding list of truthy values where true denotes the item is selected (represented by blue boxes, where T is truthy and F is falsy):

The first logical step is to separate the items marked truthy and not truthy into their corresponding lists. Note that relative order in each list must be maintained (i.e. the order of selected items must be 1,4,5, and the order of unselected items must be 2,3,6,7)!

The second logical step is given an index in the remaining list of unselected items, insert all selected items before the item at the given index. Assuming indexing starts at 0, suppose you want to insert the selection at index 3. This corresponds to the spot before the 7 box, so the selected items should be inserted before the 7.

The final solution is then 2,3,6,1,4,5,7.

Note that this logical diagram depicts one way this could be done; your program does not need to take the same logical steps as long as the output always produces the same observable result.

Input

Your program is given 3 inputs:

A list of integers representing the items. This may be an empty list. This list will always consist of unique positive integers, not necessarily in sorted order (i.e. 5 will not be in the list twice).

A list of truthy/falsy values with the same length as the list of items, where a truthy value represents that the item at the same index has been selected.

An integer representing where to insert the selection. You may choose what the index of the first item of the list is as long as it is constant in every run of your program (e.g. the first item could be index 0 or index 1). Please specify which convention your program adheres to. This index should be in the range [starting_idx, ending_idx+1], i.e. it will always be a valid index. For the case index is ending_idx+1, the selection should be inserted at the end of the list.
You may assume this integer will fit into your language's native integer type.

The input may come from any source desired (stdio, function parameter, etc.)

Output

The output is a list representing the final sequence of items. This can be to any source desired (stdio, return value, function output parameter, etc.). You are allowed to modify any of the inputs in-place (for example, given a modify-able list as a function parameter, and having your function operate in-place on that list).

Test cases

All of the following test cases assume 0-based indexing. I've used 0 and 1 to indicate falsy/truthy values respectively for the selection mask.

Test cases happen to have lists formatted as [a,b,c], but as long as your input lists represent a finite ordered sequence that's fine.

Input:

```<code>[]
[]
0
</code>```

Output:

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

Input:

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

Output:

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

Input:

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

Output:

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

Input:

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

Output:

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

Input:

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

Output:

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

Input:

```<code>[]
</code>```0

Output:

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

Input:

```<code>[]
</code>```2

Output:

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

Scoring

This is code golf; shortest answer in bytes wins. Standard loopholes are prohibited. You are allowed to use any built-ins desired.

Body:
Python 3, 106 93 bytes

def f(x,y,z):
 t,f=[],[]
 for n in range(len(x)):(f,t)[y[n]].append(x[n])
 f[z:z]=t
 return f

Older version:

def f(x,y,z):
 t,f=[],[]
 for n in range(len(x)):
  if y[n]:t+=[x[n]]
  else:f+=[x[n]]
 f[z:z]=t
 return f


答:
C, 57 bytes

Call f() with the string to detriplicate. The function modifies its parameter. Requires C99 because of the for-loop declaration.

```<code>f(char*p){for(char*s=p,m[256]={0};*s=*p;s+=++m[*p++]<3);}
</code>```

Title: Detriplicate a string

Body:
C, 57 bytes

Call f() with the string to detriplicate. The function modifies its parameter. Requires C99 because of the for-loop declaration.

f(char*p){for(char*s=p,m[256]={0};*s=*p;s+=++m[*p++]<3);}


问:
The shortest code to tell if a number is even or odd
One of my colleagues proposed us a challenge: to write the shortest C/C++ program to determine if a number is even or odd.

These are the requirements:

Get a number from keyboard, at run-time (not from command line)

Output the string pari if the number is even

Output the string dispari if the number is odd

We can assume that the input is legal

We can assume that the machine has a i386 architecture

Code preprocessing is not allowed (e.g.: use #defines)

[edit after comments] The code can be considered valid if it compiles with gcc 4.x

This is the best attempt we had so far (file test.c, 50B):

```<code>main(i){scanf("%d",&i);puts("dispari"+3*(~i&1));}
</code>```

Do you think we can go further?

(*): "dispari" is the italian for odd and "pari" is the italian for even

答:
39 bytes

Given you didn't specified the range of the number input, then here's a solution that handles 0..9 only:

```<code>main(){puts("dispari"-~getchar()%2*3);}
</code>```

OwnerDisplayName: Vincenzo Pii

Body:
39 bytes

Given you didn't specified the range of the number input, then here's a solution that handles 0..9 only:

main(){puts("dispari"-~getchar()%2*3);}


答:
Python 3, 91 bytes

```<code>def f(a,x,i):b=[c for c,z in zip(a,x)if z<1];return b[:i]+[c for c in a if(c in b)<1]+b[i:]
</code>```

where a is the elements/numbers list,x is the True/False list and i is the index.

Multiline version for improved readability:

```<code>def f(a,x,i):
    b=[c for c,z in zip(a,x)if z<1]
    return b[:i]+[c for c in a if(c in b)<1]+b[i:]
</code>```

How does it work?

The call to zip(a,x) results in a list of tuples where each of them contains the info: (element,0|1). Then a list comprehension is used to determine the elements that have a 0/False value associated and stores them in the variable b.

So [c for c,z in zip(a,x)if z<1] creates a list that contains all the elements that have a 0(False) value associated.

After that, the list of elements which have a True|1 value associated (which is determined by checking which elements of a are not present in b : [c for c in a if(c in b)<1]) is inserted in the list with all the elements that have a 0(False) value associated (list b) at the specified index i and the resulting list is returned.

Title: Collect and place items

Body:
Python 3, 91 bytes

def f(a,x,i):b=[c for c,z in zip(a,x)if z<1];return b[:i]+[c for c in a if(c in b)<1]+b[i:]

where a is the elements/numbers list,x is the True/False list and i is the index.

Multiline version for improved readability:

def f(a,x,i):
    b=[c for c,z in zip(a,x)if z<1]
    return b[:i]+[c for c in a if(c in b)<1]+b[i:]

How does it work?

The call to zip(a,x) results in a list of tuples where each of them contains the info: (element,0|1). Then a list comprehension is used to determine the elements that have a 0/False value associated and stores them in the variable b.

So [c for c,z in zip(a,x)if z<1] creates a list that contains all the elements that have a 0(False) value associated.

After that, the list of elements which have a True|1 value associated (which is determined by checking which elements of a are not present in b : [c for c in a if(c in b)<1]) is inserted in the list with all the elements that have a 0(False) value associated (list b) at the specified index i and the resulting list is returned.


答:
Matlab, 138 bytes

This a straighforward approach, using 1-based indices because Matlab uses 1-based indices by default. To count the number of steps we use a for loop counting from 1 to infinity(!). For the case were we cannot escape the array, we use a vector v to keep track of which entries we already visited. If we visit an entry twice, we know we are stuck in an unescapeable cycle. To see check whether we are outside of an array, we use the try/catch structure, which also catches out of bounds exceptions.

function r=f(a,i);v=a*0;v(i)=1;for k=1:Inf;if isprime(i);i=i-a(i);else;i=a(i);end;try;if v(i);r=0;break;end;v(i)=1;catch;r=k;break;end;end
```

Title: Array Escape - get out of there

Body:
One day you awake only to find yourself caught in an array. You try to just walk out of there, taking one index at the time, but it seems there are other rules:

The array is completely filled with natural numbers.

If you find yourself on an index n, you go to the index array[n], except:

If you find yourself on an index n which is a prime number, you take array[n] steps back

Example:
You start on index 4, in this array (start index is 0):

```<code>array = [1,4,5,6,8,10,14,15,2,2,4,5,7];
-----------------^ you are here
</code>```

As the value of the field you are on is 8, you go to the index 8 as the first step. The field you land on contains the value 2. You then go to index 2 as your second step. As2is a prime number, you take 5 steps back, which is your third step. As there is no index -3, you successfully escaped the array in a total of 3 steps.

Your task is:

To write a program or function, which accepts an array and a start index as parameter, and outputs the amount of steps to escape the array. If you can't escape the array (e.g. [2,0,2] with start-index 2 => you constantly go from index 2 to 0), output a falsy value. You may use one-based indexing or zero-based indexing, but please specify which you use.

Test cases

Input: [2,5,6,8,1,2,3], 3

Output: 1

Input: [2, 0, 2], 2

Output: false

Input: [14,1,2,5,1,3,51,5,12,3,4,41,15,4,12,243,51,2,14,51,12,11], 5;

Output: 6

The shortest answer wins.


答:
PowerShell v2+, 31 bytes

```<code>$args-replace'(.)(?<=\1.*\1.+)'
</code>```

Uses the same regex as in Kobi's Retina answer, just encapsulated in the PowerShell -replace operator. Works because both are using .NET-flavor regex in the background.

Alternatively, without regex, 56 bytes

```<code>$b=,0*200;-join([char[]]$args[0]|%{"$_"*($b[$_]++-lt2)})
</code>```

Creates a helper array $b pre-populated with 0s. Casts the input string $args[0] as a char-array, pipes it through a loop |%{...}. Each iteration outputs the current character $_ as a string "$_" multiplied by a Boolean that is only $TRUE (implicitly cast to 1 here) if the appropriate point in the helper array is less than 2 (i.e., we haven't seen this char twice already). The resultant collection of strings is encapsulated in parens and -joined together to form a single output string. That's left on the pipeline and output is implicit.

Title: Detriplicate a string

Body:
A lot of languages have built-in ways to get rid of duplicates, or "deduplicate" or "uniquify" a list or string. A less common task is to "detriplicate" a string. That is, for every character that appears, the first two occurrences are kept.

Here is an example where the characters that should be deleted are labelled with ^:

```<code>aaabcbccdbabdcd
  ^    ^ ^^^ ^^
aabcbcdd
</code>```

Your task is to implement exactly this operation.

Rules

Input is a single, possibly empty, string. You may assume that it only contains lowercase letters in the ASCII range.

Output should be a single string with all characters removed which have already appeared at least twice in the string (so the left-most two occurrences are kept).

Instead of strings you may work with lists of characters (or singleton strings), but the format has to be consistent between input and output.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

Every pair of lines is one test case, input followed by output.

```<code>

xxxxx
xx
abcabc
abcabc
abcdabcaba
abcdabc
abacbadcba
abacbdc
aaabcbccdbabdcd
aabcbcdd
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates a leaderboard 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 + 3 (-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:
PowerShell v2+, 31 bytes

$args-replace'(.)(?<=\1.*\1.+)'

Uses the same regex as in Kobi's Retina answer, just encapsulated in the PowerShell -replace operator. Works because both are using .NET-flavor regex in the background.

Alternatively, without regex, 56 bytes

$b=,0*200;-join([char[]]$args[0]|%{"$_"*($b[$_]++-lt2)})

Creates a helper array $b pre-populated with 0s. Casts the input string $args[0] as a char-array, pipes it through a loop |%{...}. Each iteration outputs the current character $_ as a string "$_" multiplied by a Boolean that is only $TRUE (implicitly cast to 1 here) if the appropriate point in the helper array is less than 2 (i.e., we haven't seen this char twice already). The resultant collection of strings is encapsulated in parens and -joined together to form a single output string. That's left on the pipeline and output is implicit.