答:
Retina, 60 bytes

```<code>^(.*)(\n(?!\1).*)*(\n(\1.*)).*(\n((?!\1)|\4).*)*$
$4
s`\n.*
</code>```

The trailing new line is significant. Takes input as the string on a line and then each word on a separate line (but no trailing newline!). Works in a similar way to my JavaScript answer by matching the longest common prefix of all lines that begin with the string on the first line. If it doesn't find one then it simply deletes all the words.

Title: Implement tab completion

Body:
Tab completion is a useful feature that auto-completes partially written commands.  You're going to be implementing it.

For example, if the available commands were ['apply','apple','apple pie','eat'], then a would complete to  appl, as all of the commands that start with a also start with appl.

Input/Output

You need to input a string, A, and a set of strings, B.

You need to output the longest common prefix of all B that starts with A.

If none of the options starts with A, then return A

You can assume that B is nonempty, and that all strings are nonempty

You cannot assume that any of the options start with A, nor that the common prefix will be longer than A

You can be case sensitive or case insensitive.

You only need to handle printable ASCII

Built-ins that explicitly do this task are allowed

Test cases:

```<code>'a'       ['apply','apple','apple pie','eat'] => 'appl'
'a'       ['apple pie']                       => 'apple pie'
'apple'   ['eat','dine']                      => 'apple'
'program' ['programa','programb']             => 'program'
'*%a('    ['*%a()-T>','*%a()-T<','@Da^n&']    => '*%a()-T'
'a'       ['abs','absolute','answer']         => 'a'
'a'       ['a','abs']                         => 'a'
'one to'  ['one to one','one to many']        => 'one to '
</code>```

Note the trailing space on the last test case

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

Body:
Retina, 60 bytes

^(.*)(\n(?!\1).*)*(\n(\1.*)).*(\n((?!\1)|\4).*)*$
$4
s`\n.*

The trailing new line is significant. Takes input as the string on a line and then each word on a separate line (but no trailing newline!). Works in a similar way to my JavaScript answer by matching the longest common prefix of all lines that begin with the string on the first line. If it doesn't find one then it simply deletes all the words.


问:
Become the Champion

Tic-Tac-Latin!

This is a true story, so names have been altered.

My latin teacher, Mr. Latin, created his own proprietary (no joke) tic tac toe variant. Let's call it tic-tac-latin. The game is simple, it is essentially tic tac toe played on a four by four grid.

Formal rule declaration

A line is either a row, column or a diagonal. There are two symbols, 'X' and 'O', but one or both may be substituted for a different symbol.

You score one point when you have three of your symbol and one of the other character.

These arrangements score:

```
---O
-O--
<b>XXXO</b>
XOOX

<b>O</b>-XX
-<b>O</b>--
--<b>X</b>-
---<b>O</b>
```

These do not score:

```
----
XXXX
----
OOOO

----
XXX-
----
OOO-
```

The game is won whenever one player has more points then another. The game is a draw only if the board gets filled up.

Challenge

Solve this game. Your job is to provide a way to guarantee a win or tie, whichever is the optimal result.

Your solution may choose to either start first or second (and may therefore choose it's symbol). It is not mandatory to implement an interactive game where the user inputs moves and the corresponding display changes. It may also be a function or program which takes input as a game state, and outputs a new board or a description of their move. Either option must run within approximately ten seconds per move made.

Playing your player against any sequence of moves must give the optimal result. This means that you may assume the input position is one that it reachable from play with your player. Submissions must be deterministic, and do not necessarily need to supply a proof of optimality, but if they get cracked (by being beaten) your submissions will be considered invalid (you may leave it up, but add (cracked) in the headline).

This is a non-trivial task, so any valid submission is impressive and is worthy of an accepted tick, but I will make code golf the primary winning criterion.

The winner is chosen by going down this list till one winner is chosen.

Shortest solved implemenation which always wins

Shortest implementation

答:
JavaScript (ES6) 392 bytes

```<code>a=>b=>(c="0ed3b56879a4c21f",r=[],k=f=>r.push([a.filter(f),b.filter(f)]),[0,1,2,3].map(i=>k(n=>n%4==i)+k(n=>(n/4|0)==i)),k(n=>n%5==0),k(n=>n&&n-15&&!(n%3)),g=r.find(o=>(o[0].length==1&&o[1].length==2)||(o[0].length==2&&o[1].length==1)),g?parseInt(c[30-[...g[0],...g[1]].map(i=>parseInt(c[i],16)).reduce((p,c)=>p+c)],16):[...a,...b].indexOf(15-a[0])+1?15-a.find(i=>b.indexOf(15-i)==-1):15-a[0])
</code>```

Usage

The "bot" will play second.

Draw a 4x4 grid which are numbered like this:

```<code>+----+----+----+----+
|  0 |  1 |  2 |  3 |
+----+----+----+----+
|  4 |  5 |  6 |  7 |
+----+----+----+----+
|  8 |  9 | 10 | 11 |
+----+----+----+----+
| 12 | 13 | 14 | 15 |
+----+----+----+----+
</code>```

Let's run this in the browser console: Just put f= before the code

So, if I wanna start at 1, I would run f([1])([]) and it will give me 14.

Nice move... What if I play 2 afterwards? f([2,1])([14]).  It will return 13.

Lemme try surrendering. Play 3. f([3,2,1])([14,13]).  Oh 0! You got me!

Play 0? f([0,2,1])([14,13]). 15 Ok let's keep playing...

Note

Play interactively.  Start with f([your-step])([]).

Prepend your next step. (See demo above)

Help the "bot" input its steps.  It will not give you good results if you give it a random setting. (Like f([1,2,4])([14,12]) will give 14 - Hey the bot wanted to play on 13 on its second move!

Brief Summary

As long as you are not surrendering, the bot will play a mirror move.

Thanks @EHTproductions for telling me that I misread the game rules and golfing tips :P

Now it will also detect if it got checkmate.  If yes, block it!

Its priorities: Block > Mirror > (fallback) look for ways to reproducing a mirror

ContentLicense: CC BY-SA 3.0

Title: Become the Champion

Body:
JavaScript (ES6) 392 bytes

a=>b=>(c="0ed3b56879a4c21f",r=[],k=f=>r.push([a.filter(f),b.filter(f)]),[0,1,2,3].map(i=>k(n=>n%4==i)+k(n=>(n/4|0)==i)),k(n=>n%5==0),k(n=>n&&n-15&&!(n%3)),g=r.find(o=>(o[0].length==1&&o[1].length==2)||(o[0].length==2&&o[1].length==1)),g?parseInt(c[30-[...g[0],...g[1]].map(i=>parseInt(c[i],16)).reduce((p,c)=>p+c)],16):[...a,...b].indexOf(15-a[0])+1?15-a.find(i=>b.indexOf(15-i)==-1):15-a[0])

Usage

The "bot" will play second.

Draw a 4x4 grid which are numbered like this:

+----+----+----+----+
|  0 |  1 |  2 |  3 |
+----+----+----+----+
|  4 |  5 |  6 |  7 |
+----+----+----+----+
|  8 |  9 | 10 | 11 |
+----+----+----+----+
| 12 | 13 | 14 | 15 |
+----+----+----+----+

Let's run this in the browser console: Just put f= before the code

So, if I wanna start at 1, I would run f([1])([]) and it will give me 14.

Nice move... What if I play 2 afterwards? f([2,1])([14]).  It will return 13.

Lemme try surrendering. Play 3. f([3,2,1])([14,13]).  Oh 0! You got me!

Play 0? f([0,2,1])([14,13]). 15 Ok let's keep playing...

Note

Play interactively.  Start with f([your-step])([]).

Prepend your next step. (See demo above)

Help the "bot" input its steps.  It will not give you good results if you give it a random setting. (Like f([1,2,4])([14,12]) will give 14 - Hey the bot wanted to play on 13 on its second move!

Brief Summary

As long as you are not surrendering, the bot will play a mirror move.

Thanks @EHTproductions for telling me that I misread the game rules and golfing tips :P

Now it will also detect if it got checkmate.  If yes, block it!

Its priorities: Block > Mirror > (fallback) look for ways to reproducing a mirror


问:
Prime counting function

Introduction

The Prime Counting Function, also known as the Pi function \$\pi(x)\$, returns the amount of primes less than or equal to x.

Challenge

Your program will take an integer x which you can assume to be positive, and output a single integer equal to the amount of primes less than or equal to x. This is a code-golf challenge, so the winner will be the program with the fewest bytes.

You may use any language of your choosing provided that it existed before this challenge went up, but if the language has a built-in prime-counting function or a primality checking function (such as Mathematica), that function cannot be used in your code.

Example Inputs

Input:

1

Output:

0

Input:

2

Output:

1

Input:

5

Output:

3

A000720 - OEIS

答:
Jelly, 6 bytes

```<code>Ḷ!²%RS
</code>```

This uses only basic arithmetic and Wilson's theorem. Try it online! or verify all test cases.

How it works

```<code>Ḷ!²%RS  Main link. Argument: n

Ḷ       Unlength; yield [0, ..., n - 1].
 !      Factorial; yield [0!, ..., (n - 1)!].
  ²     Square; yield [0!², ..., (n - 1)!²].
    R   Range; yield [1, ..., n].
   %    Modulus; yield [0!² % 1, ..., (n - 1)!² % n].
        By a corollary to Wilson's theorem, (k - 1)!² % k yields 1 if k is prime
        and 0 if k is 1 or composite.
     S  Sum; add the resulting Booleans.
</code>```

ContentLicense: CC BY-SA 4.0

Title: Prime counting function

Body:
Jelly, 6 bytes

Ḷ!²%RS

This uses only basic arithmetic and Wilson's theorem. Try it online! or verify all test cases.

How it works

Ḷ!²%RS  Main link. Argument: n

Ḷ       Unlength; yield [0, ..., n - 1].
 !      Factorial; yield [0!, ..., (n - 1)!].
  ²     Square; yield [0!², ..., (n - 1)!²].
    R   Range; yield [1, ..., n].
   %    Modulus; yield [0!² % 1, ..., (n - 1)!² % n].
        By a corollary to Wilson's theorem, (k - 1)!² % k yields 1 if k is prime
        and 0 if k is 1 or composite.
     S  Sum; add the resulting Booleans.


Title: Prime counting function

Body:
Introduction

The Prime Counting Function, also known as the Pi function \$\pi(x)\$, returns the amount of primes less than or equal to x.

Challenge

Your program will take an integer x which you can assume to be positive, and output a single integer equal to the amount of primes less than or equal to x. This is a code-golf challenge, so the winner will be the program with the fewest bytes.

You may use any language of your choosing provided that it existed before this challenge went up, but if the language has a built-in prime-counting function or a primality checking function (such as Mathematica), that function cannot be used in your code.

Example Inputs

Input:

1

Output:

0

Input:

2

Output:

1

Input:

5

Output:

3

A000720 - OEIS

Body:
Java 7,102 bytes

Brute force

int f(int n){int i=2,j=2,c=1,t=0;for(;i<=n;j=2,c+=t==1?1:0,i++)for(;j<i;t=i%j++==0?j=i+1:1);return c;}

Ungolfed

int f(int n){
int i=2,j=2,c=1,t=0;
for(;i<=n;j=2,c+=t==1?1:0,i++)
    for(;j<i;)
        t=i%j++==0?j=i+1:1;
    return c;
 }


问:
Tips for Golfing in ECMAScript 6 and above
This is similar to other "Tips for golfing in <...>" but specifically targeting the newer features in JavaScript brought up in ECMAScript 6 and above.

JavaScript inherently is a very verbose language, function(){}, .forEach(), converting string to array, array-like object to array, etc, etc are super bloats and not healthy for Golfing.

ES6+, on the other hand, has some super handy features and reduced footprint. x=>y, [...x], etc. are just some of the examples.

Please post some nice tricks that can help shave off those few extra bytes from your code.

NOTE: Tricks for ES5 are already available in Tips for golfing in JavaScript; answers to this thread should focus on tricks only available in ES6 and other future ES versions.

However, this thread is also for users who currently golf using ES5 features. Answers may also contain tips to help them understand and map ES6 features to their style of ES5 coding.

答:
How to golf with recursion

Recursion, though not the fastest option, is very often the shortest. Generally, recursion is shortest if the solution can simplified to the solution to a smaller part of the challenge, especially if the input is a number or a string. For instance, if f("abcd") can be calculated from "a" and f("bcd"), it's usually best to use recursion.

Take, for instance, factorial:

n=>[...Array(n).keys()].reduce((x,y)=>x*++y,1)
n=>[...Array(n)].reduce((x,_,i)=>x*++i,1)
n=>[...Array(n)].reduce(x=>x*n--,1)
n=>{for(t=1;n;)t*=n--;return t}
n=>eval("for(t=1;n;)t*=n--")
f=n=>n?n*f(n-1):1
```

<p>In this example, recursion is obviously way shorter than any other option.</p>

<p>How about sum of charcodes:</p>

<pre class="lang-js prettyprint-override"><code>s=>[...s].map(x=>t+=x.charCodeAt(),t=0)|t
s=>[...s].reduce((t,x)=>t+x.charCodeAt())
s=>[for(x of(t=0,s))t+=x.charCodeAt()]|t  // Firefox 30+ only
f=s=>s?s.charCodeAt()+f(s.slice(1)):0
</code>```

This one is trickier, but we can see that when implemented correctly, recursion saves 4 bytes over .map.

Now let's look at the different types of recursion:

Pre-recursion

This is usually the shortest type of recursion. The input is split into two parts a and b, and the function calculates something with a and f(b). Going back to our factorial example:

f=n=>n?n*f(n-1):1
```

<p>In this case, <code>a</code> is <strong>n</strong>, <code>b</code> is <strong>n-1</strong>, and the value returned is <code>a*f(b)</code>.</p>

<p><strong>Important note: All</strong> recursive functions <strong>must</strong> have a way to stop recursing when the input is small enough. In the factorial function, this is controlled with the <code>n? :1</code>, i.e. if the input is <strong>0</strong>, return <strong>1</strong> without calling <code>f</code> again.</p>

<h2>Post-recursion</h2>

<p>Post-recursion is similar to pre-recursion, but slightly different. The input is split into two parts <code>a</code> and <code>b</code>, and the function calculates something with <code>a</code>, then calls <code>f(b,a)</code>. The second argument usually has a default value (i.e. <code>f(a,b=1)</code>).</p>

<p>Pre-recursion is good when you need to do something special with the final result. For example, if you want the factorial of a number plus 1:</p>

<pre class="lang-js prettyprint-override"><code>f=(n,p=1)=>n?f(n-1,n*p):p+1
</code>```

Even then, however, post- is not always shorter than using pre-recursion within another function:

n=>(f=n=>n?n*f(n-1):1)(n)+1
```

<p>So when is it shorter? You may notice that post-recursion in this example requires parentheses around the function arguments, while pre-recursion did not. Generally, if both solutions need parentheses around the arguments, post-recursion is around 2 bytes shorter:</p>

<pre class="lang-js prettyprint-override"><code>n=>!(g=([x,...a])=>a[0]?x-a.pop()+g(a):0)(n)
f=([x,...a],n=0)=>a[0]?f(a,x-a.pop()+n):!n
</code>```

(programs here taken from this answer)

How to find the shortest solution

Usually the only way to find the shortest method is to try all of them. This includes:

Loops

.map (for strings, either [...s].map or s.replace; for numbers, you can create a range)

Array comprehensions

Pre-recursion (sometimes within another of these options)

Post-recursion

And these are just the most common solutions; the best solution might be a combination of these, or even something entirely different. The best way to find the shortest solution is to try everything.

Body:
How to golf with recursion

Recursion, though not the fastest option, is very often the shortest. Generally, recursion is shortest if the solution can simplified to the solution to a smaller part of the challenge, especially if the input is a number or a string. For instance, if f("abcd") can be calculated from "a" and f("bcd"), it's usually best to use recursion.

Take, for instance, factorial:

n=>[...Array(n).keys()].reduce((x,y)=>x*++y,1)
n=>[...Array(n)].reduce((x,_,i)=>x*++i,1)
n=>[...Array(n)].reduce(x=>x*n--,1)
n=>{for(t=1;n;)t*=n--;return t}
n=>eval("for(t=1;n;)t*=n--")
f=n=>n?n*f(n-1):1

In this example, recursion is obviously way shorter than any other option.

How about sum of charcodes:

s=>[...s].map(x=>t+=x.charCodeAt(),t=0)|t
s=>[...s].reduce((t,x)=>t+x.charCodeAt())
s=>[for(x of(t=0,s))t+=x.charCodeAt()]|t  // Firefox 30+ only
f=s=>s?s.charCodeAt()+f(s.slice(1)):0

This one is trickier, but we can see that when implemented correctly, recursion saves 4 bytes over .map.

Now let's look at the different types of recursion:

Pre-recursion

This is usually the shortest type of recursion. The input is split into two parts a and b, and the function calculates something with a and f(b). Going back to our factorial example:

f=n=>n?n*f(n-1):1

In this case, a is n, b is n-1, and the value returned is a*f(b).

Important note: All recursive functions must have a way to stop recursing when the input is small enough. In the factorial function, this is controlled with the n? :1, i.e. if the input is 0, return 1 without calling f again.

Post-recursion

Post-recursion is similar to pre-recursion, but slightly different. The input is split into two parts a and b, and the function calculates something with a, then calls f(b,a). The second argument usually has a default value (i.e. f(a,b=1)).

Pre-recursion is good when you need to do something special with the final result. For example, if you want the factorial of a number plus 1:

f=(n,p=1)=>n?f(n-1,n*p):p+1

Even then, however, post- is not always shorter than using pre-recursion within another function:

n=>(f=n=>n?n*f(n-1):1)(n)+1

So when is it shorter? You may notice that post-recursion in this example requires parentheses around the function arguments, while pre-recursion did not. Generally, if both solutions need parentheses around the arguments, post-recursion is around 2 bytes shorter:

n=>!(g=([x,...a])=>a[0]?x-a.pop()+g(a):0)(n)
f=([x,...a],n=0)=>a[0]?f(a,x-a.pop()+n):!n

(programs here taken from this answer)

How to find the shortest solution

Usually the only way to find the shortest method is to try all of them. This includes:

Loops

.map (for strings, either [...s].map or s.replace; for numbers, you can create a range)

Array comprehensions

Pre-recursion (sometimes within another of these options)

Post-recursion

And these are just the most common solutions; the best solution might be a combination of these, or even something entirely different. The best way to find the shortest solution is to try everything.


答:
q 35 bytes

```<code>{sum 1=sum'[0=2_' a mod\: a:til x]}
</code>```

Title: Prime counting function

Body:
q 35 bytes

{sum 1=sum'[0=2_' a mod\: a:til x]}


问:
Implement a Truth-Machine
A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

Gets a number (either 0 or 1) from STDIN.

If that number is 0, print out 0 and terminate.

If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

take input from STDIN or an acceptable alternative

If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program

must output to STDOUT or an acceptable alternative

If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.

when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory

the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. 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. Other than that, all the standard rules of code-golf must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

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

```

答:
Copy, <s>67</s> 59 bytes

My new esolang :D

```<code>getch a
add b a
add b -48
print a
skip b
skip 1
copy -4 0 1
</code>```

Explanation:

```<code>getch a     Take input in variable 'a'
add b a     Set 'b' to 'a'
add b -48   Substract 48 from 'b'
print a     Print 'a'
skip b      Skip the copy if 'a' is not zero
skip 1      ^
copy -4 0 1 Copy the code block from the print to this instruction after this instruction
</code>```

Title: Implement a Truth-Machine

Body:
Copy, <s>67</s> 59 bytes

My new esolang :D

getch a
add b a
add b -48
print a
skip b
skip 1
copy -4 0 1

Explanation:

getch a     Take input in variable 'a'
add b a     Set 'b' to 'a'
add b -48   Substract 48 from 'b'
print a     Print 'a'
skip b      Skip the copy if 'a' is not zero
skip 1      ^
copy -4 0 1 Copy the code block from the print to this instruction after this instruction


问:
The Great, White, North!

Eh!

You know, the problem with us Canadians is that sometimes, after a long day of moose hunting and dam repairing, we forget our way back to our cabins! Wouldn't it be great if our handy laptop (which, is always at our side), had some way to point us home? Well, it's been long told that, if you display a compass on your computer, it will be the brightest when pointed North. I'd like to test this out, but I need a compact program to take with me on my next trip, because my hard drive is already filled with maple syrup recipes (and those CANNOT go). So, your task is to design me a program which, when run, saves or displays an image of the following compass rose:

The letters may be in a different font. Remember, least is best, so lowest byte count wins!

Specifications

Colors

Light purple: #9999FF

Gray: #E5E5E5

Lengths and Angles

Angle a = 45°

Angle b = 90°

Length c = 250 units

Length d = 200 units

Length e = 40 units

Length f = 45 units

Clarifications

The text may be in any appropriate font, where appropriate denotes that it is readable to the average, educated human being.

The text must be 3 units away from the spikes at its closest point, must not touch the rose, and must be upright

If a line is drawn from the center of the rose, through the end point of the spike and beyond, it should cross through the center of the text with a precision of +/- 2 units (the text must be centered along an axis a, where a extends from the middle of the page, through the end of the spike, and beyond)

Each character must be at least 15 units by 15 units, and have an x/y or y/x ratio of no more than 2:1 (no stretching – readability)

The dim circle passing through the longer spikes and text closest to the middle on the reference image is not to be drawn.

The image must be square, and at least 400px by 400px

A compressed image within the source is disallowed

A unit must be at least 1 pixel

答:
PHP, 628 bytes

added a few linebreaks for convenience.

```<code>$c=$z.create;$h=$c($w=250,$w);$i=$c(530,533);$a=$z.colorallocate;$a($h,$f=255,$f,$f);$a($i,$f,$f,$f);$a($h,229,229,229);$a($h,153,153,$f);
$p=$z.filledpolygon;$p($h,$o=[0,64,0,0,141,141,],3,2);$p($h,[64,0]+$o,3,1);$p($h,$o=[0,$w,0,0,57,57],3,1);$p($h,[$w,0]+$o,3,2);
$c=$z.copy;$r=$z.rotate;$c($i,$h,263,267,0,0,$w,$w);$c($i,$r($h,90,0),263,17,0,0,$w,$w);$c($i,$r($h,180,0),13,17,0,0,$w,$w);$c($i,$r($h,270,0),13,267,0,0,$w,$w);
$s=$z.string;$s($i,5,259,0,N,3);$s($i,5,259,518,S,3);$s($i,5,0,259,W,3);$s($i,5,518,259,E,3);$s($i,5,106,108,NW,3);$s($i,5,406,108,NE,3);$s($i,5,406,410,SE,3);$s($i,5,106,410,SW,3);
imagepng($i,"n.png");
</code>```

Run with -r. Creates a file n.png with the image; unit is 2 pixels.

I must admit I found the coords for the winds by trial & error, and they are probably a bit off. Will do the calculations soon; but I promise: they won´t change the byte count.

Had my fun for now excavating my trignonometry and struggling with imagecopy ... what a sissy!

on golfing: not many tricks; but these few saved a lot:

Assigning function names and two of the values to variables probably had the largest impact.

I didn´t even count before I replaced the function names.

The magic with the array + operator gave 42 bytes.

Writing a file instead of sending the image to the browser saved 27 bytes.

Moving assignments to the first usage of the variables gave a few more.

breakdown

```<code>// create images and allocate colors
$c=imagecreate;
$h=$c($w=250,$w);   // helper image - just as large as needed or imagecopy will screw up
$i=$c(530,533);     // main image

$a=imagecolorallocate;
$a($h,$f=255,$f,$f);    // white is 0
$a($i,$f,$f,$f);    // must be assigned to both images
$a($h,229,229,229); // grey is 1
$a($h,153,153,$f);  // purple is 2

// draw the south-east quadrant
$p=imagefilledpolygon;
// small triangle purple first
$p($h,$o=[
// point 3: 0.8*e *2
    0,64,
// point 1: center
    0,0,
// point 2: a=45 degrees, d=200 units
    141,141,// d/sqrt(2)=141.421356
],3,2);
// small triangle grey
$p($h,[64,0]+$o,3,1);

// large triangles
$p($h,$o=[
    0,$w,
    0,0,
    57,57   // e*sqrt(2)=56.5685424949
],3,1);

$p($h,[$w,0]+$o,3,2);

// create rose
$c=imagecopy;
$r=imagerotate;
$c($i,$h,263,267,0,0,$w,$w);            // copy quadrant to main image (SE)
$c($i,$r($h,90,0),263,17,0,0,$w,$w);    // rotate quadrant and copy again (NE)
$c($i,$r($h,180,0),13,17,0,0,$w,$w);    // rotate and copy again (NW)
$c($i,$r($h,270,0),13,267,0,0,$w,$w);// rotate and copy a last time (SW)

// add circle
#imageellipse($i,263,267,500,500,2);    // grey is now 2: imagecopy shuffled colors

// add names
$s=imagestring;
$s($i,5,259,  0,N,3);   // 5 is actually the largest internal font PHP provides
$s($i,5,259,518,S,3);   // unassigned colors are black
$s($i,5,  0,259,W,3);
$s($i,5,518,259,E,3);

$s($i,5,106,108,NW,3);
$s($i,5,406,108,NE,3);
$s($i,5,406,410,SE,3);
$s($i,5,106,410,SW,3);

// output
#header("Content-Type:image/png");
#imagepng($i);
imagepng($i,"n.png");
</code>```

Title: The Great, White, North!

Body:
PHP, 628 bytes

added a few linebreaks for convenience.

$c=$z.create;$h=$c($w=250,$w);$i=$c(530,533);$a=$z.colorallocate;$a($h,$f=255,$f,$f);$a($i,$f,$f,$f);$a($h,229,229,229);$a($h,153,153,$f);
$p=$z.filledpolygon;$p($h,$o=[0,64,0,0,141,141,],3,2);$p($h,[64,0]+$o,3,1);$p($h,$o=[0,$w,0,0,57,57],3,1);$p($h,[$w,0]+$o,3,2);
$c=$z.copy;$r=$z.rotate;$c($i,$h,263,267,0,0,$w,$w);$c($i,$r($h,90,0),263,17,0,0,$w,$w);$c($i,$r($h,180,0),13,17,0,0,$w,$w);$c($i,$r($h,270,0),13,267,0,0,$w,$w);
$s=$z.string;$s($i,5,259,0,N,3);$s($i,5,259,518,S,3);$s($i,5,0,259,W,3);$s($i,5,518,259,E,3);$s($i,5,106,108,NW,3);$s($i,5,406,108,NE,3);$s($i,5,406,410,SE,3);$s($i,5,106,410,SW,3);
imagepng($i,"n.png");

Run with -r. Creates a file n.png with the image; unit is 2 pixels.

I must admit I found the coords for the winds by trial & error, and they are probably a bit off. Will do the calculations soon; but I promise: they won´t change the byte count.

Had my fun for now excavating my trignonometry and struggling with imagecopy ... what a sissy!

on golfing: not many tricks; but these few saved a lot:

Assigning function names and two of the values to variables probably had the largest impact.

I didn´t even count before I replaced the function names.

The magic with the array + operator gave 42 bytes.

Writing a file instead of sending the image to the browser saved 27 bytes.

Moving assignments to the first usage of the variables gave a few more.

breakdown

// create images and allocate colors
$c=imagecreate;
$h=$c($w=250,$w);   // helper image - just as large as needed or imagecopy will screw up
$i=$c(530,533);     // main image

$a=imagecolorallocate;
$a($h,$f=255,$f,$f);    // white is 0
$a($i,$f,$f,$f);    // must be assigned to both images
$a($h,229,229,229); // grey is 1
$a($h,153,153,$f);  // purple is 2

// draw the south-east quadrant
$p=imagefilledpolygon;
// small triangle purple first
$p($h,$o=[
// point 3: 0.8*e *2
    0,64,
// point 1: center
    0,0,
// point 2: a=45 degrees, d=200 units
    141,141,// d/sqrt(2)=141.421356
],3,2);
// small triangle grey
$p($h,[64,0]+$o,3,1);

// large triangles
$p($h,$o=[
    0,$w,
    0,0,
    57,57   // e*sqrt(2)=56.5685424949
],3,1);

$p($h,[$w,0]+$o,3,2);

// create rose
$c=imagecopy;
$r=imagerotate;
$c($i,$h,263,267,0,0,$w,$w);            // copy quadrant to main image (SE)
$c($i,$r($h,90,0),263,17,0,0,$w,$w);    // rotate quadrant and copy again (NE)
$c($i,$r($h,180,0),13,17,0,0,$w,$w);    // rotate and copy again (NW)
$c($i,$r($h,270,0),13,267,0,0,$w,$w);// rotate and copy a last time (SW)

// add circle
#imageellipse($i,263,267,500,500,2);    // grey is now 2: imagecopy shuffled colors

// add names
$s=imagestring;
$s($i,5,259,  0,N,3);   // 5 is actually the largest internal font PHP provides
$s($i,5,259,518,S,3);   // unassigned colors are black
$s($i,5,  0,259,W,3);
$s($i,5,518,259,E,3);

$s($i,5,106,108,NW,3);
$s($i,5,406,108,NE,3);
$s($i,5,406,410,SE,3);
$s($i,5,106,410,SW,3);

// output
#header("Content-Type:image/png");
#imagepng($i);
imagepng($i,"n.png");


问:
Showcase of Languages

Notes

This thread is open and unlocked only because the community decided to make an exception. Please do not use this question as evidence that you can ask similar questions here. Please do not create additional showcase questions.

This is no longer a popularity-contest, nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.

This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.

How this works

All answers should include the name of the programming language at the top of the post, prefixed by a #.

Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.

Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.

The snippets do not need to be related. In fact, snippets that are too related may be redundant.

Since this is not a contest, all programming languages are welcome, whenever they were created.

Answers that contain more than a handful of code snippets should use a Stack Snippet to collapse everything except the factoid and one of the snippets.

Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a Stack Snippet for compressing posts, which should mitigate the effect of the 30,000 character limit.

Answers that predate these guidelines should be edited. Please help updating them as needed.

Current answers, sorted alphabetically by language name

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('
' + temp.innerText || temp.textContent + '');}}})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul></code>```

答:
Copy

Copy is my new esolang. The only branching operations are skipping a instruction and code removing and copying, and the only arithmetic operations addition and negation.

Length 6

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

skip skip the next instruction if its argument is not 0. So here, it's essentially a no-op.

Length 7

```<code>add a 5
</code>```

Add 5 to the variable a. Since a is undefined, it set it to 5.

Length 8

```<code>add a -8
</code>```

Add -8 to the variable a. This is to demonstrate than signed numbers are allowed as command arguments.

Title: Showcase of Languages

Body:
Copy

Copy is my new esolang. The only branching operations are skipping a instruction and code removing and copying, and the only arithmetic operations addition and negation.

Length 6

skip 0

skip skip the next instruction if its argument is not 0. So here, it's essentially a no-op.

Length 7

add a 5

Add 5 to the variable a. Since a is undefined, it set it to 5.

Length 8

add a -8

Add -8 to the variable a. This is to demonstrate than signed numbers are allowed as command arguments.


问:
Merge working time periods
You have an array of working time period pairs (from, till) received from user input and written according  24-hour clock format convention.
   You have to merge these periods if the intersect each other.

For example, if you have (10, 12), (11, 13), (12, 14) you should merge them into (10,14).
   Also (23, 0) and (0, 1) should be merged into (23, 1).

UPDATE:

@dmckee Let assume that the set of pairs like (10:00, 12:00) is the valid input.

@dude We don't consider Sundays and holidays so all merges should be performed for the common twenty-four hours range.

@steven-rumbalski  The result of (0,8), (8,16), (16,0) may be any (x,x) pair, for example, (00:00,00:00).

Example 1

Input

```<code>(09:00,12:00),(11:00,13:00),(17:00,19:00)
</code>```

Output

```<code>(09:00,13:00),(17:00,19:00)
</code>```

Example 2

Input

```<code>(00:00,08:00),(08:00,16:00),(16:00,00:00)
</code>```

Output

```<code>(00:00)
</code>```

Title: Merge working time periods

Body:
Python (198 chars)

r=[]
p=r.append
l=r+sorted(a<b and (a,b)or p((0,b))or(a,24)for a,b in input())
r[:]=[]
a,b=l[0]
for c,d in l[1:]:
 if c>b:p((a,b));a,b=c,d
 elif b<d:b=d
if b>23:b=a and r.pop(0)[1]
p((a,b))
print r

Example:

> python merge.py
(10, 12), (11, 13), (12, 14)
[(10, 14)]
> python merge.py
(23,0),(0,1)
[(23, 1)]
> python merge.py
(0,8), (8,16), (16,0)
[(0, 0)]


问:
Print a layered cake

Challenge

Given an input n, print an ASCII art cake n layers tall, viewed from the side, with two candles on top. Refer to the examples below for details.

Output

```<code>>> cake(1)

 _|_|_
|     |
+-----+

>> cake(3)

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

...and so on.

Rules

Standard loopholes prohibited

Please make an attempt at a clever solution

This is code-golf, so shortest answer in bytes wins. However, the answer will not be selected.

Have fun!

答:
Vimscript, <s>116</s> 115 bytes

Pretty messy but it works!

```<code>fu A(n)
let @z="Vkyjply4lpjy4hp"
exe "norm 2i+\e5i-\eo||\e5i \e".a:n."@zddl4xggd$i_|_|_"
exe "%ce ".(a:n*4+3)
endfu
</code>```

To call it: call A(3) in an empty buffer. To load the function, source cake.vim

Explanation

2i+<Esc>5i-<Esc> writes the first line +-----+

o||<Esc>5i<Space><Esc> adds |     | on the second line

Vkyjply4lpjy4hp is saved in the macro @z - it visually selects both lines, yanks them, pastes them under and adds 4 dashes and spaces to them.

#@z repeats this # times

ddl4x deletes the last lines and remove for dashes to the bottom of the cake to make it equal with the top of the bottom layer

ggd$i_|_|_ replaces the first line by the top of the cake

%ce then centers the whole cake to the  width of the bottom layer! !

Title: Print a layered cake

Body:
Vimscript, <s>116</s> 115 bytes

Pretty messy but it works!

fu A(n)
let @z="Vkyjply4lpjy4hp"
exe "norm 2i+\e5i-\eo||\e5i \e".a:n."@zddl4xggd$i_|_|_"
exe "%ce ".(a:n*4+3)
endfu

To call it: call A(3) in an empty buffer. To load the function, source cake.vim

Explanation

2i+<Esc>5i-<Esc> writes the first line +-----+

o||<Esc>5i<Space><Esc> adds |     | on the second line

Vkyjply4lpjy4hp is saved in the macro @z - it visually selects both lines, yanks them, pastes them under and adds 4 dashes and spaces to them.

#@z repeats this # times

ddl4x deletes the last lines and remove for dashes to the bottom of the cake to make it equal with the top of the bottom layer

ggd$i_|_|_ replaces the first line by the top of the cake

%ce then centers the whole cake to the  width of the bottom layer! !


问:
Shortest way to strip the commas from column n given a .csv file/input
Ok, so the input here is going to be a .csv file and so is the output. Now, given a .csv file/input like so

```<code>"apple","banana","apple,banana","orange"
"grape","orange","grape,orange","sprout"
# 0       1        2              3
</code>```

strip out all commas for a given nth column's entries (index starts at 0). So, for the input above, the program would output a .csv file like so for n = 2:

```<code>"apple","banana","applebanana","orange"
"grape","orange","grapeorange","sprout"
</code>```

If the particular column's entries do not have commas, then it does nothing. Could have any allowable/manageable number of columns, and if you somehow find that creating a program that takes more than one argument, say, a, b, c, ..., z like this

```<code>program(a=1,b=4,c=65, ..., z=0, mycsv.csv)
</code>```

for respective columns 2, 5, and 66, which all strip out commas for each, to be shorter, then do that.

Shortest code measured in bytes wins, and it doesn't have to be a file that is output/input.

答:
Python 2, <s>129</s> <s>126</s> <s>125</s> <s>98</s> <s>96</s> <s>94</s> 92 bytes

lambda n,f:''.join(c*((r[:i].count('"')-n*2)*','!=c)for r in open(f)for i,c in enumerate(r))
```

<p>This is a lambda expression; to use it, prefix <code>lambda</code> with <code>s=</code>.</p>

<p>Iterates through each character of each line, filtering characters based on whether it's a comma and it's in a double-quoted string.</p>

<p>Now doesn't use the <code>csv</code> module at all!</p>

<p>Example run:</p>

```>>> s=lambda n,f:''.join(c*((r[:i].count('"')-n*2)*','!=c)for r in open(f)for i,c in enumerate(r))
>>> print s(2, 'test.csv')
"apple","banana","applebanana","orange"
"grape","orange","grapeorange","sprout"
```

Body:
Python 2, <s>129</s> <s>126</s> <s>125</s> <s>98</s> <s>96</s> <s>94</s> 92 bytes

lambda n,f:''.join(c*((r[:i].count('"')-n*2)*','!=c)for r in open(f)for i,c in enumerate(r))

This is a lambda expression; to use it, prefix lambda with s=.

Iterates through each character of each line, filtering characters based on whether it's a comma and it's in a double-quoted string.

Now doesn't use the csv module at all!

Example run:

>>> s=lambda n,f:''.join(c*((r[:i].count('"')-n*2)*','!=c)for r in open(f)for i,c in enumerate(r))
>>> print s(2, 'test.csv')
"apple","banana","applebanana","orange"
"grape","orange","grapeorange","sprout"


问:
A Mouse with Dynamite
You're a mouse. Your mouse friends have all been captured, and are unconscious and trapped in a maze that has only one entrance/exit. You happen to have a perfect map of the maze, so you can plot a solution to rush in and carry them all to safety. However, the maze is guarded with a security system that will trigger an alert if a threshold of 1000 is reached, causing you to be captured and fail your rescue mission.

From your previous investigations of the maze, each square you step (i.e., each horizontal or vertical movement -- mice can't move diagonally) adds 1 to the security system's counter. However, if you're carrying a weight (either a block of dynamite or an unconscious mouse friend), it instead adds 2 since it detects the additional pressure. The entrance/exit square doesn't have this security system, and so doesn't add to the counter.

You have an unlimited supply of dynamite that you've brought to the entrance, so you can simply blow up all the walls to free your friends. But you need to be cautious with doing so, since each explosion adds 50 to the counter from the concussive pressure. Additionally, you can only carry one thing at a time, either one mouse or one block of dynamite. Since each block of dynamite can only detonate one wall space, this means that if there are multiple walls in a row, you need to make an empty-handed trip back to the entrance to grab more.

Worked-through example

Suppose our maze looks like the following:

```<code>######
#M# E#
######
</code>```

I'll use c for the counter. We start at the Entrance, move one square left while carrying dynamite, c=2. We detonate the dynamite to explode the wall, c=52. We move two squares left, empty-handed, to get c=54, and we're now standing on the mouse's square. We pick our friend up, and move 3 squares back to the Exit, but the last square doesn't count since it doesn't have any sensors, so that's only 2 squares with something on our back. That means that when we reach the exit with the final mouse, c=58, which is less than 1000, and therefore the mission succeeds.

Challenge

Given an input maze, output whether you, the mouse hero, can successfully rescue all trapped mice within the constraints outlined above, or whether the mission is a failure.

Input

A 2D maze in any acceptable format (multiline string, array of strings, etc.).

For this challenge, I will be using # for both the interior and exterior walls, M for the mouse friends, and E for the entrance.

The entrance will never be immediately adjacent to an interior wall (there will always be at least one space in which to move freely).

You can substitute any printable ASCII characters you wish so long as it's consistent. This does allow you to use two different symbols for interior walls vs. exterior walls, so long as you maintain consistency (e.g., if you choose to use @ for interior walls instead, and leave # for exterior, every interior wall must be @ and every exterior wall #).

The maze will always be completely bounded by walls, but is not necessarily rectangular. If desired, you can assume that the maze is padded with spaces to make rectangular input (optional).

The maze may have sections that are unreachable without dynamite.

You cannot dynamite the exterior walls of the maze.

Output

A truthy/falsey value. Truthy for "Yes, the mouse can rescue every other mouse" or Falsey for "No, the alarm system will be tripped."

The Rules

Either a full program or a function are acceptable.

Standard loopholes are forbidden.

This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

Truthy examples, separated by blank lines.

```<code>#####
#M E#
#####

######
#M# E#
######

########
#E  # M#
#   #  #
#   #  #
#      #
########

#############################
#    ##      #       #      #
#  M ## M    #       #      #
#    ##      #   M   #    E #
#M   ##      #       #      #
#############################

###############
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMM MM#
#MMMMMMMMMMMME#
###############
</code>```

Falsey examples, separated by blank lines

```<code>#############################
#M   ##      ##      ##     #
#  M ## M    ##      ##     #
#    ##      ##  M   ##   E #
#M   ##      ##      ##     #
#############################
#############################
                     ########
                     ########
                     #   #  #
                     # M # M#
                     ########

              #####
              # M #
              #####
              #####
              #####
              #####
###################
# # # ##   ## # # #
#M#M#M## E ##M#M#M#
# # # ##   ## # # #
###################
#######
######
#####
####
# M#
####

###############
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMME#
###############
</code>```

答:
JavaScript, <s>863</s> <s>834</s> <s>785</s> 781 bytes

Saved 29 bytes thanks to ETHproductions

Saved 53 bytes thanks to Jordan

```<code>L=[]
f=(S,r="",R="",p=0,s=S.replace(RegExp(r),R),l=`((.|\n){${s.split`
`[0].length}})`,q=p+1,o=p+2,n=p+50)=>s in L|p>999?1e3:!/M/.test(s,L[s]=0)&/E/.test(s)?p:Math.min(...[[/ E/,"me",q],[/ E/,"de",o],[/ME/,"ce",q],[/E /,"em",q],[/E /,"ed",o],[/EM/,"ec",q],[`E${l} `,"e$1m",q],[`E${l} `,"e$1d",o],[`E${l}M`,"e$1c",q],[` ${l}E`,"m$1e",q],[` ${l}E`,"d$1e",o],[`M${l}E`,"c$1e",q],[/ m/,"m ",q],[/m /," m",q],[`m${l} `," $1m",q],[` ${l}m`,"m$1 ",q],[/ (d|c)/,"$1 ",o],[/(d|c) /," $1",o],[`(d|c)${l} `," $2$1",o],[` ${l}(d|c)`,"$3$1 ",o],[/d#/,"m ",n],[/#d/," m",n],[`#${l}d`," $1m",n],[`d${l}#`,"m$1 ",n],[/mM/," c",q],[/Mm/,"c ",q],[`M${l}m`,"c$1 ",q],[`m${l}M`," $1c",q],[/[mc]e/," E",p],[/e[mc]/,"E ",p],[`e${l}[mc]`,"E$1 ",p],[`[mc]${l}e`," $1E",p]].map(a=>f(s,...a)))
F=s=>f(s)<1e3
</code>```

Takes input as a multiline string.

This defines an anonymous function that uses a recursive function f to determine if you trip off the alarm before retrieving all the mice. f returns 1000 if the pressure is above 1000 (to avoid endless recursion), returns the pressure if there are no more mice to rescue and the mouse in the exit, and returns the minimum pressure of all possible moves from the current state otherwise. It uses an array L to keep track of already visited positions where L[pos]==0 if it is visited, and undefined if it isn't. This may not be necessary, but it prevents the mouse from doing useless moves and throwing recursion errors at the very least. (This does mean you should redefine L if you are testing this multiple times)

This uses the format in the question other than that it requires you to use a different character for the external walls. (Anything other than # MEmecd)

More readable version:

```<code>stateList = []
f=(s,regex="",replacement="",pressure=0,state=s.replace(regexp(regex),replacement),line=`((.|\n){${state.split("\n")[0].length}})`)=>{
    if (state in stateList || pressure > 999) return 1e3
    if (!/M/.test(state) && /E/.test(state)) return pressure

    stateList[state] = 0

    return [
        [/ E/,"me",pressure+1],
        [/ E/,"de",pressure+2],
        [/ME/,"ce",pressure+1],
        [/E /,"em",pressure+1],
        [/E /,"ed",pressure+2],
        [/EM/,"ec",pressure+1],
        [`E${line} `,"e$1m",pressure+1],
        [`E${line} `,"e$1d",pressure+2],
        [`E${line}M`,"e$1c",pressure+1],
        [` ${line}E`,"m$1e",pressure+1],
        [` ${line}E`,"d$1e",pressure+2],
        [`M${line}E`,"c$1e",pressure+1],
        [/ m/,"m ",pressure+1],
        [/m /," m",pressure+1],
        [`m${line} `," $1m",pressure+1],
        [` ${line}m`,"m$1 ",pressure+1],
        [/ ([dc])/,"$1 ",pressure+2],
        [/([dc]) /," $1",pressure+2],
        [`([dc])${line} `," $2$1",pressure+2],
        [` ${line}([dc])`,"$3$1 ",pressure+2],
        [/d#/,"m ",pressure+50],
        [/#d/," m",pressure+50],
        [`#${line}d`," $1m",pressure+50],
        [`d${line}#`,"m$1 ",pressure+50],
        [/mM/," c",pressure+1],
        [/Mm/,"c ",pressure+1],
        [`M${line}m`,"c$1 ",pressure+1],
        [`m${line}M`," $1c",pressure+1],
        [/[mc]e/," E",pressure],
        [/e[mc]/,"E ",pressure],
        [`e${line}[mc]`,"E$1 ",pressure],
        [`[mc]${line}e`," $1E",pressure]
    ].map(a=>f(state,...a)).reduce((a,b)=>a-b<0?a:b) //reduce used for support in more browsers.
}
s=>f(s)>1e3
</code>```

Title: A Mouse with Dynamite

Body:
JavaScript, <s>863</s> <s>834</s> <s>785</s> 781 bytes

Saved 29 bytes thanks to ETHproductions

Saved 53 bytes thanks to Jordan

L=[]
f=(S,r="",R="",p=0,s=S.replace(RegExp(r),R),l=`((.|\n){${s.split`
`[0].length}})`,q=p+1,o=p+2,n=p+50)=>s in L|p>999?1e3:!/M/.test(s,L[s]=0)&/E/.test(s)?p:Math.min(...[[/ E/,"me",q],[/ E/,"de",o],[/ME/,"ce",q],[/E /,"em",q],[/E /,"ed",o],[/EM/,"ec",q],[`E${l} `,"e$1m",q],[`E${l} `,"e$1d",o],[`E${l}M`,"e$1c",q],[` ${l}E`,"m$1e",q],[` ${l}E`,"d$1e",o],[`M${l}E`,"c$1e",q],[/ m/,"m ",q],[/m /," m",q],[`m${l} `," $1m",q],[` ${l}m`,"m$1 ",q],[/ (d|c)/,"$1 ",o],[/(d|c) /," $1",o],[`(d|c)${l} `," $2$1",o],[` ${l}(d|c)`,"$3$1 ",o],[/d#/,"m ",n],[/#d/," m",n],[`#${l}d`," $1m",n],[`d${l}#`,"m$1 ",n],[/mM/," c",q],[/Mm/,"c ",q],[`M${l}m`,"c$1 ",q],[`m${l}M`," $1c",q],[/[mc]e/," E",p],[/e[mc]/,"E ",p],[`e${l}[mc]`,"E$1 ",p],[`[mc]${l}e`," $1E",p]].map(a=>f(s,...a)))
F=s=>f(s)<1e3

Takes input as a multiline string.

This defines an anonymous function that uses a recursive function f to determine if you trip off the alarm before retrieving all the mice. f returns 1000 if the pressure is above 1000 (to avoid endless recursion), returns the pressure if there are no more mice to rescue and the mouse in the exit, and returns the minimum pressure of all possible moves from the current state otherwise. It uses an array L to keep track of already visited positions where L[pos]==0 if it is visited, and undefined if it isn't. This may not be necessary, but it prevents the mouse from doing useless moves and throwing recursion errors at the very least. (This does mean you should redefine L if you are testing this multiple times)

This uses the format in the question other than that it requires you to use a different character for the external walls. (Anything other than # MEmecd)

More readable version:

stateList = []
f=(s,regex="",replacement="",pressure=0,state=s.replace(regexp(regex),replacement),line=`((.|\n){${state.split("\n")[0].length}})`)=>{
    if (state in stateList || pressure > 999) return 1e3
    if (!/M/.test(state) && /E/.test(state)) return pressure

    stateList[state] = 0

    return [
        [/ E/,"me",pressure+1],
        [/ E/,"de",pressure+2],
        [/ME/,"ce",pressure+1],
        [/E /,"em",pressure+1],
        [/E /,"ed",pressure+2],
        [/EM/,"ec",pressure+1],
        [`E${line} `,"e$1m",pressure+1],
        [`E${line} `,"e$1d",pressure+2],
        [`E${line}M`,"e$1c",pressure+1],
        [` ${line}E`,"m$1e",pressure+1],
        [` ${line}E`,"d$1e",pressure+2],
        [`M${line}E`,"c$1e",pressure+1],
        [/ m/,"m ",pressure+1],
        [/m /," m",pressure+1],
        [`m${line} `," $1m",pressure+1],
        [` ${line}m`,"m$1 ",pressure+1],
        [/ ([dc])/,"$1 ",pressure+2],
        [/([dc]) /," $1",pressure+2],
        [`([dc])${line} `," $2$1",pressure+2],
        [` ${line}([dc])`,"$3$1 ",pressure+2],
        [/d#/,"m ",pressure+50],
        [/#d/," m",pressure+50],
        [`#${line}d`," $1m",pressure+50],
        [`d${line}#`,"m$1 ",pressure+50],
        [/mM/," c",pressure+1],
        [/Mm/,"c ",pressure+1],
        [`M${line}m`,"c$1 ",pressure+1],
        [`m${line}M`," $1c",pressure+1],
        [/[mc]e/," E",pressure],
        [/e[mc]/,"E ",pressure],
        [`e${line}[mc]`,"E$1 ",pressure],
        [`[mc]${line}e`," $1E",pressure]
    ].map(a=>f(state,...a)).reduce((a,b)=>a-b<0?a:b) //reduce used for support in more browsers.
}
s=>f(s)>1e3


答:
JavaScript (ES6), <s>95</s> <s>93</s> 90 bytes

Takes the content of the CSV file as its first parameter and the column index as its second parameter, with currying syntax.

let f =

s=>n=>s.split(/("[^"]*")/).map(c=>(c<' '?(k=0,c):k++-n*2?c:c.split`,`.join``),k=-1).join``

console.log(f(
`"apple","banana","apple,banana","orange"
"grape","orange","grape,orange","sprout"
`)(2));```

Title: Shortest way to strip the commas from column n given a .csv file/input

Body:
Ok, so the input here is going to be a .csv file and so is the output. Now, given a .csv file/input like so

```<code>"apple","banana","apple,banana","orange"
"grape","orange","grape,orange","sprout"
# 0       1        2              3
</code>```

strip out all commas for a given nth column's entries (index starts at 0). So, for the input above, the program would output a .csv file like so for n = 2:

```<code>"apple","banana","applebanana","orange"
"grape","orange","grapeorange","sprout"
</code>```

If the particular column's entries do not have commas, then it does nothing. Could have any allowable/manageable number of columns, and if you somehow find that creating a program that takes more than one argument, say, a, b, c, ..., z like this

```<code>program(a=1,b=4,c=65, ..., z=0, mycsv.csv)
</code>```

for respective columns 2, 5, and 66, which all strip out commas for each, to be shorter, then do that.

Shortest code measured in bytes wins, and it doesn't have to be a file that is output/input.


答:
NodeJS, 129 bytes

```<code>(f,n)=>(require("fs").readFileSync(f)+"").split`
`.map(a=>a.match(/".*?"/g).map((b,i)=>i-n?b:b.replace(/,/g,"")).join`,`).join`
`
</code>```

Defines an anonymous function that takes a file path and a number as input. It is no longer required to take input as a file, but I will leave this here for comparison.

Body:
NodeJS, 129 bytes

(f,n)=>(require("fs").readFileSync(f)+"").split`
`.map(a=>a.match(/".*?"/g).map((b,i)=>i-n?b:b.replace(/,/g,"")).join`,`).join`
`

Defines an anonymous function that takes a file path and a number as input. It is no longer required to take input as a file, but I will leave this here for comparison.


答:
hansl

hansl is a programming language that is used in the statistical software project gretl since 2001. It resembles a mixture of R, Stata, and C. It operates with datasets, time series, vectors, matrices, and functions. Just as in R, there are dozens of user-written packages for econometrics and data analysis. It is a matrix-oriented interpreted language that is Turing-complete (!). Its fortes are econometric estimation and numerical maximisation, and it can be integrated with R, Ox, Octave, Stata, Python, Julia, and gnuplot.

Length 1 snippet

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

You know how difficult it can be to build matrices from vectors? One can attain the effect by reading the input row-wise, column-wise, or through assembling the mess into a dataset? In hansl, you do not hassle: just write ~ between the two vectors, and voila, you get them bound <s>in tight leather</s> together vertically: A~B. Do you have two matrices you want to assemble? X~Y, easy as pie.

Length 2 snippet

```<code>$h
</code>```

This neat accessor returns the series of estimated conditional heteroskedasticity from the last GARCH model. Doesn’t it amaze you that esoteric programming languages have abbreviations for everything? Take that, MATL!

Length 3 snippet

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

This is probably the most frequently used estimation method in all of econometrics. This command estimates a linear regression model describing the relationship between the dependent variable and predictors (like ols wage 0 age education married), returns the full model and generates many useful accessors (like $uhat for residuals, $aic for Akaike information criterion etc.)

Factoid: Its name comes from the famous fairy tale “Hansel and Gretel” by the Grimm brothers, with a modern twist (like Flick-r, Tumbl-r, and similar names, but gret-l omitted the penultimate vowel long before it became mainstream!).

Title: Showcase of Languages

Body:
Notes

This thread is open and unlocked only because the community decided to make an exception. Please do not use this question as evidence that you can ask similar questions here. Please do not create additional showcase questions.

This is no longer a popularity-contest, nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.

This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.

How this works

All answers should include the name of the programming language at the top of the post, prefixed by a #.

Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.

Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.

The snippets do not need to be related. In fact, snippets that are too related may be redundant.

Since this is not a contest, all programming languages are welcome, whenever they were created.

Answers that contain more than a handful of code snippets should use a Stack Snippet to collapse everything except the factoid and one of the snippets.

Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a Stack Snippet for compressing posts, which should mitigate the effect of the 30,000 character limit.

Answers that predate these guidelines should be edited. Please help updating them as needed.

Current answers, sorted alphabetically by language name

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('
' + temp.innerText || temp.textContent + '');}}})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul></code>```

Body:
hansl

hansl is a programming language that is used in the statistical software project gretl since 2001. It resembles a mixture of R, Stata, and C. It operates with datasets, time series, vectors, matrices, and functions. Just as in R, there are dozens of user-written packages for econometrics and data analysis. It is a matrix-oriented interpreted language that is Turing-complete (!). Its fortes are econometric estimation and numerical maximisation, and it can be integrated with R, Ox, Octave, Stata, Python, Julia, and gnuplot.

Length 1 snippet

~

You know how difficult it can be to build matrices from vectors? One can attain the effect by reading the input row-wise, column-wise, or through assembling the mess into a dataset? In hansl, you do not hassle: just write ~ between the two vectors, and voila, you get them bound <s>in tight leather</s> together vertically: A~B. Do you have two matrices you want to assemble? X~Y, easy as pie.

Length 2 snippet

$h

This neat accessor returns the series of estimated conditional heteroskedasticity from the last GARCH model. Doesn’t it amaze you that esoteric programming languages have abbreviations for everything? Take that, MATL!

Length 3 snippet

ols

This is probably the most frequently used estimation method in all of econometrics. This command estimates a linear regression model describing the relationship between the dependent variable and predictors (like ols wage 0 age education married), returns the full model and generates many useful accessors (like $uhat for residuals, $aic for Akaike information criterion etc.)

Factoid: Its name comes from the famous fairy tale “Hansel and Gretel” by the Grimm brothers, with a modern twist (like Flick-r, Tumbl-r, and similar names, but gret-l omitted the penultimate vowel long before it became mainstream!).


问:
Draw a Bumpy String
(Inspired by this challenge.)

Let's say we have a string ABBCBA. We can say that there is a rise between A and B, for B follows A; we can say that there is a run between B and B, for nothing changes; and finally we can say there is a fall between C and B. We can draw a graph like this:

```<code>             A   B   B   C   B   A
Rising:        o       o
Continuing:        o
Falling:                   o   o
</code>```

Without the labels, and minimizing whitespace:

```<code>o o
 o
   oo
</code>```

This is the expected output for input ABBCBA.

You may use any non-whitespace character to replace o in the output. Further, each column may optionally have an extra space between them, like so:

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

The input will consist of at least three characters. The string will consist entirely of uppercase letters, but you may instead use lowercase letters.

Test cases

```<code>TEST CASE
LINE 1
LINE 2
LINE 3

HELLOWORLD
 o oo o
  o
o    o oo

TESTCASE
 oo  o

o  oo o

EXAMINATION
o o o o o

 o o o o o

ZSILENTYOUTH
  o ooo o

oo o   o oo

ABC
oo

ABCBA
oo

  oo
</code>```

答:
Jelly, 11 bytes

```<code>OIṠ“ o ”ṙZY
</code>```

Try it online! or verify all test cases.

How it works

```<code>OIṠ“ o ”ṙZY  Main link. Argument: s (string)

O            Ordinal; replace all characters with their code points.
 I           Increments; compute the differences of consecutive code points.
  Ṡ          Sign function.
   “ o ”ṙ    Rotate that string -1, 0, or 1 unit(s) to the left.
         Z   Zip; transpose rows and columns.
          Y  Join, separating by linefeeds.
</code>```

Title: Draw a Bumpy String

Body:
Jelly, 11 bytes

OIṠ“ o ”ṙZY

Try it online! or verify all test cases.

How it works

OIṠ“ o ”ṙZY  Main link. Argument: s (string)

O            Ordinal; replace all characters with their code points.
 I           Increments; compute the differences of consecutive code points.
  Ṡ          Sign function.
   “ o ”ṙ    Rotate that string -1, 0, or 1 unit(s) to the left.
         Z   Zip; transpose rows and columns.
          Y  Join, separating by linefeeds.


答:
JavaScript (ES6), <s>96</s> <s>95</s> <s>89</s> <s>87</s> 82 bytes

2 bytes saved by using 0 instead of o, as suggested by Conor O'Brien

<s>2</s> 6 bytes saved thanks to ETHproductions

let f =

s=>[1,0,-1].map(k=>s.replace(/./g,(c,i)=>i--?(c>s[i])-(c<s[i])-k&&' ':'')).join`
`

console.log(f("HELLOWORLD"));
console.log(f("EXAMINATION"));```

Title: Draw a Bumpy String

Body:
(Inspired by this challenge.)

Let's say we have a string ABBCBA. We can say that there is a rise between A and B, for B follows A; we can say that there is a run between B and B, for nothing changes; and finally we can say there is a fall between C and B. We can draw a graph like this:

```<code>             A   B   B   C   B   A
Rising:        o       o
Continuing:        o
Falling:                   o   o
</code>```

Without the labels, and minimizing whitespace:

```<code>o o
 o
   oo
</code>```

This is the expected output for input ABBCBA.

You may use any non-whitespace character to replace o in the output. Further, each column may optionally have an extra space between them, like so:

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

The input will consist of at least three characters. The string will consist entirely of uppercase letters, but you may instead use lowercase letters.

Test cases

```<code>TEST CASE
LINE 1
LINE 2
LINE 3

HELLOWORLD
 o oo o
  o
o    o oo

TESTCASE
 oo  o

o  oo o

EXAMINATION
o o o o o

 o o o o o

ZSILENTYOUTH
  o ooo o

oo o   o oo

ABC
oo

ABCBA
oo

  oo
</code>```


答:
CJam, 19 bytes

```<code>l2ew{:-g)S3*0t}%zN*
</code>```

Uses 0 instead of o.

Try it online!

Explanation

```<code>l      e# Read input.
2ew    e# Get all pairs of consecutive letters.
{      e# Map this block over the pairs...
  :-   e#   Compute the difference between the two letters.
  g    e#   Signum. Gives -1 for rises, 1 for falls, 0 otherwise.
  )    e#   Increment. Gives 0 for rises, 2 for falls, 1 otherwise. Call this i.
  S3*  e#   Push a string with three spaces.
  0t   e#   Replace the i'th space (zero-based) with a zero.
}%
z      e# Transpose.
N*     e# Join with linefeeds.
</code>```

Title: Draw a Bumpy String

Body:
CJam, 19 bytes

l2ew{:-g)S3*0t}%zN*

Uses 0 instead of o.

Try it online!

Explanation

l      e# Read input.
2ew    e# Get all pairs of consecutive letters.
{      e# Map this block over the pairs...
  :-   e#   Compute the difference between the two letters.
  g    e#   Signum. Gives -1 for rises, 1 for falls, 0 otherwise.
  )    e#   Increment. Gives 0 for rises, 2 for falls, 1 otherwise. Call this i.
  S3*  e#   Push a string with three spaces.
  0t   e#   Replace the i'th space (zero-based) with a zero.
}%
z      e# Transpose.
N*     e# Join with linefeeds.


问:
Write the fastest Fibonacci
This is yet another challenge about the Fibonacci numbers.

The goal is to compute the 20'000'000th Fibonacii number as fast as possible. The decimal output is about 4 MiB large; it starts with:

28543982899108793710435526490684533031144309848579

The MD5 sum of the output is

fa831ff5dd57a830792d8ded4c24c2cb

You have to submit a program that calculates the number while running and puts the result to stdout. The fastest program, as measured on my own machine, wins.

Here are some additional rules:

You have to submit the source code and a binary runnable on an x64 Linux

The source code must be shorter than 1 MiB, in case of assembly it is also acceptable if only the binary is that small.

You must not include the number to be computed in your binary, even in a disguised fashion. The number has to be calculated at runtime.

My computer has two cores; you are allowed to use parallelism

I took a small implementation from the Internet which runs in about 4.5 seconds. It should not be very difficult to beat this, assuming that you have a good algorithm.

答:
I implemented the matrix multiplication method (from sicp, http://sicp.org.ua/sicp/Exercise1-19) in SBCL but it takes about 30 seconds to finish.  I ported it to C using GMP, and it returns the correct result in about 1.36 seconds on my machine.  It's about as fast as boothby's answer.</p>

```<code>#include <gmp.h>
#include <stdio.h>

int main()
{
  int n = 20000000;

  mpz_t a, b, p, q, psq, qsq, twopq, bq, aq, ap, bp;
  int count = n;

  mpz_init_set_si(a, 1);
  mpz_init_set_si(b, 0);
  mpz_init_set_si(p, 0);
  mpz_init_set_si(q, 1);
  mpz_init(psq);
  mpz_init(qsq);
  mpz_init(twopq);
  mpz_init(bq);
  mpz_init(aq);
  mpz_init(ap);
  mpz_init(bp);

  while(count > 0)
    {
      if ((count % 2) == 0)
        {
          mpz_mul(psq, p, p);
          mpz_mul(qsq, q, q);
          mpz_mul(twopq, p, q);
          mpz_mul_si(twopq, twopq, 2);

          mpz_add(p, psq, qsq);    // p -> (p * p) + (q * q)
          mpz_add(q, twopq, qsq);  // q -> (2 * p * q) + (q * q)
          count/=2;
        }

      else
       {
          mpz_mul(bq, b, q);
          mpz_mul(aq, a, q);
          mpz_mul(ap, a, p);
          mpz_mul(bp, b, p);

          mpz_add(a, bq, aq);      // a -> (b * q) + (a * q)
          mpz_add(a, a, ap);       //              + (a * p)

          mpz_add(b, bp, aq);      // b -> (b * p) + (a * q)

          count--;
       }

    }

  gmp_printf("%Zd\n", b);
  return 0;
}
</code>```

Title: Write the fastest Fibonacci

Body:
I implemented the matrix multiplication method (from sicp, http://sicp.org.ua/sicp/Exercise1-19) in SBCL but it takes about 30 seconds to finish.  I ported it to C using GMP, and it returns the correct result in about 1.36 seconds on my machine.  It's about as fast as boothby's answer.

#include <gmp.h>
#include <stdio.h>

int main()
{
  int n = 20000000;

  mpz_t a, b, p, q, psq, qsq, twopq, bq, aq, ap, bp;
  int count = n;

  mpz_init_set_si(a, 1);
  mpz_init_set_si(b, 0);
  mpz_init_set_si(p, 0);
  mpz_init_set_si(q, 1);
  mpz_init(psq);
  mpz_init(qsq);
  mpz_init(twopq);
  mpz_init(bq);
  mpz_init(aq);
  mpz_init(ap);
  mpz_init(bp);

  while(count > 0)
    {
      if ((count % 2) == 0)
        {
          mpz_mul(psq, p, p);
          mpz_mul(qsq, q, q);
          mpz_mul(twopq, p, q);
          mpz_mul_si(twopq, twopq, 2);

          mpz_add(p, psq, qsq);    // p -> (p * p) + (q * q)
          mpz_add(q, twopq, qsq);  // q -> (2 * p * q) + (q * q)
          count/=2;
        }

      else
       {
          mpz_mul(bq, b, q);
          mpz_mul(aq, a, q);
          mpz_mul(ap, a, p);
          mpz_mul(bp, b, p);

          mpz_add(a, bq, aq);      // a -> (b * q) + (a * q)
          mpz_add(a, a, ap);       //              + (a * p)

          mpz_add(b, bp, aq);      // b -> (b * p) + (a * q)

          count--;
       }

    }

  gmp_printf("%Zd\n", b);
  return 0;
}


答:
MATL, <s>15</s>, 14 bytes

```<code>dZSqtQtQv~79*c
</code>```

Try it online!

Explanation:

They say a picture is worth a thousand words, so here is a beta online interpreter that shows you the value on top of the stack live as it updates. Note that it's still in beta, so you might need to hit run several times.

So first, we call dZS. d gives us the difference between each consecutive element, and ZS gives us the sign (-1, 0, or 1) of each element. So with 'HELLOWORLD' as input, after the first step we'll have:

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

Now, we just use q to decrement this and get:

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

And then two times we duplicate the top of the stack and increment the array (tQ) After this we'll have

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

Now all of the '0's are where we want to output a character. So, we join these three arrays into a matrix (v), and logically negate it (~). Then we multiply every value in the matrix by the ASCII value of 'O', (79*) and display it as a string with c.

Title: Draw a Bumpy String

Body:
MATL, <s>15</s>, 14 bytes

dZSqtQtQv~79*c

Try it online!

Explanation:

They say a picture is worth a thousand words, so here is a beta online interpreter that shows you the value on top of the stack live as it updates. Note that it's still in beta, so you might need to hit run several times.

So first, we call dZS. d gives us the difference between each consecutive element, and ZS gives us the sign (-1, 0, or 1) of each element. So with 'HELLOWORLD' as input, after the first step we'll have:

-1  1  0  1  1 -1  1 -1 -1

Now, we just use q to decrement this and get:

-2  0 -1  0  0 -2  0 -2 -2

And then two times we duplicate the top of the stack and increment the array (tQ) After this we'll have

-2  0 -1  0  0 -2  0 -2 -2
-1  1  0  1  1 -1  1 -1 -1
0   2  1  2  2  0  2  0  0

Now all of the '0's are where we want to output a character. So, we join these three arrays into a matrix (v), and logically negate it (~). Then we multiply every value in the matrix by the ASCII value of 'O', (79*) and display it as a string with c.


答:
Mathematica, <s>93</s> <s>83</s> <s>68</s> 64 bytes

(uses 0, not O)

```<code>Row[Column@Insert[{,},0,2-#]&/@Sign@Differences@LetterNumber@#]&
</code>```

Explanation

```<code>LetterNumber@#
</code>```

Gets the position in the alphabet of each characters of the input.

```<code>Sign@Differences@
</code>```

Takes the difference between each consecutive elements, and takes the sign (-1 for negative/falling, 0 for 0/continuing, 1 for positive/rising)

```<code>Insert[{,},0,2-#]&
</code>```

Inserts a 0 in a list of two Nulls, in the first position if rising, middle if continuing, and third position if falling.

```<code>Row[Column@ ... ]
</code>```

Formats the output.

If the output could look different from the one in the question, the above code could be shortened to 41 bytes:

```<code>ListPlot@*Sign@*Differences@*LetterNumber
</code>```

... which creates something like this (for "ABBCBA"):

Title: Draw a Bumpy String

Body:
Mathematica, <s>93</s> <s>83</s> <s>68</s> 64 bytes

(uses 0, not O)

Row[Column@Insert[{,},0,2-#]&/@Sign@Differences@LetterNumber@#]&

Explanation

LetterNumber@#

Gets the position in the alphabet of each characters of the input.

Sign@Differences@

Takes the difference between each consecutive elements, and takes the sign (-1 for negative/falling, 0 for 0/continuing, 1 for positive/rising)

Insert[{,},0,2-#]&

Inserts a 0 in a list of two Nulls, in the first position if rising, middle if continuing, and third position if falling.

Row[Column@ ... ]

Formats the output.

If the output could look different from the one in the question, the above code could be shortened to 41 bytes:

ListPlot@*Sign@*Differences@*LetterNumber

... which creates something like this (for "ABBCBA"):


答:
PHP, 95 Bytes

```<code>for($b[1]=$b[0]=$b[-1]=" ";($s=$argv[1])[++$i];)$b[$s[$i-1]<=>$s[$i]][$i]=8;echo join("\n",$b);
</code>```

1.Create an array of strings with the index -1 to 1 alternative $b=array_fill(-1,3," ");

2.Fill the strings dependent by the spaceship operator and position of the input

3.Output join the array with a new line

First Way 111 Bytes

```<code>for($o=" ";$i<$l=strlen($s=$argv[1])-1;)$o[$l*(1+($s[$i]<=>$s[$i+1]))+$i++]=8;echo join("\n",str_split($o,$l));
</code>```

Use the spaceship operator <=> spaceship operator

Title: Draw a Bumpy String

Body:
PHP, 95 Bytes

for($b[1]=$b[0]=$b[-1]=" ";($s=$argv[1])[++$i];)$b[$s[$i-1]<=>$s[$i]][$i]=8;echo join("\n",$b);

1.Create an array of strings with the index -1 to 1 alternative $b=array_fill(-1,3," ");

2.Fill the strings dependent by the spaceship operator and position of the input

3.Output join the array with a new line

First Way 111 Bytes

for($o=" ";$i<$l=strlen($s=$argv[1])-1;)$o[$l*(1+($s[$i]<=>$s[$i+1]))+$i++]=8;echo join("\n",str_split($o,$l));

Use the spaceship operator <=> spaceship operator


答:
Haskell, 63 bytes

```<code>f w=[do(e,y)<-zip w$tail w;max" "['o'|b e y]|b<-[(<),(==),(>)]]
</code>```

Returns a list of three strings, representing the lines of output. Contains no subliminal messages.

dianne saved three bytes by using do notation and max instead of a list comprehension and last.

Title: Draw a Bumpy String

Body:
Haskell, 63 bytes

f w=[do(e,y)<-zip w$tail w;max" "['o'|b e y]|b<-[(<),(==),(>)]]

Returns a list of three strings, representing the lines of output. Contains no subliminal messages.

dianne saved three bytes by using do notation and max instead of a list comprehension and last.


答:
Python 2, <s>76</s> 71 bytes

lambda s:[''.join(' o'[cmp(*x)==n]for x in zip(s,s[1:]))for n in-1,0,1]
```

Thanks to @xnor for notifying me that returning a list of strings is allowed.

Test it on Ideone.

Title: Draw a Bumpy String

Body:
Python 2, <s>76</s> 71 bytes

lambda s:[''.join(' o'[cmp(*x)==n]for x in zip(s,s[1:]))for n in-1,0,1]

Thanks to @xnor for notifying me that returning a list of strings is allowed.

Test it on Ideone.


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

```

答:
Turtlèd, <s>490 487</s> 451 bytes

Turtlèd does not support newlines in code... so oneliner fun!

golfed some bytes for not needing to support 0

Golfed some bytes removing useless code, and some other tricks

```<code>?#0#.:l( >;,u,[ :ll[*,l]d],u{*{*r}l' d{ l}[ (*.d)(0'1d)(1'2d)(2'3d)(3'4d)(4'5d)(5'6d)(6'7d)(7'8d)(8'9d)(9.l( .))]u[ r]lu}u2[#[ ;{ l}[ (0u.)(1u'1)(2u'2)(3u'3)(4u'4)(5u'5)(6u'6)(7u'7)(8u'8)(9u'9)dl]ur[ r]l[#[ r]l[ (0'9l( '#;))(1.;)(2'1;)(3'2;)(4'3;)(5'4;)(6'5;)(7'6;)(8'7;)(9'8;)]uuu[*r]{*l}u{*r}'*{*l}:;{ l}[ l]r]' uu[*r]{*r}d]l(*,(*@1)(1@0)'*)u{*' l}:;d[ (0'9l( '#l))(1.d)(2'1d)(3'2d)(4'3d)(5'4d)(6'5d)(7'6d)(8'7d)(9'8d)]r( u[ r]uu)][ [ l]r[ ' r]ul],)
</code>```

Try it online!

I am most certainly not going to explain this with the annotations for each part of the code, at least not right now.

General explanation:

The program writes 0, takes integer input, if it is not one (if it is, it skips the rest of the code), it writes out two lines of asterisks, removing the zero that was written, one to compare for the prime checking, one to turn into a decimal string. It turns the lower one into a decimal string, then moves the decimal string up one. It writes out a single asterisk into a line above the other for each decrement of the upper decimal string. when goes below zero, the program moves the decimal string back up again, and keeps going on the upper line until it either aligns with the lower line, or goes past it. If it aligns, it sets the character variable to 1, if the character variable has not already been set to one. This is because it has no method to distinguish one when testing divisibility, so this makes it so it has to have more than one factor match. If it has been set to one, it sets it to zero. After it has tested all the numbers from n-1 to 1, it cleans up all the mess that it used to test the primality, then writes the character variable, which will be one if prime, else 0

Title: Is this number a prime?

Body:
Turtlèd, <s>490 487</s> 451 bytes

Turtlèd does not support newlines in code... so oneliner fun!

golfed some bytes for not needing to support 0

Golfed some bytes removing useless code, and some other tricks

?#0#.:l( >;,u,[ :ll[*,l]d],u{*{*r}l' d{ l}[ (*.d)(0'1d)(1'2d)(2'3d)(3'4d)(4'5d)(5'6d)(6'7d)(7'8d)(8'9d)(9.l( .))]u[ r]lu}u2[#[ ;{ l}[ (0u.)(1u'1)(2u'2)(3u'3)(4u'4)(5u'5)(6u'6)(7u'7)(8u'8)(9u'9)dl]ur[ r]l[#[ r]l[ (0'9l( '#;))(1.;)(2'1;)(3'2;)(4'3;)(5'4;)(6'5;)(7'6;)(8'7;)(9'8;)]uuu[*r]{*l}u{*r}'*{*l}:;{ l}[ l]r]' uu[*r]{*r}d]l(*,(*@1)(1@0)'*)u{*' l}:;d[ (0'9l( '#l))(1.d)(2'1d)(3'2d)(4'3d)(5'4d)(6'5d)(7'6d)(8'7d)(9'8d)]r( u[ r]uu)][ [ l]r[ ' r]ul],)

<a href="http://turtled.tryitonline.net/#code=PyMwIy46bCggPjssdSxbIDpsbFsqLGxdZF0sdXsqeypyfWwnIGR7IGx9WyAoKi5kKSgwJzFkKSgxJzJkKSgyJzNkKSgzJzRkKSg0JzVkKSg1JzZkKSg2JzdkKSg3JzhkKSg4JzlkKSg5LmwoIC4pKV11WyByXWx1fXUyWyNbIDt7IGx9WyAoMHUuKSgxdScxKSgydScyKSgzdSczKSg0dSc0KSg1dSc1KSg2dSc2KSg3dSc3KSg4dSc4KSg5dSc5KWRsXXVyWyByXWxbI1sgcl1sWyAoMCc5bCggJyM7KSkoMS47KSgyJzE7KSgzJzI7KSg0JzM7KSg1JzQ7KSg2JzU7KSg3JzY7KSg4Jzc7KSg5Jzg7KV11dXVbKnJdeypsfXV7KnJ9Jyp7Kmx9Ojt7IGx9WyBsXXJdJyB1dVsqcl17KnJ9ZF1sKCosKCpAMSkoMUAwKScqKXV7KicgbH06O2RbICgwJzlsKCAnI2wpKSgxLmQpKDInMWQpKDMnMmQpKDQnM2QpKDUnNGQpKDYnNWQpKDcnNmQpKDgnN2QpKDknOGQpXXIoIHVbIHJddXUpXVsgWyBsXXJbICcgcl11bF0sKQ&input=MTM" rel="nofollow">Try it online!

I am most certainly not going to explain this with the annotations for each part of the code, at least not right now.

General explanation:

The program writes 0, takes integer input, if it is not one (if it is, it skips the rest of the code), it writes out two lines of asterisks, removing the zero that was written, one to compare for the prime checking, one to turn into a decimal string. It turns the lower one into a decimal string, then moves the decimal string up one. It writes out a single asterisk into a line above the other for each decrement of the upper decimal string. when goes below zero, the program moves the decimal string back up again, and keeps going on the upper line until it either aligns with the lower line, or goes past it. If it aligns, it sets the character variable to 1, if the character variable has not already been set to one. This is because it has no method to distinguish one when testing divisibility, so this makes it so it has to have more than one factor match. If it has been set to one, it sets it to zero. After it has tested all the numbers from n-1 to 1, it cleans up all the mess that it used to test the primality, then writes the character variable, which will be one if prime, else 0


答:
JavaScript (ES6), 81 bytes

```<code>s=>[s,s,s].map(f=([c,...s],n)=>(p=s[0])?((c<p)-(c>p)+n-1&&" ")+f(s,n):"").join`
`
</code>```

Written from scratch, though it was heavily inspired by @Arnauld's answer. Uses recursion to calculate the contents of each row.

Title: Draw a Bumpy String

Body:
JavaScript (ES6), 81 bytes

s=>[s,s,s].map(f=([c,...s],n)=>(p=s[0])?((c<p)-(c>p)+n-1&&" ")+f(s,n):"").join`
`

Written from scratch, though it was heavily inspired by @Arnauld's answer. Uses recursion to calculate the contents of each row.