问:
Output all strings
Given a set of letters, output all strings made of those letters. (This is Kleene star of the set.) For example, for {'a','b'}, the strings are:

```<code>'', 'a', 'b', 'aa', 'ab', 'ba', 'bb', 'aaa', 'aab', ...
</code>```

Input: A non-empty collection of distinct letters a..z. These may be characters or single-character strings.

Output: All strings in those letters, in any order, without repeats. You may use lists of chars as strings.

This is an infinite list, so you can output it by:

Running forever writing more and more strings. These strings can be written in any flat separated format, meaning that they you can tell where each string ends, but the strings aren't subdivided into groups.

Taking a number n as input and outputting the first n strings in any flat separated format

Yielding each string in turn from a generator object

Producing an infinite object

Be sure that your method eventually produces every string in the output, since it's possible to produce infinitely many strings from the set while never getting to some strings.

You may not output it by

Producing the nth string given n

Providing a membership oracle that decides if a given string belongs to the set

Built-ins are allowed, but I ask voters to give attention to answers that implement the operation themselves over ones that mostly rely on a built-in.

var QUESTION_ID=74273,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/74273/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

```

答:
Cinnamon Gum, 6 bytes

```<code>0000000: 6801 301c e74b                           h.0..K
</code>```

Non-competing because Cinnamon Gum was made after this challenge.

Try it online (TIO limits output).

Explanation

The h puts Cinnamon Gum in format and generate mode. The rest of the string decompresses to [%s]*. The %s is then replaced with the input, and a generator is created that outputs all possible strings matching the regex.

Title: Output all strings

Body:
Cinnamon Gum, 6 bytes

0000000: 6801 301c e74b                           h.0..K

Non-competing because Cinnamon Gum was made after this challenge.

Try it online (TIO limits output).

Explanation

The h puts Cinnamon Gum in format and generate mode. The rest of the string decompresses to [%s]*. The %s is then replaced with the input, and a generator is created that outputs all possible strings matching the regex.


问:
Print out all IPv6 addresses

This reminds me when a few years ago someone uploaded a torrent "Hacker tool: complete list of all IP addresses". This was, of course, just a generated list of the ~4 billion IPv4 addresses, but thousands of "h4xx0rz" downloaded it. Look mum, imahacker!

This was then, but nowadays everybody has switched to IPv6. (Right?)

Your task is to write a program that prints out all IPv6 addresses.

You should write a full program that takes no input and prints IPv6 addresses, one per line, and no other output. Your program must print all 2128 possible addresses, including invalid ones. Each address must be printed exactly once. You may print the addresses in any order.

Each address may be printed in full, with 8 groups of 4 hexadecimal digits separated by colons, e.g.

```<code>2001:0db8:85a3:0000:0000:8a2e:0370:7334
</code>```

You may, at your discretion, use any of the standard abbreviations from RFC 5952:

Leading zeros in a group may be omitted, except that 0 cannot be abbreviated further.

:: may be used at most once per address to abbreviate a sequence of one or more all-zero groups.

The hexadecimal digits may use lowercase or uppercase.

If you achieve the representation recommendation from RFC 5952 (lowercase letters only, shortest possible representation, with :: used as early as possible if there are multiple places where it can be used), you get a -20% bonus.

Due to the size of the output, your program is not expected to finish while we're sitting there. Your program may be interrupted by external means at some point (Ctrl+C, pulling out the power, …). Your program must produce output as a stream, so that after a “reasonable” wait, it will have produced some lines. Basically, building a giant string in memory only to print it at the end is not allowed. Any program that would run out of memory on a “standard” PC is disqualified. (Nonetheless, if your program was left to run for sufficiently long, it must print all IPv6 addresses and then exit.)

(If this condition is a problem for web interpreters that run the program until completion and then let you see the output, and you don't have a hosted interpreter, test your program on a smaller version of the problem, and then carefully adjust it to the full 2128.)

Your score is your program's length in bytes, multiplied by 0.8 if you get the bonus. It's code golf, so the lowest score wins.

答:
Cinnamon Gum, 16 bytes

```<code>0000000: 678b 36d0 b54c d44d 8bc5 455b 8d0c 0500  g.6..L.M..E[....                               .
</code>```

Try it online. (TIO limits output)

Explanation

The g mode puts Cinnamon Gum in generate mode. The rest of the string decompresses to this regex:

```<code>[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]
</code>```

It then creates a generator of all possible strings that match the regex and iterates through it, printing out each one.

Somewhat amusingly, the golfier regex ([0-9a-f]{4,4}:){7,7}[0-9a-f]{4,4} actually compresses to a longer string than the regex above.

ContentLicense: CC BY-SA 3.0

Title: Print out all IPv6 addresses

Body:
Cinnamon Gum, 16 bytes

0000000: 678b 36d0 b54c d44d 8bc5 455b 8d0c 0500  g.6..L.M..E[....                               .

Try it online. (TIO limits output)

Explanation

The g mode puts Cinnamon Gum in generate mode. The rest of the string decompresses to this regex:

[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]:[0-9a-f][0-9a-f][0-9a-f][0-9a-f]

It then creates a generator of all possible strings that match the regex and iterates through it, printing out each one.

Somewhat amusingly, the golfier regex ([0-9a-f]{4,4}:){7,7}[0-9a-f]{4,4} actually compresses to a longer string than the regex above.


问:
Generate a looping array

Introduction

A pointer array is an array L of nonzero integers where 0 ≤ L[i]+i < len(L) holds for all indices i (assuming 0-based indexing).
We say that the index i points to the index L[i]+i.
A pointer array is a loop if the indices form a single cycle of length len(L).
Here are some examples:

[1,2,-1,3] is not a pointer array, because the 3 does not point to an index.

[1,2,-1,-3] is a pointer array, but not a loop, because no index points to the -1.

[2,2,-2,-2] is a pointer array, but not a loop, because the indices form two cycles.

[2,2,-1,-3] is a loop.

Input

Your input is a non-empty list of nonzero integers, in any reasonable format.
It may be unsorted and/or contain duplicates.

Output

Your output shall be a loop that contains all the integers in the input list (and possibly other integers too), counting multiplicities.
They need not occur in the same order as in the input, and the output need not be minimal in any sense.

Example

For the input [2,-4,2], an acceptable output would be [2,2,-1,1,-4].

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Including a couple of example inputs and outputs in your answer is appreciated.

Test cases

These are given in the format input -> some possible output(s).

```<code>[1] -> [1,-1] or [1,1,1,-3]
[2] -> [2,-1,-1] or [1,2,-2,-1]
[-2] -> [1,1,-2] or [3,1,2,-2,-4]
[2,-2] -> [2,-1,1,-2] or [2,-1,2,-2,-1]
[2,2,2] -> [2,-1,2,-2,2,-2,-1] or [2,2,2,2,-3,-5]
[2,-4,2] -> [2,2,-1,1,-4] or [2,5,1,1,1,-4,2,-7,-1]
[3,-1,2,-2,-1,-5] -> [2,3,-1,2,-1,-5] or [3,3,-1,-1,2,2,-1,6,1,1,1,1,-12,-5]
[-2,-2,10,-2,-2,-2] -> [10,-1,1,-2,-2,1,-2,-2,1,-2,-2]
[-15,15,-15] -> [15,-1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,-15,-15]
[1,2,3,4,5] -> [1,2,3,-1,4,-1,5,-1,-1,-9,-1,-1]
</code>```

Title: Generate a looping array

Body:
Jelly, 12 bytes

ż~Ṣ€FxA$;L$U

Try it online!

Background

Consider the pair of integers n, ~n, where n ≥ 0 and ~ denotes bitwise NOT, i.e., ~n = -(n + 1).

By placing n copies of n to the left of n + 1 copies of ~n, if we start traversing the pointer array from the rightmost ~n, we'll traverse all 2n + 1 elements and find ourselves at the left of the leftmost n.

For example, if n = 4:

X  4  4  4  4  -5 -5 -5 -5 -5
                            ^
            ^
                         ^
         ^
                      ^
      ^
                   ^
   ^
                ^
^

For the special case n = 0, the element n itself is repeated 0 times, leaving this:

X -1
   ^
^

For each integer k in the input, we can form a pair n, ~n that contains k by setting n = k if k > 0 and n = ~k if k < 0. This works because ~ is an involution, i.e., ~~k = k.

All that's left to do is chain the generated tuples and prepend their combined lengths, so the leftmost element takes us back to the rightmost one.

Examples

[1] -> [3, 1, -2, -2]
[2] -> [5, 2, 2, -3, -3, -3]
[-2] -> [3, 1, -2, -2]
[2, -2] -> [8, 1, -2, -2, 2, 2, -3, -3, -3]
[2, 2, 2] -> [15, 2, 2, -3, -3, -3, 2, 2, -3, -3, -3, 2, 2, -3, -3, -3]
[2, -4, 2] -> [17, 2, 2, -3, -3, -3, 3, 3, 3, -4, -4, -4, -4, 2, 2, -3, -3, -3]
[3, -1, 2, -2, -1, -5] -> [26, 4, 4, 4, 4, -5, -5, -5, -5, -5, -1, 1, -2, -2, 2, 2, -3, -3, -3, -1, 3, 3, 3, -4, -4, -4, -4]
[-2, -2, 10, -2, -2, -2] -> [36, 1, -2, -2, 1, -2, -2, 1, -2, -2, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, -11, -11, -11, -11, -11, -11, -11, -11, -11, -11, -11, 1, -2, -2, 1, -2, -2]
[-15, 15, -15] -> [89, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, -16, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15, -15]
[1, 2, 3, 4, 5] -> [35, 5, 5, 5, 5, 5, -6, -6, -6, -6, -6, -6, 4, 4, 4, 4, -5, -5, -5, -5, -5, 3, 3, 3, -4, -4, -4, -4, 2, 2, -3, -3, -3, 1, -2, -2]

How it works

ż~Ṣ€FxA$;L$U  Main link. Argument: A (list of integers)

 ~            Yield the bitwise not of each k in A.
ż             Zipwith; pair each k in A with ~k.
  Ṣ€          Sort each pair, yielding [~n, n] with n ≥ 0.
    F         Flatten the list of pairs.
       $      Combine the previous two links into a monadic chain:
      A         Yield the absolute values of all integers in the list.
                |n| = n and |~n| = |-(n + 1)| = n + 1
     x          Repeat each integer m a total of |m| times.
          $   Combine the previous two links into a monadic chain:
         L      Yield the length of the generated list.
        ;       Append the length to the list.
           U  Upend; reverse the generated list.


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

答:
Detour

If you're having difficulty understanding any of these concepts (or, more likely, if I'm explaining them poorly), please feel free to try it yourself on the online interpreter which gives a nice visualization of the data moving around. There is also a TIO site but it doesn't have a cell visualization tool

Summary

Detour is a 2D language I made. While most 2D languages revolve around directing the instruction pointer (think ><>, befunge), this one focuses on redirection of data/objects. Each character in the program translates to a cell. Each cell will either simply pass on its contents (NOP), modify its contents and pass it on (operations such as addition), or redirect its contents (e.g. pointing its contents downward). More on this later.

Factoid

Detour got its name from the "control flow" in the language. I often find myself constructing complex paths to make data travel around the existing data flow, hence "Detour". This is the purest form of spaghetti code.

Length 1 Snippet

:
```

<p><code>:</code> specifies where input is taken. At the start of the program, all input arguments are pushed to the <code>:</code> cell, and then start moving rightward. If no <code>:</code> cell is found, one is inserted by default somewhere (usually at the top or middle).</p>

<h3>Length 2 Snippet</h3>

<pre class="lang-py prettyprint-override"><code>+.
</code>```

This is a program that adds two numbers and outputs the result. The . outputs its contents; that's pretty simple. The more complex part would be +. + is a binary operator which, as you would expect, adds two numbers. The way it adds them, however, is a little weird. In Detour, an operator that takes multiple operands will wait for all its operands to be in the cell before performing the operation.

So let's say a 3 is pushed into a + cell. That 3 will stay in that cell until a second number is also pushed into the cell. After our program does its thing, eventually a 4 finds its way into the same + cell. Now, it has two operands, and will happily add them together and push the result (7) into the next cell.

In this case, the next cell is .. Once the two input arguments get onto the + cell, their result is pushed to ., which outputs the result and exits the program.

Length 3 Snippet

$<<
```

<p>Ok, now it's starting to get interesting. <code><</code> is the decrement operator, so it takes <code>n</code> and pushes <code>n-1</code> to the next cell. <code>$</code> is the duplicate operator, it clones its contents, pushing one to the next cell, while the other skips the immediate cell. The first clone usually will then also hit the second cell.</p>

<p>Example:</p>

<pre class="lang-py prettyprint-override"><code>$<<
4

$<<
 44

$<<
  33

$<<
   23
</code>```

As you can see, $<< yields n-2, n-1. I use this in my fibonacci sequence answer

Length 4 Snippet

[<,]
```

<p>Now it starts to get interesting. <code>[]</code> denotes a loop; that is to say, data will pass through it until it is negative or zero. The body of the loop, <code><,</code> does two things: 1) decrement the number; 2) output it. For example, <code>4[<,]</code> will output <code>3210</code></p>

<h3>Length 5 Snippet</h3>

<pre class="lang-py prettyprint-override"><code>[$<<]
</code>```

Now we get to start combining previous snippets (I know, a bit cheaty, but it's late and I'm tired). Remember how in the length 3 snippet we discussed how n$<< yields (n-2, n-1)? Now imagine if we repeatedly run that process over all generated n until they are all ≤ 0? We get the fibonacci sequence!

Warning: the produced results  will be negative. Take this into account before using this sequence for something that may pertain to black holes

Length 6 Snippet

g>d$G+
```

<p>This calculates, given <code>n</code>, <code>n + (n + 1) / 2</code>. While this is not very useful, it demonstrates an important concept: registers. <code>g</code> stores a value in the register, while <code>G</code> retrieves it. What happens is the number gets stored in <code>g</code>. Then it walks through, getting incremented (<code>></code>), cut in half (<code>d</code>), then duplicated (<code>$</code>). The new value (<code>(n+1)/2</code>) gets added to the value stored in <code>g</code> (<code>n</code>). This yields <code>n + (n+1)/2</code>. Here we start getting into the complicated stuff that's hard to explain with words, feel free to try it in the interpreter.</p>

<p><em>Registers are used in my fibonacci sequence answer (the 30-byte solution) to store the value of <code>sqrt(5)</code>.</em></p>

<h2>Length 7 Snippet</h2>

<pre class="lang-py prettyprint-override"><code><Q.
;d<
</code>```

This is again kind of nonsensical, but demonstrates two key components of Detour.

Control flow (Q)

Recursion (;)

First off, Control Flow.

As mentioned in the intro, control flow in Detour is pretty nonstandard. In Detour, control flow cells manipulate an object's direction or location rather than its value. We have seen some control flow in the form of $ and [].

As in the example, Q conditionally redirects objects: that is, it will move an object depending on the object's value. In Q's case, it will push the object down (put keep it pointed in the same direction) if it is positive, and will push it forward otherwise.

Recursion (;) is another type of control flow. ; will move an object to the start of the program (where the input came through, or more concisely, the location of the : cell).

Combining these two things, we can see what the snippet does

take input n

decrement it

If n >= 0, push it down

halve it, then decrement it and move it back to the start (lines wrap around in Detour making ;>d equivalent to  >d;)

Else, push it forward

output it.

This can be translated to the following Python program:

def f(n):
  n -= 1      # <
  if n <= 0:  # Q
    print(n)    # .
  else:       # Q
    n /= 2      # d
    n -= 1      # <
    f(n)        # ;

f(input())
```

<h2>Length 9 Snippet</h2>

<pre class="lang-py prettyprint-override"><code><Q>S.
;$<
</code>```

This is a recursive fibonacci definition. S sums up all items pushed to it. The bottom uses the fact that objects can wrap around the edges, so ;$< is identical to $<; with a leading space.

Title: Showcase of Languages

Body:
Detour

If you're having difficulty understanding any of these concepts (or, more likely, if I'm explaining them poorly), please feel free to try it yourself on the online interpreter which gives a nice visualization of the data moving around. There is also a TIO site but it doesn't have a cell visualization tool

Summary

Detour is a 2D language I made. While most 2D languages revolve around directing the instruction pointer (think ><>, befunge), this one focuses on redirection of data/objects. Each character in the program translates to a cell. Each cell will either simply pass on its contents (NOP), modify its contents and pass it on (operations such as addition), or redirect its contents (e.g. pointing its contents downward). More on this later.

Factoid

Detour got its name from the "control flow" in the language. I often find myself constructing complex paths to make data travel around the existing data flow, hence "Detour". This is the purest form of spaghetti code.

Length 1 Snippet

:

: specifies where input is taken. At the start of the program, all input arguments are pushed to the : cell, and then start moving rightward. If no : cell is found, one is inserted by default somewhere (usually at the top or middle).

Length 2 Snippet

+.

This is a program that adds two numbers and outputs the result. The . outputs its contents; that's pretty simple. The more complex part would be +. + is a binary operator which, as you would expect, adds two numbers. The way it adds them, however, is a little weird. In Detour, an operator that takes multiple operands will wait for all its operands to be in the cell before performing the operation.

So let's say a 3 is pushed into a + cell. That 3 will stay in that cell until a second number is also pushed into the cell. After our program does its thing, eventually a 4 finds its way into the same + cell. Now, it has two operands, and will happily add them together and push the result (7) into the next cell.

In this case, the next cell is .. Once the two input arguments get onto the + cell, their result is pushed to ., which outputs the result and exits the program.

Length 3 Snippet

$<<

Ok, now it's starting to get interesting. < is the decrement operator, so it takes n and pushes n-1 to the next cell. $ is the duplicate operator, it clones its contents, pushing one to the next cell, while the other skips the immediate cell. The first clone usually will then also hit the second cell.

Example:

$<<
4

$<<
 44

$<<
  33

$<<
   23

As you can see, $<< yields n-2, n-1. I use this in my fibonacci sequence answer

Length 4 Snippet

[<,]

Now it starts to get interesting. [] denotes a loop; that is to say, data will pass through it until it is negative or zero. The body of the loop, <, does two things: 1) decrement the number; 2) output it. For example, 4[<,] will output 3210

Length 5 Snippet

[$<<]

Now we get to start combining previous snippets (I know, a bit cheaty, but it's late and I'm tired). Remember how in the length 3 snippet we discussed how n$<< yields (n-2, n-1)? Now imagine if we repeatedly run that process over all generated n until they are all ≤ 0? We get the fibonacci sequence!

Warning: the produced results  will be negative. Take this into account before using this sequence for something that may pertain to black holes

Length 6 Snippet

g>d$G+

This calculates, given n, n + (n + 1) / 2. While this is not very useful, it demonstrates an important concept: registers. g stores a value in the register, while G retrieves it. What happens is the number gets stored in g. Then it walks through, getting incremented (>), cut in half (d), then duplicated ($). The new value ((n+1)/2) gets added to the value stored in g (n). This yields n + (n+1)/2. Here we start getting into the complicated stuff that's hard to explain with words, feel free to try it in the interpreter.

Registers are used in my fibonacci sequence answer (the 30-byte solution) to store the value of sqrt(5).

Length 7 Snippet

<Q.
;d<

This is again kind of nonsensical, but demonstrates two key components of Detour.

Control flow (Q)

Recursion (;)

First off, Control Flow.

As mentioned in the intro, control flow in Detour is pretty nonstandard. In Detour, control flow cells manipulate an object's direction or location rather than its value. We have seen some control flow in the form of $ and [].

As in the example, Q conditionally redirects objects: that is, it will move an object depending on the object's value. In Q's case, it will push the object down (put keep it pointed in the same direction) if it is positive, and will push it forward otherwise.

Recursion (;) is another type of control flow. ; will move an object to the start of the program (where the input came through, or more concisely, the location of the : cell).

Combining these two things, we can see what the snippet does

take input n

decrement it

If n >= 0, push it down

halve it, then decrement it and move it back to the start (lines wrap around in Detour making ;>d equivalent to  >d;)

Else, push it forward

output it.

This can be translated to the following Python program:

def f(n):
  n -= 1      # <
  if n <= 0:  # Q
    print(n)    # .
  else:       # Q
    n /= 2      # d
    n -= 1      # <
    f(n)        # ;

f(input())

Length 9 Snippet

<Q>S.
;$<

This is a recursive fibonacci definition. S sums up all items pushed to it. The bottom uses the fact that objects can wrap around the edges, so ;$< is identical to $<; with a leading space.


答:
Quetzalcoatl

6 snippet:

{c.I?}.

Makes a block with Code Snippet 4.

5 snippet:

{c.I}

Makes a code block, containing the code c.I. On snippet 8, we will use this.

4 snippet:

c.I?

Same as before, but also does power. Result is xth root of x.

3 snippet:

c.I

Outputs (input, 1/input) because I in 1/.

2 snippet:

c (or any token) + -q compiler flag

<s>Proper</s> quine. -q outputs source instead of running code.

1 snippet:

1 or  (no code) + -n (1 byte).

Like in GolfScript, numbers just push their value. This outputs 1 because Quetzalcoatl implicitly prints the stack. This works for any digit 0-9. Second snippet outputs Quetzalcoatl, because -n outputs Quetzalcoatl.

Interesting fact:

Quetzalcoatl got its name from the Aztec snake god (I wrote it).

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


问:
Cat goes "Meow"

cat goes  "Meow"

We are all familiar with the concept of a cat program. The user types something in, it is echoed back to the user. Easy. But all cat programs I've seen so far have missed one fact: a cat goes "Meow". So your task is to write a program that copies all STDIN to STDOUT UNLESS the input is cat, in which case your program should output cat goes "Meow".

Scoring

This is code-golf, so your score is your byte count, with a few modifiers:

If your program works for any additional animals other than cat (e.g. cow: cow goes "Moo"), for each additional animal: -10

If your program doesn't use the word "cat": -15

If your program responds to fox with "What does the fox say": -25

Animals and sounds that go together:

cow goes moo
duck goes quack
sheep goes baa
bees go buzz
frogs go croak

Anything else on this list is allowed.

Rules

Standard loopholes apply

You must not write anything to STDERR

You can use single quotes/no quotes instead of double quotes.

Leaderboard

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

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

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

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

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

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

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

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

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

var QUESTION_ID=62500;var OVERRIDE_USER=46470;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+)(?=[^\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

```

答:
AWK, 32 - 15 = 17

```<code>/^[c]at$/{$0=$0" goes 'Meow'"}1
</code>```

I think this counts as not using "cat".  Could have saved a couple bytes if "cat" were allowed to be anywhere in the line.

For giggles I also put together one with more animals, but it's not competitive, especially with trying to capture the correct verb to use, but here's what I came up with :)

```<code>{for(;I<split("ca""t,Meow,bees,Buzz,bird,Song,cow,Moo,crow,Caw,dog,Woof,duck,Quack,frogs,Croak,hog,Oink,ox,Low,pig,Oink,sheep,Baa,swan,Cry",a,",");)
m[a[I-1]="'"a[I+=2]"'"}
m[$0]{$0=$0($0~/s$/?" go ":" goes ")m[$0]}
/^fox$/{$0="What does the fox say"}
1
</code>```

Title: Cat goes "Meow"

Body:
AWK, 32 - 15 = 17

/^[c]at$/{$0=$0" goes 'Meow'"}1

I think this counts as not using "cat".  Could have saved a couple bytes if "cat" were allowed to be anywhere in the line.

For giggles I also put together one with more animals, but it's not competitive, especially with trying to capture the correct verb to use, but here's what I came up with :)

{for(;I<split("ca""t,Meow,bees,Buzz,bird,Song,cow,Moo,crow,Caw,dog,Woof,duck,Quack,frogs,Croak,hog,Oink,ox,Low,pig,Oink,sheep,Baa,swan,Cry",a,",");)
m[a[I-1]="'"a[I+=2]"'"}
m[$0]{$0=$0($0~/s$/?" go ":" goes ")m[$0]}
/^fox$/{$0="What does the fox say"}
1


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

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

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

Task

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

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

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

Input

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

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

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

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

Output

Output has to be written to STDOUT or closest alternative.

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

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

Additional rules

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

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

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

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

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

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

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

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

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

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Pyth, 2 bytes

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

Try it here!

Pyth now has implicit input!

Title: Is this number a prime?

Body:
Pyth, 2 bytes

P_

Try it here!

Pyth now has implicit input!


问:
Shorten an already short mathematical expression
For once, I was doing some real work, updating old code, and bumped into an expression that is equivalent to what would be written as πx + ex in good old-fashioned math. I thought it would be possible to write it shorter than it was written in the language I work with (APL), and therefore present this very simple challenge:

Write a function or program that (by any means) accepts zero or more numbers, and returns (by any means) the result of the above expression for x = each of the given numbers with at least 3 significant digits for each result.

If your language does not have π and/or e, use the values 3.142 and 2.718.

Scoring is number of bytes, so preface your answer with # LanguageName, 00 bytes.

Standard loop-holes are not allowed.

Edit: Now the solution I came up with, ○+*, has been found. The original code was (○x)+*x.

答:
Reng v.3.3, 53 bytes

Noncompeting because it postdates the challenge, but hey, not winning any awards for brevity. :P Try it here!

```<code>2²5³*:"G"(%3+i#II*ZA*9+(%2+#E1II0e1+ø
1-)E*(:0eø
$+n~
</code>```

Line 0

Here is a view of the stack in line 0:

```<code>Sequence read | Stack
2²            | 4
5³            | 4 125
*             | 500
:             | 500 500
"G"           | 500 500 71
(             | 500 71 500
%             | 500 0.142
3+            | 500 3.142
i             | 500 3.142 <i>
#I            | 500 3.142     ; I <- i
I             | 500 3.142 <i>
*             | 500 3.142*<i>
ZA            | 500 3.142*<i> 35 10
*             | 500 3.142*<i> 350
9+            | 500 3.142*<i> 359
(             | 3.142*<i> 359 500
%             | 3.142*<i> 0.718
2+            | 3.142*<i> 2.718
#E            | 3.142*<i>     ; E <- 2.718
1II0          | 3.142*<i> 1 <i> <i> 0
e             | 3.142*<i> 1 <i> <i>==0
1+            | 3.142*<i> 1 <i> (<i>==0)+1
</code>```

ø then goes to the next Nth line. When 0 is input, this goes straight to line 2. Otherwise, we go to line 1.

Line 1

```<code>1-)E*(:0eø
</code>```

This multiples E i times, which is e^i. We decrement the counter (initially I), multiply the STOS (our running e power) by E, go back to the counter, and do this (i' is the current counter):

```<code>Sequence read | Stack (partial)
              | i'
:             | i' i'
0             | i' i' 0
e             | i' i'==0
</code>```

ø then does one of two things. If the counter is not 0, then we go to the "next" 0th line, i.e., the beginning of the current line. If it is zero, then 0e yields 1, and goes to the next line.

Line 2

```<code>$+n~
</code>```

$ drops the counter (ON THE FLOOR!). + adds the top two results, n outputs that number, and ~ quits the program.

Case 1: input is 0. The TOS is 1 ("e^0") and the STOS is 0 (pi*0). Adding them yields the correct result.

Case 2: input is not 0. The result is as you might expect.

Body:
Reng v.3.3, 53 bytes

Noncompeting because it postdates the challenge, but hey, not winning any awards for brevity. :P Try it here!

2²5³*:"G"(%3+i#II*ZA*9+(%2+#E1II0e1+ø
1-)E*(:0eø
$+n~

Line 0

Here is a view of the stack in line 0:

Sequence read | Stack
2²            | 4
5³            | 4 125
*             | 500
:             | 500 500
"G"           | 500 500 71
(             | 500 71 500
%             | 500 0.142
3+            | 500 3.142
i             | 500 3.142 <i>
#I            | 500 3.142     ; I <- i
I             | 500 3.142 <i>
*             | 500 3.142*<i>
ZA            | 500 3.142*<i> 35 10
*             | 500 3.142*<i> 350
9+            | 500 3.142*<i> 359
(             | 3.142*<i> 359 500
%             | 3.142*<i> 0.718
2+            | 3.142*<i> 2.718
#E            | 3.142*<i>     ; E <- 2.718
1II0          | 3.142*<i> 1 <i> <i> 0
e             | 3.142*<i> 1 <i> <i>==0
1+            | 3.142*<i> 1 <i> (<i>==0)+1

ø then goes to the next Nth line. When 0 is input, this goes straight to line 2. Otherwise, we go to line 1.

Line 1

1-)E*(:0eø

This multiples E i times, which is e^i. We decrement the counter (initially I), multiply the STOS (our running e power) by E, go back to the counter, and do this (i' is the current counter):

Sequence read | Stack (partial)
              | i'
:             | i' i'
0             | i' i' 0
e             | i' i'==0

ø then does one of two things. If the counter is not 0, then we go to the "next" 0th line, i.e., the beginning of the current line. If it is zero, then 0e yields 1, and goes to the next line.

Line 2

$+n~

$ drops the counter (ON THE FLOOR!). + adds the top two results, n outputs that number, and ~ quits the program.

Case 1: input is 0. The TOS is 1 ("e^0") and the STOS is 0 (pi*0). Adding them yields the correct result.

Case 2: input is not 0. The result is as you might expect.


问:
Create your own Gym Exercise and follow along irl
Let's do an exercise together, shall we? Simply follow the movements of the stickman. What stickman you ask? The one we are about to create!

Make a program that allows for a string-input only containing integers, and outputs the following nine stick-figures with an interval in between:

```<code> @  \@/ |@_ _@| @/   \@ |@| \@\ /@/
/|\  |   |   |   |   |   |   |   |
/ \ / \ / \ / \ /|\ /|\ / \ / \ / \
 1   2   3   4   5   6   7   8   9
</code>```

This will result in an animation, which we can then follow along irl.

Here is an example of the output created when the input is "123245762":

Some rules:

This is tagged code-golf, so shortest code in bytes wins

The input is a string only containing [1-9] with a length potentially varying from 2 to 100 characters **

The animation must be an endless loop

The interval time must be 750 ms

No duplicated adjacent integers are allowed in the input - this also includes the first and last integers of the input (see the seventh and eight test cases) **

** How it fails in case of invalid input is completely up to you, but it should be clear that it fails. It could throw an exception; simply return at the start; reboot your PC; delete it's own source-/compile-code; hack into the military and shoots a rocket to the compiling GPS-location. Your call. EDIT: It's not allowed to simply display a (correct / half) animation as failing input. It must be clear that something is wrong with the input for the failing testcases below. Thanks to @user81655 for bringing this to my attention, hence the edit.

Subrules:

Please post the gif for one of the (non-failing) test cases below in your answer, which you can make very easy with the following program: screentogif.codeplex.com (Any other gif-creating program is also allowed of course.)

Bonus points if you actually do the exercise alongside the animation irl when it's finished. ;)

Correct testcases:

123245762

65

121234346565879879132418791576

Failing testcases:

2 // Too few characters

7282918274959292747383785189478174826894958127476192947512897571298593912374857471978269591928974518735891891723878 // Too much characters

1232405762 // Containing invalid input (the 0)

112212 // Fails because of the 11 and 22 present

1232457621 // Fails because of the starting and leading 1

Body:
JavaScript (ES6), 165 bytes

f=s=>{n=s[0];e.textContent=' @ \\@/|@__@|@/  \\@|@|\\@\\/@/'.substr(n*3-3,3)+(n>1?`
 |
`:`
/|\\
`)+(n<5|n>6?'/ \\':'/|\\');s=s.slice(1)+n;s[0]-n&&setTimeout(f,750,s)}
f("123245762")

<pre id=e>


问:
Print, Increment, Decrement, Alias - Interpret Prindeal
Prindeal (pronounced prin-dee-al) is a new esoteric programming language that only has four commands: print, increment, decrement, and alias. Despite its minimalism, complex mathematical operations can be done in Prindeal by cleverly combining the four commands.

Your task in this code golf challenge is to write the shortest program that can run Prindeal code.

The spec is long but I've tried to make it as clear as possible and I believe that if you make the effort to learn Prindeal you'll find it to be quite elegant!

Intrepreting Prindeal

Preprocessing

Before a Prindeal program can be interpreted these things need to be removed from it in this order:

Anything after a # sign to the end of the line it's on, plus the # itself. (These are comments.)

Trailing whitespace on any line.

Completely empty lines.

For example, the Prindeal program

```<code>p cat #The next line has 7 trailing spaces.
p dog

#p mouse
</code>```

would be preprocessed into

```<code>p cat
p dog
</code>```

From here on we'll assume this preprocessing step has been done.

Variables

We quickly need to define variables before showing how they are used.

Variables (and references to variables) are what are passed into the arguments of Prindeal commands. Variables are always global, so modifications to a variable, no matter where they occur, are reflected everywhere.

Each variable holds a non-negative arbitrary-precision integer (0, 1, 2, 3, ...). Variables do not need to be pre-initialized - they always start with the value 0 the first time they are used or called for.

A variable name may be any non-empty string of alphanumerics and underscores that does not start with a digit - [a-zA-Z_][0-9a-zA-Z_]* in regex. They are case sensitive, so spiny_lumpsuck3r and Spiny_lumpsuck3r are different variables.

Execution

Prindeal is an imperative programming language. When a Prindeal program is run its statements are executed from top to bottom in order and then the program ends.

Every non-indented line in a Prindeal program is a statement that involves the execution of a single command which may or may not take arguments.

Indented lines only occur after alias commands. Specifically, exactly three lines indented with single spaces occur after every alias command  and are considered a part of it. So alias statements are really four lines long. (They could be one line, four is merely more readable.)

Non-alias Statements

With the exception of alias, every statement in a Prindeal program has the form:

```<code>[command name] [argument 1] [argument 2] [argument 3] ...
</code>```

There may be an arbitrary number of arguments (including none at all). Each argument is always a variable or (as we'll see when discussing alias) a reference to a variable.

Once done executing, each statement is flagged as either a failure or success depending on if errors were encountered or not. (This only really matters when we get around to using alias.)

The built-ins print, increment, and decrement are statements with the above form. Here is what they do:

print has command name p and takes one argument. It prints the name of the variable passed in and its value (in decimal) separated by " = ", then a newline. It is always flagged as a success.

For example, the Prindeal program

```<code>p _MyVariable_321
p screaming_hairy_armadillo
</code>```

would output

```<code>_MyVariable_321 = 0
screaming_hairy_armadillo = 0
</code>```

because all variables start at 0. (The spaces before and after the equals sign are required.)

increment has command name i and takes one argument. It increments the value of the variable passed in by 1. It is always flagged as a success..

For example, the program

```<code>i alpaca
p alpaca
i alpaca
p alpaca
</code>```

would output

```<code>alpaca = 1
alpaca = 2
</code>```

Note how alpaca was incremented from 0 to 1 even though it had never been accessed before.

decrement has command name d and takes one argument. If the variable passed in is nonzero its value is decremented by 1 and the statement is flagged as a success. If the variable passed in is 0 then nothing is done and the statement is flagged as a failure.

For example, the program

```<code>i malamute
p malamute
d malamute    #success
p malamute
d malamute    #failure
p malamute
d akita       #failure
p akita
</code>```

would output

```<code>malamute = 1
malamute = 0
malamute = 0
akita = 0
</code>```

Notice that decrementing a variable with value 0 is the only way to produce a failure.

The alias Statement and Aliased Commands

The alias command has a special syntax and is the most powerful because it can be used to define new commands. The alias command name is a and an alias statement has the form:

```<code>a [name of new command]
 [statement A]
 [statement B]
 [statement C]
</code>```

Where each [statement X] represents any non-alias statement, i.e. something with the form [command name] [argument 1] [argument 2] [argument 3] ....

The aliased command's name [name of new command] may be any non-empty string of alphanumerics and underscores that does not start with a digit - [a-zA-Z_][0-9a-zA-Z_]* in regex.

(This is the same set of names as variables but aliased commands and variables are different things used in different places. A variable could be named the same as a command with no ill consequences.)

When an alias statement is executed, a new command is added alongside the original four p i d a commands. The new command can be used as the [command name] in statements and called with arguments just like any other non-alias command.

When a statement with an aliased command name is executed, exactly two more statements from its original alias statement are run:

[statement A] is always run

[statement B] is run if [statement A] was a success

[statement C] is run if [statement A] was a failure

Statements A, B, and C are always run lazily, i.e. they are evaluated on the fly at the time they are run.

When done executing, the aliased command is flagged with the same success or failure flag as statement B or C, whichever one was executed. (alias statements themselves do not need to be flagged since they cannot occur within themselves.)

Alias Example 1

Say we want a new command that increments the variable frog twice. This alias statement achieves it:

```<code>p cat
p dog
</code>```0

Statement A (i frog) is always run and always flagged as a success
  so statement B (i frog) is also always run and the variable frog
  is thus incremented by 2. The increment_frog_twice command is always
  flagged as a success because statement B is always run and B is
  always a success. Statement C (d frog) is never run.

So the output to

```<code>p cat
p dog
</code>```1

would be

```<code>p cat
p dog
</code>```2

We can generalize this example so that any variable can be incremented twice by giving the aliased command an argument.

Within an alias statement the positive integers 1, 2, 3, etc. represent the 1st, 2nd, 3rd, etc. arguments passed into the aliased command. (These arguments might be plain variables or references to variables themselves.) These numbers can only appear within the arguments of statement A, B, and C in an alias statement. It doesn't make sense for them to appear elsewhere.

Alias Example 2

This generalizes the last example - any variable passed into increment_twice will be incremented by 2 because 1 is a reference to the first argument passed in:

```<code>a increment_twice
 i 1
 i 1
 d 1 #never reached
p toad
increment_twice toad
p toad
</code>```

The output of this program would be

```<code>toad = 0
toad = 2
</code>```

We could then alias another command that takes in two arguments and calls increment_twice on both of them:

```<code>a increment_twice
 i 1
 i 1
 d 1 #never reached
a increment_both_twice
 increment_twice 1
 increment_twice 2
 d 1 #never reached
increment_both_twice platypus duck
p platypus
p duck
</code>```

The output here would be

```<code>platypus = 2
duck = 2
</code>```

It's important to realize that aliased commands can be recursive, as this is where their true power lies. For example, we can make a command that sets any variable passed in to 0:

Alias Example 3

The set_to_zero command takes one argument and sets its variable to 0 and is flagged as a success when done:

```<code>a set_to_zero
 d 1
 set_to_zero 1
 i _dummy_
i oryx
i oryx
i oryx
p oryx
set_to_zero oryx
p oryx
</code>```

The output of this program would be

```<code>oryx = 3
oryx = 0
</code>```

What's happening is that when set_to_zero oryx is run, d 1 successfully decrements oryx from from 3 to 2, then set_to_zero 1 is called, which is the same as calling set_to_zero oryx again. So the process repeats until d 1 is a failure, stopping the recursion and increment the _dummy_ variable so a success is produced.

Challenge

Write a program that can execute Prindeal code exactly as described above. Take the Prindeal code in via stdin, the command line, or as a text file. Print the Prindeal program's output to stdout or your language's closest alternative.

Alternatively, you can write a function that takes in the code as a string and prints or returns the output string.

Additionally, you can assume that:

The input Prindeal code will only contain newlines and printable ASCII and (optionally) that it ends with an empty line.

The input code will be valid Prindeal - well formed and syntactically correct.

Running the code will not produce any infinite loops nor any invalid references to commands that have not been defined or arguments that have not been given.

The command names p, i, d, and a will never be aliased over. (You may not assume that variables will not have these names.)

Also, it doesn't matter if your variable values aren't truly arbitrary-precision integers as only numbers less than about 1000 will be tested. It's also alright if you language has recursion limits (such as Python) that more complex Prindeal programs might encounter as long as the test program below works.

Test Program

Here is a large Prindeal program that builds up the operations of addition, multiplication, and exponentiation through the use of dummy variables (starting with _ by convention) and many helper aliases:

```<code>#Command Definitions:
a s             #flag as a success
 i _
 d _
 d _
a f             #flag as a failure
 d _
 d _
 d _
a z             #1 = zero
 d 1
 z 1
 s
a n             #1 = one
 z 1
 i 1
 s
a move          #2 += 1, 1 = zero
 moveH 1 2
 move 1 2
 s
a moveH         #move helper
 d 1
 i 2
 f
a dupe          #2 += 1, 3 += 1, 1 = zero
 dupeH1 1 2 3
 dupe 1 2 3
 s
a dupeH1        #dupe helper
 d 1
 dupeH2 2 3
 f
a dupeH2        #dupe helper
 i 1
 i 2
 s
a copy          #2 = 1
 z 2
 copyH 1 2
 s
a copyH         #copy helper
 dupe 1 2 _copy
 move _copy 1
 s
a addTo         #1 += 2
 copy 2 _add
 #testing comments #
 move _add 1#in weird places # just because #
 s
#it's a g##d idea
###
a add           #1 = 2 + 3
 #its a good idea
 z 1
 addH 1 2 3
 s
##

#
a addH          #add helper
#this is a comment
 addTo 1 2 #as is this
 addTo 1 3
 s
a mul           #1 = 2 * 3
 mulH1 1 2
 mulH2 1 3
 s
a mulH1         #mul helper
 z 1
 copy 2 _mul
 s
a mulH2         #mul helper
 mulH3 1 2
 mulH2 1 2
 s
a mulH3         #mul helper
 d _mul
 addTo 1 2
 f
a mulBy         #1 *= 2
 mul _mulBy 1 2
 copy _mulBy 1
 s
a pow           #1 = 2^3
 powH1 1 3
 powH2 1 2
 s
a powH1         #pow helper
 n 1
 copy 2 _pow
 s
a powH2         #pow helper
 powH3 1 2
 powH2 1 2
 s
a powH3         #pow helper
 d _pow
 mulBy 1 2
 f

#Running Tests:
p A
p B
p C
n A         #A = 1
n B         #B = 1
add C A B   #C = A + B = 1 + 1 = 2
p ____
p A
p B
p C
add B A C   #B = A + C = 1 + 2 = 3
p ____
p A
p B
p C
mul d B C   #d = B * C = 3 * 2 = 6
p ____
p d
mulBy d B   #d = d * B = 6 * 3 = 18
p ____
p d
d A         #A = A - 1 = 1 - 1 = 0
mulBy d A   #d = d * A = 18 * 0 = 0
p ____
p d
pow A C B   #A = C ^ B = 2 ^ 3 = 8
p ____
p A
p B
p C
pow A B C   #A = B ^ C = 3 ^ 2 = 9
p ____
p A
p B
p C
pow C A B   #C = A ^ B = 9 ^ 3 = 729
p ____
p A
p B
p C
</code>```

(If you're playing around with this code be aware that many of the commands will fail if the same variable is given multiple times as an argument. This can easily be fixed but the resulting code is longer.)

Your Prindeal interpreter should be able to produce the exact output:

```<code>[command name] [argument 1] [argument 2] [argument 3] ...
</code>```0

Scoring

The shortest code in bytes wins. Tiebreaker goes to earlier submission.

Brownie Bonus: Write a cool program in Prindeal. I implemented addition and multiplication, can you do subtraction or division?

答:
Python - <s>695</s> 688 bytes

def p(v):print v,"=",w.get(v,0)
def i(v):w[v]=w.get(v,0)+1
def d(v):
 if v in w:
<TAB>w[v]-=1
<TAB>if not w[v]:del w[v]
 else:return 1
def a(n,b,d,h):
 def g(*a):
<TAB>i=1;f=b;s=d;t=h
<TAB>for v in a:v=q+v+q;k=q+j(i)+q;f=c(f,k,v);s=c(s,k,v);t=c(t,k,v);i+=1
<TAB>y=u(t,e)if u(f,e)else u(s,e);i=1;return y
 e[n]=g
q="'";w=x={};u=eval;e={'a':a,'d':d,'i':i,'p':p};import sys;l=sys.stdin.readlines();r="";j=str;c=j.replace;sys.setrecursionlimit(2000)
for h in l:
 h = h.strip()
 if not h:continue
 l = h.split();f=l[0];n=f+"("
 if "#" in f:continue
 for g in l[1:]:
<TAB>b=g.find("#")+1
<TAB>if b:g=g[:b-1]
<TAB>if g:n+="'%s',"%g
<TAB>if b:break
 if x:x-=1;d+='"%s)",'%n
 else:x=(f=="a")*3;d=n
 if not x:d+=")\n";r+=d
exec r in e
```

<TAB> is a literal tab character.

Body:
Python - <s>695</s> 688 bytes

def p(v):print v,"=",w.get(v,0)
def i(v):w[v]=w.get(v,0)+1
def d(v):
 if v in w:
<TAB>w[v]-=1
<TAB>if not w[v]:del w[v]
 else:return 1
def a(n,b,d,h):
 def g(*a):
<TAB>i=1;f=b;s=d;t=h
<TAB>for v in a:v=q+v+q;k=q+j(i)+q;f=c(f,k,v);s=c(s,k,v);t=c(t,k,v);i+=1
<TAB>y=u(t,e)if u(f,e)else u(s,e);i=1;return y
 e[n]=g
q="'";w=x={};u=eval;e={'a':a,'d':d,'i':i,'p':p};import sys;l=sys.stdin.readlines();r="";j=str;c=j.replace;sys.setrecursionlimit(2000)
for h in l:
 h = h.strip()
 if not h:continue
 l = h.split();f=l[0];n=f+"("
 if "#" in f:continue
 for g in l[1:]:
<TAB>b=g.find("#")+1
<TAB>if b:g=g[:b-1]
<TAB>if g:n+="'%s',"%g
<TAB>if b:break
 if x:x-=1;d+='"%s)",'%n
 else:x=(f=="a")*3;d=n
 if not x:d+=")\n";r+=d
exec r in e

<TAB> is a literal tab character.


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

```

答:
Fission, 12 bytes

This is about the shortest I can do at the moment.

```<code>*;R?[   X!@J
</code>```

Try it online

```<code>  R           # Create a atom heading right
   ?          # Set atom mass to input char
    [         # Set direction right
        X     # Clone atom and sending one back
         !    # Print the character
          @   # Swap mass and energy on atom
           J  # Jump (48 for 0, 49 for 1)
*             # Kill program.  Landing spot for 0
 ;            # Kill atom.  Landing spot for 1
</code>```

The length of this program is quite dependent on the landing spots for the Jump command.  There is also a requirement for a bit of space between the [ direction setter and the X linear cloner. Otherwise an extra 0 will get printed.  The input must be either 0 or 1 for this to work.  The input is not validated.

Originally I was going to put up a 18 byte program which is more forgiving on invalid inputs.

```<code>R?@YI@0'L
O0'&[X'1
</code>```

Title: Implement a Truth-Machine

Body:
Fission, 12 bytes

This is about the shortest I can do at the moment.

*;R?[   X!@J

Try it online

  R           # Create a atom heading right
   ?          # Set atom mass to input char
    [         # Set direction right
        X     # Clone atom and sending one back
         !    # Print the character
          @   # Swap mass and energy on atom
           J  # Jump (48 for 0, 49 for 1)
*             # Kill program.  Landing spot for 0
 ;            # Kill atom.  Landing spot for 1

The length of this program is quite dependent on the landing spots for the Jump command.  There is also a requirement for a bit of space between the [ direction setter and the X linear cloner. Otherwise an extra 0 will get printed.  The input must be either 0 or 1 for this to work.  The input is not validated.

Originally I was going to put up a 18 byte program which is more forgiving on invalid inputs.

R?@YI@0'L
O0'&[X'1


问:
Diamondize a Matrix
Given a matrix, output a representation of the matrix where the top left element is on top, the anti-diagonal is the central row and the bottom right element is at the bottom.

For example, consider the following matrix:

```<code>1 2 3
4 5 6
7 8 9
</code>```

The diamond version of this matrix is:

```<code>  1
 4 2
7 5 3
 8 6
  9
</code>```

Inputs and outputs

An input matrix will be given as a list of lists (or anything similar in your language of choice). The output shall be a list of lists as well.

The matrices will only contain positive integers.

The input matrix will not necessarily be square.

The input matrix will be at least 1×1.

Test Cases

```<code>Input:  [[1]]
Output: [[1]]

Input:  [[1,2],[3,4]]
Output: [[1],[3,2],[4]]

Input:  [[1,2,3],[4,5,6]]
Output: [[1],[4,2],[5,3],[6]]

Input:  [[11,2,5],[3,99,3],[4,8,15],[16,23,42]]
Output: [[11],[3,2],[4,99,5],[16,8,3],[23,15],[42]]
</code>```

Scoring

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

答:
Octave, 77 bytes

With a little abuse of the accumarray function:

```<code>@(M)char(accumarray(((1:size(M,1))+(0:size(M,2)-1)')(:),M(:),[],@(x){num2str(x')}))
</code>```

This defines an anonymous function. To use it, assign to a varible or use ans.

Input is the matrix with : as row separator. Output is a cell array containing an array for each row (Octave's equivalent to jagged arrays). This is displayed by Octave showing the indices of the cell array and the contents of each cell. Try it here.

To display the result separated by spaces and newlines only: 83 bytes

```<code>@(M)char(accumarray(((1:size(M,1))+(0:size(M,2)-1)')(:),M(:),[],@(x){num2str(x')}))
</code>```

You can also try it here.

Title: Diamondize a Matrix

Body:
Octave, 77 bytes

With a little abuse of the accumarray function:

@(M)char(accumarray(((1:size(M,1))+(0:size(M,2)-1)')(:),M(:),[],@(x){num2str(x')}))

This defines an anonymous function. To use it, assign to a varible or use ans.

Input is the matrix with : as row separator. Output is a cell array containing an array for each row (Octave's equivalent to jagged arrays). This is displayed by Octave showing the indices of the cell array and the contents of each cell. Try it here.

To display the result separated by spaces and newlines only: 83 bytes

@(M)char(accumarray(((1:size(M,1))+(0:size(M,2)-1)')(:),M(:),[],@(x){num2str(x')}))

You can also try it here.


答:
Racket, 31 bytes

```<code>(require math)(λ(n)(prime? n))
</code>```

A standard library has a function for it. If we want to keep the import but write our own, we could do this for 51 bytes:

```<code>(require math)(λ(n)(equal?(list 1 n)(divisors n)))
</code>```

On the other hand, if builtins were disallowed, for <s>64</s> 55 bytes, thanks to @MatthewButterick, we can write our own:

```<code>(λ(n)(=(count(λ(i)(=(modulo n(+ i 1))0))(range n))2))
</code>```

Old one, for 64:

```<code>(λ(n)(equal?'(1)(filter(λ(i)(zero?(modulo n i)))(range 1 n))))
</code>```

Title: Is this number a prime?

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

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

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

Task

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

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

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

Input

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

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

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

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

Output

Output has to be written to STDOUT or closest alternative.

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

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

Additional rules

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

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

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

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

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

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

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

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

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

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
Racket, 31 bytes

(require math)(λ(n)(prime? n))

A standard library has a function for it. If we want to keep the import but write our own, we could do this for 51 bytes:

(require math)(λ(n)(equal?(list 1 n)(divisors n)))

On the other hand, if builtins were disallowed, for <s>64</s> 55 bytes, thanks to @MatthewButterick, we can write our own:

(λ(n)(=(count(λ(i)(=(modulo n(+ i 1))0))(range n))2))

Old one, for 64:

(λ(n)(equal?'(1)(filter(λ(i)(zero?(modulo n i)))(range 1 n))))


问:
Palindromizing the strings

Introduction

For the ones who don't know, a palindrome is when a string is equal to the string backwards (with exception to interpunction, spaces, etc.). An example of a palindrome is:

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

If you reverse this, you will end up with:

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

Which is the same. Therefore, we call this a palindrome. To palindromize things, let's take a look at an example of a string:

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

This is not a palindrome. To palindromize this, we need to merge the reversed string into the initial string at the right of the initial string, leaving both versions intact. The shorter, the better.

The first thing we can try is the following:

```<code>adbcb
bcbda
^^ ^^
</code>```

Not all characters match, so this is not the right position for the reversed string. We go one step to the right:

```<code>adbcb
 bcbda
 ^^^^
</code>```

This also doesn't match all characters. We go another step to the right:

```<code>adbcb
  bcbda
</code>```

This time, all characters match. We can merge both string leaving the intact. The final result is:

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

This is the palindromized string.

The Task

Given a string (with at least one character) containing only lowercase letters (or uppercase, if that fits better), output the palindromized string.

Test cases

```<code>Input     Output

abcb      abcba
hello     hellolleh
bonobo    bonobonob
radar     radar
hex       hexeh
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

答:
Seriously, 34 bytes

```<code>╩╜lur`╜╨"Σ╜+;;R=*"£M`MΣ;░p╜;;R=I.
</code>```

The last character is a non-breaking space (ASCII 127 or 0x7F).

Try it online!

Explanation:

```<code>╩╜lur`╜╨"Σ╜+;;R=*"£M`MΣ;░p╜;;R=I.<NBSP>
╩                                        push inputs to registers (call the value in register 0 "s" for this explanation)
 ╜lur                                    push range(0, len(s)+1)
     `              `M                   map (for i in a):
      ╜╨                                   push all i-length permutations of s
        "        "£M                       map (for k in perms):
         Σ╜+                                 push s+''.join(k) (call it p)
            ;;R=                             palindrome test
                *                            multiply (push p if palindrome else '')
                      Σ                  summation (flatten lists into list of strings)
                       ;░                filter truthy values
                         p               pop first element (guaranteed to be shortest, call it x)
                          ╜;;R=I         pop x, push s if s is palindromic else x
                                .<NBSP>  print and quit
</code>```

Title: Palindromizing the strings

Body:
Seriously, 34 bytes

╩╜lur`╜╨"Σ╜+;;R=*"£M`MΣ;░p╜;;R=I.

The last character is a non-breaking space (ASCII 127 or 0x7F).

Try it online!

Explanation:

╩╜lur`╜╨"Σ╜+;;R=*"£M`MΣ;░p╜;;R=I.<NBSP>
╩                                        push inputs to registers (call the value in register 0 "s" for this explanation)
 ╜lur                                    push range(0, len(s)+1)
     `              `M                   map (for i in a):
      ╜╨                                   push all i-length permutations of s
        "        "£M                       map (for k in perms):
         Σ╜+                                 push s+''.join(k) (call it p)
            ;;R=                             palindrome test
                *                            multiply (push p if palindrome else '')
                      Σ                  summation (flatten lists into list of strings)
                       ;░                filter truthy values
                         p               pop first element (guaranteed to be shortest, call it x)
                          ╜;;R=I         pop x, push s if s is palindromic else x
                                .<NBSP>  print and quit


答:
Python, 128 bytes (numpy)

```<code>(lambda A: (lambda A,S:[[A[U][I-U] for U in range(min(S[1]-1,I),max(I-S[0]+1,0)-1,-1)] for I in range(S[1]+S[0]-1)])(A,A.shape))
</code>```

Title: Diamondize a Matrix

Body:
Given a matrix, output a representation of the matrix where the top left element is on top, the anti-diagonal is the central row and the bottom right element is at the bottom.

For example, consider the following matrix:

```<code>1 2 3
4 5 6
7 8 9
</code>```

The diamond version of this matrix is:

```<code>  1
 4 2
7 5 3
 8 6
  9
</code>```

Inputs and outputs

An input matrix will be given as a list of lists (or anything similar in your language of choice). The output shall be a list of lists as well.

The matrices will only contain positive integers.

The input matrix will not necessarily be square.

The input matrix will be at least 1×1.

Test Cases

```<code>Input:  [[1]]
Output: [[1]]

Input:  [[1,2],[3,4]]
Output: [[1],[3,2],[4]]

Input:  [[1,2,3],[4,5,6]]
Output: [[1],[4,2],[5,3],[6]]

Input:  [[11,2,5],[3,99,3],[4,8,15],[16,23,42]]
Output: [[11],[3,2],[4,99,5],[16,8,3],[23,15],[42]]
</code>```

Scoring

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

Body:
Python, 128 bytes (numpy)

(lambda A: (lambda A,S:[[A[U][I-U] for U in range(min(S[1]-1,I),max(I-S[0]+1,0)-1,-1)] for I in range(S[1]+S[0]-1)])(A,A.shape))


答:
Octave, <s>63</s> 62 bytes

Removed one byte thanks to <s>@DonMue...</s> @LuisMendo!

```<code>@(a)cellfun(@(x)x(x>0)',num2cell(spdiags(flipud(a)),1),'un',0)
</code>```

I went the boring route and munged the antidiagonals.

Sample run on ideone.

Title: Diamondize a Matrix

Body:
Octave, <s>63</s> 62 bytes

Removed one byte thanks to <s>@DonMue...</s> @LuisMendo!

@(a)cellfun(@(x)x(x>0)',num2cell(spdiags(flipud(a)),1),'un',0)

I went the boring route and munged the antidiagonals.

Sample run on ideone.


答:
C#, 202 bytes

I tried.

```<code>class P{static void Main(string[]a){string s=Console.ReadLine(),o=new string(s.Reverse().ToArray()),w=s;for(int i=0;w!=new string(w.Reverse().ToArray());){w=s.Substring(0,i++)+o;}Console.WriteLine(w);}}
</code>```

Ungolfed:

```<code>class P
{
    static void Main(string[] a)
    {
        string s = Console.ReadLine(), o = new string(s.Reverse().ToArray()), w = s;
        for(int i = 0; w!=new string(w.Reverse().ToArray());)
        {
            w = s.Substring(0, i++) + o;
        }
        Console.WriteLine(w);
        Console.ReadKey();
    }

}
</code>```

Can anyone provide me with any ideas to group the two calls to .Reverse().ToArray() ? A separate method is more bytes.

Title: Palindromizing the strings

Body:
Introduction

For the ones who don't know, a palindrome is when a string is equal to the string backwards (with exception to interpunction, spaces, etc.). An example of a palindrome is:

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

If you reverse this, you will end up with:

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

Which is the same. Therefore, we call this a palindrome. To palindromize things, let's take a look at an example of a string:

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

This is not a palindrome. To palindromize this, we need to merge the reversed string into the initial string at the right of the initial string, leaving both versions intact. The shorter, the better.

The first thing we can try is the following:

```<code>adbcb
bcbda
^^ ^^
</code>```

Not all characters match, so this is not the right position for the reversed string. We go one step to the right:

```<code>adbcb
 bcbda
 ^^^^
</code>```

This also doesn't match all characters. We go another step to the right:

```<code>adbcb
  bcbda
</code>```

This time, all characters match. We can merge both string leaving the intact. The final result is:

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

This is the palindromized string.

The Task

Given a string (with at least one character) containing only lowercase letters (or uppercase, if that fits better), output the palindromized string.

Test cases

```<code>Input     Output

abcb      abcba
hello     hellolleh
bonobo    bonobonob
radar     radar
hex       hexeh
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

Body:
C#, 202 bytes

I tried.

class P{static void Main(string[]a){string s=Console.ReadLine(),o=new string(s.Reverse().ToArray()),w=s;for(int i=0;w!=new string(w.Reverse().ToArray());){w=s.Substring(0,i++)+o;}Console.WriteLine(w);}}

Ungolfed:

class P
{
    static void Main(string[] a)
    {
        string s = Console.ReadLine(), o = new string(s.Reverse().ToArray()), w = s;
        for(int i = 0; w!=new string(w.Reverse().ToArray());)
        {
            w = s.Substring(0, i++) + o;
        }
        Console.WriteLine(w);
        Console.ReadKey();
    }

}

Can anyone provide me with any ideas to group the two calls to .Reverse().ToArray() ? A separate method is more bytes.


问:
Stretch the word
The input is a word of lowercase letters not separated by whitespace. A newline at the end is optional.

The same word must be output in a modified version: For each character, double it the second time it appears in the original word, triple it the third time etc.

Example input:

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

Example output:

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

Standard I/O rules apply. The shortest code in bytes wins.

Tests provided by @Neil :

```<code>tutu -> tuttuu
queue -> queuuee
bookkeeper -> boookkkeeepeeer
repetitive -> repeetittiiveee
uncopyrightables -> uncopyrightables
abracadabra -> abraacaaadaaaabbrraaaaa
mississippi -> misssiisssssssiiipppiiii
</code>```

答:
Go, 142 bytes

No awards, but a neat exercise.

```<code>import(."fmt"
."strings")
func f(s string){m:=map[rune]int{}
for _,c:=range s{if _,ok:=m[c];!ok{m[c]=1}
Print(Repeat(string(c),m[c]))
m[c]++}}
</code>```

You can save 1 byte by changing for _,c to for i,c and changing string(c) to s[i:i+1], but then it works only with ASCII.

Title: Stretch the word

Body:
Go, 142 bytes

No awards, but a neat exercise.

import(."fmt"
."strings")
func f(s string){m:=map[rune]int{}
for _,c:=range s{if _,ok:=m[c];!ok{m[c]=1}
Print(Repeat(string(c),m[c]))
m[c]++}}

You can save 1 byte by changing for _,c to for i,c and changing string(c) to s[i:i+1], but then it works only with ASCII.


问:
Snakify a String
A snakified string looks like this:

```<code>T AnE eOf ifi ing
h s x l A k e r
isI amp Sna dSt
</code>```

Your Task

Take a string s and a size n, then output the snakified string. The inputs ThisIsAnExampleOfaSnakifiedString and 3 would produce the example above.

Specifications

s will only contain ASCII characters between code points 33 and 126 inclusive (no spaces or newlines).

s will be between 1 and 100 characters long.

n is an integer representing the size of each output string segment. Each line of characters (up/down or left/right) that make up the curves in the "snake" is n characters long. See the test cases for examples.

n will be between 3 and 10 inclusive.

The output string always starts pointing downwards.

Trailing spaces on each line are allowed.

Trailing newlines at the end of the output are also allowed.

Leading spaces are not allowed.

code-golf means shortest code in bytes wins.

Test Cases

```<code>a 3

a

----------

Hello,World! 3

H Wor
e , l
llo d!

----------

ProgrammingPuzzlesAndCodeGolf 4

P  ngPu  Code
r  i  z  d  G
o  m  z  n  o
gram  lesA  lf

----------

IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot. 5

I   gramW   tStri   100Ch   gBeca   CaseW   DoesN
H   o   o   u   n   e   a   n   u   t   i   t   o
o   r   r   p   g   r   r   o   s   s   l   I   t
p   P   k   n   s   A   a   L   e   e   l   f   .
eYour   sForI   Which   cters   ThisT   FailI

----------

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 10

!        <=>?@ABCDE        `abcdefghi
"        ;        F        _        j
#        :        G        ^        k
$        9        H        ]        l
%        8        I        \        m
&        7        J        [        n
'        6        K        Z        o        ~
(        5        L        Y        p        }
)        4        M        X        q        |
*+,-./0123        NOPQRSTUVW        rstuvwxyz{
</code>```

答:
JavaScript (ES6), 122 bytes

document.write("```"+(

// --- Solution ---
s=>n=>[...s].map((c,i)=>(a[p]=c,p+=[l+1,1,-l-1,1][i/n%4|0]),p=0,a=[...(" ".repeat(l=s.length)+`
`).repeat(n--)])&&a.join``
// ----------------

)("IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.")(5))</code>```

Same algorithm as @LevelRiverSt's answer.

Title: Snakify a String

Body:
JavaScript (ES6), 122 bytes

document.write("<pre>"+(

// --- Solution ---
s=>n=>[...s].map((c,i)=>(a[p]=c,p+=[l+1,1,-l-1,1][i/n%4|0]),p=0,a=[...(" ".repeat(l=s.length)+`
`).repeat(n--)])&&a.join``
// ----------------

)("IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.")(5))

Same algorithm as @LevelRiverSt's answer.


问:
Find the first word starting with each letter
Given a string, find the first word starting with each letter (case insensitive).

Sample

Using Ferulas flourish in gorgeous gardens. as input:

```<code>"Ferulas flourish in gorgeous gardens."
 ^^^^^^^          ^^ ^^^^^^^^
 |                |  |
 |                |  --> is the first word starting with `g`
 |                --> is the first word starting with `i`
 --> is the first word starting with `f`
</code>```

Then, the output for this sample should be the matched words joined by one single space:

```<code>"Ferulas in gorgeous"
</code>```

Challenge

Both input and output must be a string representation, or the closest alternative in your language.

Program or function allowed.

You can consider a word being at least one of: lowercase or uppercase letters, digits, underscore.

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

Another samples:

```<code>input: "Take all first words for each letter... this is a test"
output: "Take all first words each letter is"
</code>```

```<code>input: "Look ^_^ .... There are 3 little dogs :)"
output: "Look _ There are 3 dogs"
</code>```

```<code>input: "...maybe some day 1 plus 2 plus 20 could result in 3"
output: "maybe some day 1 plus 2 could result in 3"
</code>```

答:
Retina, 45 bytes

```
i`\b((\w)\w*)\b(?&lt=\b\2\w*\b.+)

\W+

^ | $

```

Simply uses a single regex to remove later words starting with the same \w character (case insensitive  with the i option), converts runs of \W to a single space, then removes any leading/trailing space from the result.

Try it online!

Edit: See @Kobi's answer for a shorter version using M!`

Body:
Retina, 45 bytes

i`\b((\w)\w*)\b(?&lt=\b\2\w*\b.+)

\W+

^ | $

Simply uses a single regex to remove later words starting with the same \w character (case insensitive  with the i option), converts runs of \W to a single space, then removes any leading/trailing space from the result.

Try it online!

Edit: See @Kobi's answer for a shorter version using M!`