问:
Transform a matrix
Write a program or function where a matrix A (maximum value of dimensions of the matrix is 100) is transformed to a new matrix B. Each element of the new matrix B is the sum of the positive neighbors of the corresponding element of the matrix A.

Only neighbors in the four orthogonal directions are considered, and the edges do not wrap around.

Example input:

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

Output:

```<code> 6  4  2
 1  6 13
 5 12 10
 2 11 12
</code>```

Rules:

As input use integers.

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

答:
MATL, 9 bytes

```<code>t0>*1Y6Z+
</code>```

Try it online!

Explanation

The input matrix is multplied by an appropriate mask to make negative values equal to 0. Then a 2D convolution is applied to compute the sum of neighbours of each entry.

```<code>t     % Take input implicitly: 2D array. Duplicate
0>    % Is each entry positive? This gives a mask of positive values
*     % Multiply: set negative values of input array to zero
1Y6   % Predefined literal: [0 1 0; 1 0 1; 0 1 0]
Z+    % 2D convolution preserving size. Implicitly display
</code>```

Title: Transform a matrix

Body:
MATL, 9 bytes

t0>*1Y6Z+

Try it online!

Explanation

The input matrix is multplied by an appropriate mask to make negative values equal to 0. Then a 2D convolution is applied to compute the sum of neighbours of each entry.

t     % Take input implicitly: 2D array. Duplicate
0>    % Is each entry positive? This gives a mask of positive values
*     % Multiply: set negative values of input array to zero
1Y6   % Predefined literal: [0 1 0; 1 0 1; 0 1 0]
Z+    % 2D convolution preserving size. Implicitly display


问:
Find the program that prints this integer sequence (Cops' thread)
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

答:
LiveCode, 35 bytes, cracked

```<code>_un_t_on oeis _
    ___u___n__
En__oeis
</code>```

oeis (2)==2

oeis (0)==0

ContentLicense: CC BY-SA 3.0

Body:
LiveCode, 35 bytes, cracked

_un_t_on oeis _
    ___u___n__
En__oeis

oeis (2)==2

oeis (0)==0


问:
Generate a parity bit
A parity bit, is one of the simplest forms of a checksum. First, you have to pick the parity, even or odd. Let's say we pick even. Now, we need a message to transmit. Let's say our message is "Foo". This is written in binary as:

```<code>01000110 01101111 01101111
</code>```

Now, we count the total number of 1's in there, which is 15. Since 15 is an odd number, we must add one extra bit to the end of our message, and we will now have an even number of 'on' bits. This last added bit is known as the "parity bit". If we had picked an odd parity for our checksum, we would have to add an extra '0' so that the number of on bits remains odd.

The challenge:

You must write a program or function that determines what the correct parity bit for a string is. Your program must take two inputs:

A string, s. This is the message that the checksum will be calculated on. This will be restricted to the 95 printable ASCII characters.

A character or single character string p, that will either be e for even parity, or o for odd parity.

and produce a truthy-falsey value representing the correct parity bit. Truthy if it's a 1, and falsey if it's a 0.

Builtins that count the number of "on" bits in a string or character are not allowed. For example, a function f that does this: f('a') == 3 or f('foo') == 16 is banned. Anything else, such as base conversion, is fair game.

Test IO:

```<code>(without the quotes)
s: "0"
p: 'e'
output: 0

s: "Foo"
p: 'e'
output: 1

s: "Hello World!"
p: 'o'
output: 0

s: "Alex is right"
p: 'e'
output: 1

s: "Programming Puzzles and Code-Golf"
p: 'e'
output: 0

s: "Programming Puzzles and Code-Golf"
p: 'o'
output: 1
</code>```

This is codegolf, so standard loopholes apply, and the shortest answer in bytes wins.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Factor, 85 bytes

For some reason I couldn't wrap my head around this one until a few minutes ago, when I simplified (and maybe shortened?) the code.

```<code>[ "e" = [ even? ] [ odd? ] ? [ [ >bin ] { } map-as concat [ 49 = ] count ] dip call ]
</code>```

? is like a ternary operator: it tests the truthiness of the third stack item, and either selects the true value or the false value.

It's roughly equivalent to the following C-like pseduocode:

```<code>void* parity_tester_function = strcmp(p, "e") ? (void *) even?  // it's a function pointer (I think)
                                              : (void *) odd? ;
</code>```

The rest of the code is pretty simple:

```<code>[                       ! to count a string's set bits:
    [ >bin ] { } map-as ! get the binary of each character, and map as an array, because you can't have stringy data nested in another string (that's called a type error)
    concat              ! { "a" "B" } concat -> "aB"
    [ 49 = ] count      ! count items in the resulting string which match this condition (in this case, the condition we're testing is whether the character has the same code point as "1")
] dip                   ! take the above function pointer off the stack, apply this anonymous function to the now-top of the stack, then restore the value after the quotation finishes.
                        ! in other words, apply this quotation to the second-to-top item on the stack
call                    ! remember that conditionally chosen function pointer? it's on the top of the stack, and the number of sets bits is second.
                        ! we're gonna call either odd? or even? on the number of set bits, and return the same thing it does.
</code>```

Title: Generate a parity bit

Body:
Factor, 85 bytes

For some reason I couldn't wrap my head around this one until a few minutes ago, when I simplified (and maybe shortened?) the code.

[ "e" = [ even? ] [ odd? ] ? [ [ >bin ] { } map-as concat [ 49 = ] count ] dip call ]

? is like a ternary operator: it tests the truthiness of the third stack item, and either selects the true value or the false value.

It's roughly equivalent to the following C-like pseduocode:

void* parity_tester_function = strcmp(p, "e") ? (void *) even?  // it's a function pointer (I think)
                                              : (void *) odd? ;

The rest of the code is pretty simple:

[                       ! to count a string's set bits:
    [ >bin ] { } map-as ! get the binary of each character, and map as an array, because you can't have stringy data nested in another string (that's called a type error)
    concat              ! { "a" "B" } concat -> "aB"
    [ 49 = ] count      ! count items in the resulting string which match this condition (in this case, the condition we're testing is whether the character has the same code point as "1")
] dip                   ! take the above function pointer off the stack, apply this anonymous function to the now-top of the stack, then restore the value after the quotation finishes.
                        ! in other words, apply this quotation to the second-to-top item on the stack
call                    ! remember that conditionally chosen function pointer? it's on the top of the stack, and the number of sets bits is second.
                        ! we're gonna call either odd? or even? on the number of set bits, and return the same thing it does.


答:
05AB1E, 1 byte, Cracked

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

_ denotes hidden code.

```<code>f(1) == 1
f(18) == 6
</code>```

Title: Find the program that prints this integer sequence (Cops' thread)

Body:
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

Body:
05AB1E, 1 byte, Cracked

_

_ denotes hidden code.

f(1) == 1
f(18) == 6


答:
IA-32 machine code, 15 bytes

Hexdump:

```<code>0f b6 c2 40 32 01 0f 9b c0 3a 21 41 72 f6 c3
</code>```

Assembly code:

```<code>    movzx eax, dl;
    inc eax;
repeat:
    xor al, [ecx];
    setpo al;
    cmp ah, [ecx];
    inc ecx;
    jb repeat;
    ret;
</code>```

This is a function that receives its first argument (string) in ecx and second argument (char) in dl. It returns the result in eax, so it's compatible with the fastcall calling convention.

This code bends the rules when it uses the setpo instruction:

Builtins that count the number of "on" bits in a string or character are not allowed

This instruction sets al to the parity bit calculated by the previous instruction - so I have these two nitpicks on the rules:

It doesn't count the number of "on" bits - it calculates the parity bit directly!

Technically, it's the previous instruction (xor) that calculates the parity bit. The setpo instruction only moves it to the al register.

These semantic details out of the way, here is the explanation on what the code does.

The representations of the characters are:

```<code>'e' = 01100101
'o' = 01101111
</code>```

If we add 1 to them, they happen to have just the right parity:

```<code>'e' + 1 = 01100110 (odd parity)
'o' + 1 = 01110000 (even parity)
</code>```

So we XOR all the characters of the string, initializing al to these values, which gives the answer.

The first instruction is movzx eax, dl instead of the more obvious (and shorter) mov al, dl, because I want to have the number 0 in a register (ah in this case) in order to be able to compare it in the right order (0, [ecx] rather than [ecx], 0).

Title: Generate a parity bit

Body:
A parity bit, is one of the simplest forms of a checksum. First, you have to pick the parity, even or odd. Let's say we pick even. Now, we need a message to transmit. Let's say our message is "Foo". This is written in binary as:

```<code>01000110 01101111 01101111
</code>```

Now, we count the total number of 1's in there, which is 15. Since 15 is an odd number, we must add one extra bit to the end of our message, and we will now have an even number of 'on' bits. This last added bit is known as the "parity bit". If we had picked an odd parity for our checksum, we would have to add an extra '0' so that the number of on bits remains odd.

The challenge:

You must write a program or function that determines what the correct parity bit for a string is. Your program must take two inputs:

A string, s. This is the message that the checksum will be calculated on. This will be restricted to the 95 printable ASCII characters.

A character or single character string p, that will either be e for even parity, or o for odd parity.

and produce a truthy-falsey value representing the correct parity bit. Truthy if it's a 1, and falsey if it's a 0.

Builtins that count the number of "on" bits in a string or character are not allowed. For example, a function f that does this: f('a') == 3 or f('foo') == 16 is banned. Anything else, such as base conversion, is fair game.

Test IO:

```<code>(without the quotes)
s: "0"
p: 'e'
output: 0

s: "Foo"
p: 'e'
output: 1

s: "Hello World!"
p: 'o'
output: 0

s: "Alex is right"
p: 'e'
output: 1

s: "Programming Puzzles and Code-Golf"
p: 'e'
output: 0

s: "Programming Puzzles and Code-Golf"
p: 'o'
output: 1
</code>```

This is codegolf, so standard loopholes apply, and the shortest answer in bytes wins.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
IA-32 machine code, 15 bytes

Hexdump:

0f b6 c2 40 32 01 0f 9b c0 3a 21 41 72 f6 c3

Assembly code:

    movzx eax, dl;
    inc eax;
repeat:
    xor al, [ecx];
    setpo al;
    cmp ah, [ecx];
    inc ecx;
    jb repeat;
    ret;

This is a function that receives its first argument (string) in ecx and second argument (char) in dl. It returns the result in eax, so it's compatible with the fastcall calling convention.

This code bends the rules when it uses the setpo instruction:

Builtins that count the number of "on" bits in a string or character are not allowed

This instruction sets al to the parity bit calculated by the previous instruction - so I have these two nitpicks on the rules:

It doesn't count the number of "on" bits - it calculates the parity bit directly!

Technically, it's the previous instruction (xor) that calculates the parity bit. The setpo instruction only moves it to the al register.

These semantic details out of the way, here is the explanation on what the code does.

The representations of the characters are:

'e' = 01100101
'o' = 01101111

If we add 1 to them, they happen to have just the right parity:

'e' + 1 = 01100110 (odd parity)
'o' + 1 = 01110000 (even parity)

So we XOR all the characters of the string, initializing al to these values, which gives the answer.

The first instruction is movzx eax, dl instead of the more obvious (and shorter) mov al, dl, because I want to have the number 0 in a register (ah in this case) in order to be able to compare it in the right order (0, [ecx] rather than [ecx], 0).


答:
Octave, <s>46</s> <s>44</s> 40 bytes

<s>Saved 2 bytes thanks to @flawr</s>

@LuisMendo's kernel was 4 bytes shorter than @flawr's.

```<code>@(M)conv2(M.*(M>0),(x='aba')~=x','same')
</code>```

Just like @LuisMendo's answer! Only less... golfy.

You can see it here on ideone.

Title: Transform a matrix

Body:
Write a program or function where a matrix A (maximum value of dimensions of the matrix is 100) is transformed to a new matrix B. Each element of the new matrix B is the sum of the positive neighbors of the corresponding element of the matrix A.

Only neighbors in the four orthogonal directions are considered, and the edges do not wrap around.

Example input:

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

Output:

```<code> 6  4  2
 1  6 13
 5 12 10
 2 11 12
</code>```

Rules:

As input use integers.

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

Body:
Octave, <s>46</s> <s>44</s> 40 bytes

<s>Saved 2 bytes thanks to @flawr</s>

@LuisMendo's kernel was 4 bytes shorter than @flawr's.

@(M)conv2(M.*(M>0),(x='aba')~=x','same')

Just like @LuisMendo's answer! Only less... golfy.

You can see it here on ideone.


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

答:
Ouroboros

Each line of an Ouroboros program represents a snake eating its own tail, with the beginning of the line being the head and the end being the tail. The only control flow operations are commands to eat or regurgitate characters of the tail. When the instruction pointer reaches the last part of the line that hasn't been eaten, it loops back to the beginning. To stop execution, simply swallow the instruction pointer.

Factoid

Ouroboros has a Stack Snippet interpreter.

Length 1

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

Outputs the top of the stack as a number. An empty stack is treated as if it contained infinite zeros, so this outputs 0. No characters are ever eaten, so the program loops (and prints) infinitely.

Length 2

```<code>1(
</code>```

Pushes a 1 and then uses ( to eat that many characters from the end of the snake. This means eating the last character. However, since that's where the instruction pointer currently is, the snake dies and the program terminates.

The program would also terminate if the number were 2, or indeed any larger number; in that case the entire snake would be swallowed. (Physically impossible, but hey--this is a metaphor.)

Length 3

```<code>32n
</code>```

Although Ouroboros processes one character per tick, it still supports multi-digit numbers in the expected way. This program will push and output 32 infinitely (rather than, for instance, pushing 3, pushing 2, and outputting only the 2).

One interesting side effect: a multi-digit number is recognized as such even when it bridges the end of the snake. The code 2n3 will first output 2, but thereafter will output 32 infinitely.

Length 4

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

r reads a positive integer from input, grabbing all contiguous digits until it finds a non-digit. n outputs as a number. a pushes 10, and o outputs this as a character (newline). Thus, an input of 1 2.3 -4abc55 will yield

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

However, because this snippet doesn't terminate the loop when the input is used up, the program will continue: r will start giving -1s to signal end-of-input, and n will keep outputting them indefinitely.

Length 5

```<code>n?2*(
</code>```

Prints one or more 0s, with the exact count depending on random numbers.

n behaves as in snippet 1, outputting a 0 from the empty stack. ?2* generates a random floating-point number between 0 and 1 and doubles it. Then ( eats that many characters (rounded down). Thus, if ? generated a number >= 0.5, the program halts; if not, it loops, prints another 0, etc.

Length 6

```<code>"oooo(
</code>```

" toggles between executing characters and treating them as a string. As in other 2D languages, you can define a string using only one quote mark because the instruction pointer wraps around. A key difference with Ouroboros, however, is that the string is pushed in reverse order, so that the first character is on the top of the stack. This means we don't need to write strings backwards or have a stack-reverse operator like ><> does.

The above code pushes "oooo(" and outputs the first four characters (the os). It then uses the last number remaining on the stack (40, the charcode of () as the argument to the ( command. Eating 40 characters definitely swallows the IP, and the program halts.

Length 7

```<code>r.*.n!(
</code>```

Truth machine program.

r reads a number from input, or -1 for EOF. .* multiplies it by itself, keeping 0 and 1 the same but mapping -1 to 1. .n dups and outputs the number. Finally, !( logically negates and  eats that many characters of the end of the snake. If the number was 0, this eats the ( and dies. If the number was 1, this eats zero characters, and execution loops back to the beginning of the snake, printing 1 indefinitely.

Length 8

```<code>i.0<2*(o
</code>```

Cat program.

i reads a single character from input, pushing its charcode (or -1 on EOF). .0< duplicates and tests if the value was less than 0; i.e., pushes 1 on EOF and 0 otherwise. 2*( multiplies by 2 and swallows that many characters. On EOF, this eats (o and ends the program; otherwise, nothing is eaten, and o outputs the character from input. The snake then loops back to the beginning.

In writing this snippet, I realized that cat can actually be done in four characters: i.)o. Go read the explanation on that answer for some crazy abuse of undefined behavior.

(Length 9 snippet pending)

Length 10

```<code>.!+.@.nao+
</code>```

Outputs the Fibonacci sequence, starting from 0 and continuing indefinitely.

First, we need to initialize the stack by pushing a 1. The trouble is that any initialization code at the head of a snake will run every time through (since it's at the head, we have no way of eating it). Therefore .!+ is designed to turn the top of the stack into a 1 iff it was previously 0 (which is the case when the stack is empty). .! dups and logically negates (1 if the value was 0, otherwise 0), and + adds that result to the top value.

(For a version that uses a second snake to perform the initialization, see the GitHub readme.)

Now the bulk of the program. Call the two numbers on the stack x and y, where x is smaller and y is on the top of the stack. .@.n copies y, rotates x to the top, and outputs a copy of it. ao outputs a newline (as in snippet 4), and + adds x to a copy of y. Now the stack contains y and x+y, and we proceed to the next iteration.

Title: Showcase of Languages

Body:
Ouroboros

Each line of an Ouroboros program represents a snake eating its own tail, with the beginning of the line being the head and the end being the tail. The only control flow operations are commands to eat or regurgitate characters of the tail. When the instruction pointer reaches the last part of the line that hasn't been eaten, it loops back to the beginning. To stop execution, simply swallow the instruction pointer.

Factoid

Ouroboros has a Stack Snippet interpreter.

Length 1

n

Outputs the top of the stack as a number. An empty stack is treated as if it contained infinite zeros, so this outputs 0. No characters are ever eaten, so the program loops (and prints) infinitely.

Length 2

1(

Pushes a 1 and then uses ( to eat that many characters from the end of the snake. This means eating the last character. However, since that's where the instruction pointer currently is, the snake dies and the program terminates.

The program would also terminate if the number were 2, or indeed any larger number; in that case the entire snake would be swallowed. (Physically impossible, but hey--this is a metaphor.)

Length 3

32n

Although Ouroboros processes one character per tick, it still supports multi-digit numbers in the expected way. This program will push and output 32 infinitely (rather than, for instance, pushing 3, pushing 2, and outputting only the 2).

One interesting side effect: a multi-digit number is recognized as such even when it bridges the end of the snake. The code 2n3 will first output 2, but thereafter will output 32 infinitely.

Length 4

rnao

r reads a positive integer from input, grabbing all contiguous digits until it finds a non-digit. n outputs as a number. a pushes 10, and o outputs this as a character (newline). Thus, an input of 1 2.3 -4abc55 will yield

1
2
3
4
55

However, because this snippet doesn't terminate the loop when the input is used up, the program will continue: r will start giving -1s to signal end-of-input, and n will keep outputting them indefinitely.

Length 5

n?2*(

Prints one or more 0s, with the exact count depending on random numbers.

n behaves as in snippet 1, outputting a 0 from the empty stack. ?2* generates a random floating-point number between 0 and 1 and doubles it. Then ( eats that many characters (rounded down). Thus, if ? generated a number >= 0.5, the program halts; if not, it loops, prints another 0, etc.

Length 6

"oooo(

" toggles between executing characters and treating them as a string. As in other 2D languages, you can define a string using only one quote mark because the instruction pointer wraps around. A key difference with Ouroboros, however, is that the string is pushed in reverse order, so that the first character is on the top of the stack. This means we don't need to write strings backwards or have a stack-reverse operator like ><> does.

The above code pushes "oooo(" and outputs the first four characters (the os). It then uses the last number remaining on the stack (40, the charcode of () as the argument to the ( command. Eating 40 characters definitely swallows the IP, and the program halts.

Length 7

r.*.n!(

Truth machine program.

r reads a number from input, or -1 for EOF. .* multiplies it by itself, keeping 0 and 1 the same but mapping -1 to 1. .n dups and outputs the number. Finally, !( logically negates and  eats that many characters of the end of the snake. If the number was 0, this eats the ( and dies. If the number was 1, this eats zero characters, and execution loops back to the beginning of the snake, printing 1 indefinitely.

Length 8

i.0<2*(o

Cat program.

i reads a single character from input, pushing its charcode (or -1 on EOF). .0< duplicates and tests if the value was less than 0; i.e., pushes 1 on EOF and 0 otherwise. 2*( multiplies by 2 and swallows that many characters. On EOF, this eats (o and ends the program; otherwise, nothing is eaten, and o outputs the character from input. The snake then loops back to the beginning.

In writing this snippet, I realized that cat can actually be done in four characters: i.)o. Go read the explanation on that answer for some crazy abuse of undefined behavior.

(Length 9 snippet pending)

Length 10

.!+.@.nao+

Outputs the Fibonacci sequence, starting from 0 and continuing indefinitely.

First, we need to initialize the stack by pushing a 1. The trouble is that any initialization code at the head of a snake will run every time through (since it's at the head, we have no way of eating it). Therefore .!+ is designed to turn the top of the stack into a 1 iff it was previously 0 (which is the case when the stack is empty). .! dups and logically negates (1 if the value was 0, otherwise 0), and + adds that result to the top value.

(For a version that uses a second snake to perform the initialization, see the GitHub readme.)

Now the bulk of the program. Call the two numbers on the stack x and y, where x is smaller and y is on the top of the stack. .@.n copies y, rotates x to the top, and outputs a copy of it. ao outputs a newline (as in snippet 4), and + adds x to a copy of y. Now the stack contains y and x+y, and we proceed to the next iteration.


答:
JavaScript (ES6), <s>99</s> 94 bytes

```<code>a=>a.map((b,i)=>b.map((_,j)=>(g=(c=j,k=j)=>c[k]>0&&c[k])(a[i-1])+g(a[i+1])+g(b,j-1)+g(b,j+1)))
</code>```

Accepts and returns a two-dimensional array.

Edit: Completely rewritten when I discovered that default arguments work when you pass an explicitly undefined value, such as when you index off the end of an array.

Title: Transform a matrix

Body:
JavaScript (ES6), <s>99</s> 94 bytes

a=>a.map((b,i)=>b.map((_,j)=>(g=(c=j,k=j)=>c[k]>0&&c[k])(a[i-1])+g(a[i+1])+g(b,j-1)+g(b,j+1)))

Accepts and returns a two-dimensional array.

Edit: Completely rewritten when I discovered that default arguments work when you pass an explicitly undefined value, such as when you index off the end of an array.


答:
Cheddar

Cheddar is a high-level, functional + object-oriented programming language designed to make programming easier, faster, and more intuitive.

Due to the fact Cheddar is still in development, running Cheddar programs can be rather difficult. Ping me in chat, @Downgoat, and I'll help you test this stuff out.

Factoid

Despite Cheddar's tasty name, it is not edible, if you'd like to eat Cheddar, please go to your local grocery store, not the Github.

Length 1 Snippet

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

This is a number. You probably guessed that but Cheddar's numbers also have some cool features:

```<code>0b1011  // Binary number
0o1337  // Octal number
0xFFFF  // Hexadecimal number

123_456_789 // One hundred twenty three million, four hundred thousand...
1.333333333 // Decimal number (yes this is a regular old floating point)
</code>```

Length 2 Snippet

```<code>[]
""
''
</code>```

These all create iterables. The first is an array []. The second and third are strings. In Cheddar strings may have literal newlines in them.

Length 3 snippet

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

This creates a range from 0 - 9, it is represented as an array so you can iterate over it, reverse it. Do anything you want!

Additionally you can use binary |> to generate a range from [a, b]

```<code> 0|>4
</code>```

the above generates: [0, 1, 2, 3, 4]

Length 4 Snippet

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

This creates a boolean with a value of true. This isn't very interesting, unfortunately.

Length 5 Snippet

```<code>1?2:3
</code>```

This is the ternary operator. This is the same as the following:

```<code>if (1) { 2 } else { 3 }
</code>```

The difference is the ternary is an expression so rather than doing:

```<code>var a: String
if (goat.type == saanen) {
    a = "bleeeeeet"
} else {
    a = "baaaaaa";
}
</code>```

You can do:

```<code>var a: String = goat.type == saanen ? "bleeeeeet" : "baaaaaa"
</code>```

Length 6 Snippet

```<code>0b1011  // Binary number
0o1337  // Octal number
0xFFFF  // Hexadecimal number

123_456_789 // One hundred twenty three million, four hundred thousand...
1.333333333 // Decimal number (yes this is a regular old floating point)
</code>```0

This, obfuscated looking code is actually very simple. It defines a lambda, or anonymous function taking one argument, a, and returns it. Note the parenthesis are optional, the following is just as valid:

```<code>0b1011  // Binary number
0o1337  // Octal number
0xFFFF  // Hexadecimal number

123_456_789 // One hundred twenty three million, four hundred thousand...
1.333333333 // Decimal number (yes this is a regular old floating point)
</code>```1

Now, if you were to call foo, it would return the value passed:

```<code>0b1011  // Binary number
0o1337  // Octal number
0xFFFF  // Hexadecimal number

123_456_789 // One hundred twenty three million, four hundred thousand...
1.333333333 // Decimal number (yes this is a regular old floating point)
</code>```2

Length 7 Snippet

```<code>var a=1
</code>```

This is the shortest assignment in Cheddar.

Additionally other ways of declaring variables

```<code>const foo = bar        // constant
const foo: String = bar // Same but requires `bar` to be a specific type
var foo = bar       // Can be changed, so can the type
var foo: String = bar // Can be changed but only to another string
</code>```

Length 9 Snippet

```<code>String::9
</code>```

This shows a cool feature of Cheddar's called casting. Classes each have defined behavior for when any class (in this case Number), is cast to them. This would output "9";

In this example String's Number cast is called which in turn casts to a string. You an also swap this around to do a number cast:

```<code>Number::"9"
</code>```

which would output a number 9.

In the event a cast fails, Cheddar throws an error. I'm planning on adding an operator castable which checks if a certain value (LHS) can be cast into (RHS). Which would work like:

```<code>if foo castable Number
    print Number::foo
</code>```

Title: Showcase of Languages

Body:
Notes

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

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

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

How this works

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

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

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

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

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

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

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

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

Current answers, sorted alphabetically by language name

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

Body:
Cheddar

Cheddar is a high-level, functional + object-oriented programming language designed to make programming easier, faster, and more intuitive.

Due to the fact Cheddar is still in development, running Cheddar programs can be rather difficult. Ping me in chat, @Downgoat, and I'll help you test this stuff out.

Factoid

Despite Cheddar's tasty name, it is not edible, if you'd like to eat Cheddar, please go to your local grocery store, not the Github.

Length 1 Snippet

1

This is a number. You probably guessed that but Cheddar's numbers also have some cool features:

0b1011  // Binary number
0o1337  // Octal number
0xFFFF  // Hexadecimal number

123_456_789 // One hundred twenty three million, four hundred thousand...
1.333333333 // Decimal number (yes this is a regular old floating point)

Length 2 Snippet

[]
""
''

These all create iterables. The first is an array []. The second and third are strings. In Cheddar strings may have literal newlines in them.

Length 3 snippet

|>9

This creates a range from 0 - 9, it is represented as an array so you can iterate over it, reverse it. Do anything you want!

Additionally you can use binary |> to generate a range from [a, b]

 0|>4

the above generates: [0, 1, 2, 3, 4]

Length 4 Snippet

true

This creates a boolean with a value of true. This isn't very interesting, unfortunately.

Length 5 Snippet

1?2:3

This is the ternary operator. This is the same as the following:

if (1) { 2 } else { 3 }

The difference is the ternary is an expression so rather than doing:

var a: String
if (goat.type == saanen) {
    a = "bleeeeeet"
} else {
    a = "baaaaaa";
}

You can do:

var a: String = goat.type == saanen ? "bleeeeeet" : "baaaaaa"

Length 6 Snippet

(a)->a

This, obfuscated looking code is actually very simple. It defines a lambda, or anonymous function taking one argument, a, and returns it. Note the parenthesis are optional, the following is just as valid:

a->a

Now, if you were to call foo, it would return the value passed:

print foo(123) // prints `123`

Length 7 Snippet

var a=1

This is the shortest assignment in Cheddar.

Additionally other ways of declaring variables

const foo = bar        // constant
const foo: String = bar // Same but requires `bar` to be a specific type
var foo = bar       // Can be changed, so can the type
var foo: String = bar // Can be changed but only to another string

Length 9 Snippet

String::9

This shows a cool feature of Cheddar's called casting. Classes each have defined behavior for when any class (in this case Number), is cast to them. This would output "9";

In this example String's Number cast is called which in turn casts to a string. You an also swap this around to do a number cast:

Number::"9"

which would output a number 9.

In the event a cast fails, Cheddar throws an error. I'm planning on adding an operator castable which checks if a certain value (LHS) can be cast into (RHS). Which would work like:

if foo castable Number
    print Number::foo


问:
One-to-one correspondence between pairs of integers and the positive integers
It is well-known that there are one-to-one correspondences between pairs of integers and the positive integers. Your task is to write code defining such a correspondence (by defining a pair of functions/programs that are inverses of each other) in your programming language of choice, plus a correctness check (see below) with the smallest number of bytes for the correspondence definition (not taking the correctness check into account).

The solution must include :

the definition of a function/program f having two integer arguments and returning an integer (that's one direction of the bijection).

either the definition of a function/program g having one integer argument and returning a pair of integers (might be an array, a list, the concatenation of the two integers separated by something   ...) or two functions/programs a and b having an integer argument and returning an integer (that's the other direction).

an additional code snippet checking that for the f and g (or f and a,b) you defined above, you have g(f(x,y))=(x,y) (or a(f(x,y))=x and b(f(x,y))=y) for any integers x,y in the range -100 < x < 100,-100 < y < 100. Note that f and g have to work for values outside of this range as well.

You may rename a,b,f or g of course. The two solutions do not have to be written in the same language.

Below is a not-optimal-at-all solution in PARI/GP, with 597 characters for the function definitions.

```<code>plane_to_line(x,y)={
my(ax,ay,z);
ax=abs(x);
ay=abs(y);
if((ax<=ay)*(y<0),        z=4*y*y-2*y+x+2;);
if((ax<=ay)*(y>=0),       z=4*y*y-2*y-x+2;);
if((ay<=ax)*(x<0),        z=4*x*x    -y+2;);
if((ay<=ax)*(x>=0)*(y<0), z=4*x*x+4*x+y+2;);
if((ay<=ax)*(x>=0)*(y>=0),z=4*x*x-4*x+y+2;);
if((x==0)*(y==0),z=1;);
return(z);
}

line_to_plane(z)={
my(l,d,x,y);
l=floor((1+sqrt(z-1))/2);
d=z-(4*l*l-4*l+2);
if(d<=l,x=l;y=d;);
if((l<d)*(d<=3*l),x=2*l-d;y=l;);
if((3*l<d)*(d<=5*l),x=(-l);y=4*l-d;);
if((5*l<d)*(d<=7*l),x=d-6*l;y=(-l););
if((7*l<d)*(d<8*l) ,x=l;y=d-8*l;);
if(z==1,x=0;y=0;);
return([x,y]);
}
</code>```

and the correctness-check code :

```<code>accu=List([])
m=100;
for(x=-m,m,for(y=-m,m,if(line_to_plane(plane_to_line(x,y))!=[x,y],\
listput(accu,[x,y]);)))
Vec(accu)
</code>```

答:
JavaScript (ES6), 171 bytes

```<code>(x,y)=>(h=x=>parseInt((x^x>>31).toString(2)+(x>>>31),4),h(x)*2+h(y))
x=>(h=x=>parseInt(x.toString(2).replace(/.(?!(..)*$)/g,''),2),i=x=>x<<31>>31^x>>>1,[i(h(x>>>1)),i(h(x))])
</code>```

Bit twiddling: negative numbers have their bits flipped; each integer is then doubled, and 1 added if it was originally negative; the bits from the integers are then interleaved. The reverse operation deletes alternate bits, divides by 2, and flips all the bits if the value was negative. I could save 3 bytes by limiting myself to 15-bit values instead of 16-bit values.

f=(x,y)=>(h=x=>parseInt((x^x>>31).toString(2)+(x>>>31),4),h(x)*2+h(y))
g=x=>(h=x=>parseInt(x.toString(2).replace(/.(?!(..)*$)/g,''),2),i=x=>x<<31>>31^x>>>1,[i(h(x>>>1)),i(h(x))])
for(i=-100;i<=100;i++)for(j=-100;j<100;j++)if(g(f(i,j))[0]!=i||g(f(i,j))[1]!=j)alert([i,j])```

Body:
JavaScript (ES6), 171 bytes

(x,y)=>(h=x=>parseInt((x^x>>31).toString(2)+(x>>>31),4),h(x)*2+h(y))
x=>(h=x=>parseInt(x.toString(2).replace(/.(?!(..)*$)/g,''),2),i=x=>x<<31>>31^x>>>1,[i(h(x>>>1)),i(h(x))])

Bit twiddling: negative numbers have their bits flipped; each integer is then doubled, and 1 added if it was originally negative; the bits from the integers are then interleaved. The reverse operation deletes alternate bits, divides by 2, and flips all the bits if the value was negative. I could save 3 bytes by limiting myself to 15-bit values instead of 16-bit values.

f=(x,y)=>(h=x=>parseInt((x^x>>31).toString(2)+(x>>>31),4),h(x)*2+h(y))
g=x=>(h=x=>parseInt(x.toString(2).replace(/.(?!(..)*$)/g,''),2),i=x=>x<<31>>31^x>>>1,[i(h(x>>>1)),i(h(x))])
for(i=-100;i<=100;i++)for(j=-100;j<100;j++)if(g(f(i,j))[0]!=i||g(f(i,j))[1]!=j)alert([i,j])


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

Input

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

Output

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

Pieces are represented by their character in FEN

Empty squares are represented by spaces

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

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

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

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

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

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

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

答:
R (out of competition)

Sorry if it's not appropriate to post this, but I thought it was cool that I just happened to have a function lying around that actually works for this question without editing! It prints unicode output rather than ascii, though. I can't remember quite why I wrote it, but it wasn't to answer a challenge.

function(x){
# x = FEN position, a string
# can be split with / or ,
# example: forsythe("rnbqkbnr/pp1ppppp/8/2p5/4P3/5N2/PPPP1PPP/RNBQKB1R")

allowed <- c(paste(1:64),
c("k", "q", "r", "b", "n", "p", "K", "Q", "R", "B", "N", "P"))
chars <- strsplit(x, "")[[1]]
chars <- chars[-which(!(chars %in% allowed))]
out <- c()
for (i in 1:length(chars)){
  if (chars[i] %in% paste(1:64)){
    out <- c(out, rep(" ", as.numeric(chars[i])))
  }
  else{
    out <- c(out, chars[i])
  }
}
if (length(out) < 64) out <- c(out, rep(" ", 64-length(out)))

pieces <- strsplit("KQRBNPkqrbnp", "")[[1]]
unicode <- c("\u2654", "\u2655", "\u2656",
"\u2657", "\u2658", "\u2659", "\u265A", "\u265B",
"\u265C", "\u265D", "\u265E", "\u265F")

for (i in 1:64){
  if (out[i] %in% pieces){
    out[i] <- unicode[which(pieces==out[i])]
  }
  else{
  }
}
out <- matrix(out, nc=8, byrow=T)
#print(out)

plot(0, xlim=c(0, 8), ylim=c(0, 8), type="n", xaxt="n", yaxt="n",
xlab="", ylab="")
for (i in 0:7){ for (j in 0:7){ rect(i, j, i+1, j+1,
col=ifelse(((i+j) %% 2) == 0, grey(0.95), "white"), border=F) }}

for (i in 0:7){ for (j in 0:7){
  text(i+0.5, j+0.5, out[8-j, i+1], cex=2)
}}

axis(1, labels=letters[1:8], at=1:8 - 0.5, tick=F)
axis(2, labels=paste(1:8), at=1:8-0.5, las=2, tick=F)

}
```


问:
Tips for golfing in MATL
MATL is a golfing language created by Luis Mendo. MATL has proven to be highly competitive, often beating submissions in other golfing languages such as Pyth, CJam and Jelly.

What are some useful tips for golfing in MATL? (As always, one tip per answer, please!)

For the record, MATL can be tested online here.

Documentation can be found on Github

答:
Some functions are extended compared with MATLAB or Octave

If you come from MATLAB or Octave, you'll find many MATL functions are similar to functions in those languages. But in quite a few of them functionality has been extended.

As an example, consider MATLAB's reshape function, which in MATL corresponds to  e. The code snippets reshape([10 20 30 40 50 60], 2, 3) and reshape([10 20 30 40 50 60], 2, []) respectively mean "reshape the row vector [10 20 30 40 50 60 into a 2×3 matrix", or "into a 2-row matrix with as many columns as needed". So the result, in both cases, is the 2D array

```<code>10    30    50
20    40    60
</code>```

Something like reshape([10 20 30 40 50 60], 2, 2) or reshape([10 20 30 40 50 60], 5, []) would give an error because of incompatible sizes. However, MATL will remove elements in the first case (try it online!) or fill with zeros in the second (try it online!) to produce, respectively,

```<code>10 30
20 40
</code>```

and

```<code>10 60
20  0
30  0
40  0
50  0
</code>```

Other functions that have extended functionality in comparison with their MATLAB counterparts are (non-exhaustive list) S (sort), Yb (strsplit), m (ismember), h (horzcat), v (vertcat), Zd (gcd), Zm (lcm), YS (circshift), YA (dec2base), ZA (base2dec), Z" (blanks).

Title: Tips for golfing in MATL

Body:
Some functions are extended compared with MATLAB or Octave

If you come from MATLAB or Octave, you'll find many MATL functions are similar to functions in those languages. But in quite a few of them functionality has been extended.

As an example, consider MATLAB's reshape function, which in MATL corresponds to  e. The code snippets reshape([10 20 30 40 50 60], 2, 3) and reshape([10 20 30 40 50 60], 2, []) respectively mean "reshape the row vector [10 20 30 40 50 60 into a 2×3 matrix", or "into a 2-row matrix with as many columns as needed". So the result, in both cases, is the 2D array

10    30    50
20    40    60

Something like reshape([10 20 30 40 50 60], 2, 2) or reshape([10 20 30 40 50 60], 5, []) would give an error because of incompatible sizes. However, MATL will remove elements in the first case (try it online!) or fill with zeros in the second (try it online!) to produce, respectively,

10 30
20 40

and

10 60
20  0
30  0
40  0
50  0

Other functions that have extended functionality in comparison with their MATLAB counterparts are (non-exhaustive list) S (sort), Yb (strsplit), m (ismember), h (horzcat), v (vertcat), Zd (gcd), Zm (lcm), YS (circshift), YA (dec2base), ZA (base2dec), Z" (blanks).


问:
Calculate the Kronecker sum of two matrices
In the examples below, A and B will be 2-by-2 matrices, and the matrices are one-indexed.

A Kronecker product has the following properties:

```<code>A⊗B =  A(1,1)*B   A(1,2)*B
        A(2,1)*B   A(2,2)*B

     =  A(1,1)*B(1,1)   A(1,1)*B(1,2)   A(1,2)*B(1,1)   A(1,2)*B(1,2)
        A(1,1)*B(2,1)   A(1,1)*B(2,2)   A(1,2)*B(2,1)   A(1,2)*B(2,2)
        A(2,1)*B(1,1)   A(2,1)*B(1,2)   A(2,2)*B(1,1)   A(2,2)*B(1,2)
        A(2,2)*B(2,1)   A(2,2)*B(1,2)   A(2,2)*B(2,1)   A(2,2)*B(2,2)
</code>```

A Kronecker sum has the following properties:

```<code>A⊕B = A⊗Ib + Ia⊗B
</code>```

Ia and Ib are the identity matrices with the dimensions of A and B respectively. A and B are square matrices. Note that A and B can be of different sizes.

```<code>A⊕B =  A(1,1)+B(1,1)  B(1,2)         A(1,2)         0
        B(2,1)         A(1,1)+B(2,2)  0              A(1,2)
        A(2,1)         0              A(2,2)+B(1,1)  B(1,2)
        0              A(2,1)         B(2,1)         A(2,2)+B(2,2)
</code>```

Given two square matrices, A and B, calculate the Kronecker sum of the two matrices.

The size of the matrices will be at least 2-by-2. The maximum size will be whatever your computer / language can handle by default, but minimum 5-by-5 input (5 MB output).

All input values will be non-negative integers

Builtin functions that calculate the Kronecker sum or Kronecker products are not allowed

In general: Standard rules regarding I/O format, program & functions, loopholes etc.

Test cases:

```<code>A =
     1     2
     3     4
B =
     5    10
     7     9

A⊕B =
     6    10     2     0
     7    10     0     2
     3     0     9    10
     0     3     7    13

----

A =
    28    83    96
     5    70     4
    10    32    44
B =
    39    19    65
    77    49    71
    80    45    76

A⊕B =
    67    19    65    83     0     0    96     0     0
    77    77    71     0    83     0     0    96     0
    80    45   104     0     0    83     0     0    96
     5     0     0   109    19    65     4     0     0
     0     5     0    77   119    71     0     4     0
     0     0     5    80    45   146     0     0     4
    10     0     0    32     0     0    83    19    65
     0    10     0     0    32     0    77    93    71
     0     0    10     0     0    32    80    45   120

----

A =
    76    57    54
    76     8    78
    39     6    94
B =
    59    92
    55    29

A⊕B =
   135    92    57     0    54     0
    55   105     0    57     0    54
    76     0    67    92    78     0
     0    76    55    37     0    78
    39     0     6     0   153    92
     0    39     0     6    55   123
</code>```

答:
Jelly, <s>26</s> <s>21</s> <s>20</s> 19 bytes

```<code>æ*9Bs2¤×€€/€S;"/€;/
</code>```

Input is a list of two 2D lists, output is a single 2D list. Try it online! or verify all test cases.

How it works

```<code>æ*9Bs2¤×€€/€S;"/€;/  Main link.
                     Argument: [A, B] (matrices of dimensions n×n and m×m)

      ¤              Evaluate the four links to the left as a niladic chain.
  9B                 Convert 9 to base 2, yielding [1, 0, 0, 1].
    s2               Split into sublists of length 2, yielding [[1, 0], [0, 1]].
æ*                   Vectorized matrix power.
                     This yields [[A¹, B⁰], [A⁰, B¹]], where B⁰ and A⁰ are the
                     identity matrices of dimensions m×m and n×n.
          /€         Reduce each pair by the following:
        €€             For each entry of the first matrix:
       ×                 Multiply the second matrix by that entry.
            S        Sum the two results, element by element.
                     This yields the Kronecker sum, in form of a n×n matrix of
                     m×m matrices.
               /€    Reduce each row of the outer matrix...
             ;"        by zipwith-concatenation.
                     This concatenates the columns of the matrices in each row,
                     yielding a list of length n of n×nm matrices.
                 ;/  Concatenate the lists, yielding a single nm×nm matrix.
</code>```

Body:
Jelly, <s>26</s> <s>21</s> <s>20</s> 19 bytes

æ*9Bs2¤×€€/€S;"/€;/

Input is a list of two 2D lists, output is a single 2D list. Try it online! or verify all test cases.

How it works

æ*9Bs2¤×€€/€S;"/€;/  Main link.
                     Argument: [A, B] (matrices of dimensions n×n and m×m)

      ¤              Evaluate the four links to the left as a niladic chain.
  9B                 Convert 9 to base 2, yielding [1, 0, 0, 1].
    s2               Split into sublists of length 2, yielding [[1, 0], [0, 1]].
æ*                   Vectorized matrix power.
                     This yields [[A¹, B⁰], [A⁰, B¹]], where B⁰ and A⁰ are the
                     identity matrices of dimensions m×m and n×n.
          /€         Reduce each pair by the following:
        €€             For each entry of the first matrix:
       ×                 Multiply the second matrix by that entry.
            S        Sum the two results, element by element.
                     This yields the Kronecker sum, in form of a n×n matrix of
                     m×m matrices.
               /€    Reduce each row of the outer matrix...
             ;"        by zipwith-concatenation.
                     This concatenates the columns of the matrices in each row,
                     yielding a list of length n of n×nm matrices.
                 ;/  Concatenate the lists, yielding a single nm×nm matrix.


问:
Negative base conversion
We already have a base conversion question, but not one with negative bases (nope, this doesn't count).

(Corresponding wiki article.)

You will receive a number (may be negative) and a base (must be negative), and your task is to convert the number into the base.

The base will only be from -10 to -2.

Specs

You may receive the number in any positive base, including unary.

You may choose receive the magnitude of the base instead (10 instead of -10).

The input can be taken in any reasonable format.

Scoring

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

Testcases

```<code>input        output
8163, -10    12243
-8163, -10   9977
17, -3       212
</code>```

答:
Jelly, 1 byte

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

Jelly supports negative bases with its base conversion builtin.

Try it online!

(bV at two bytes if the output must be a single integer.)

Title: Negative base conversion

Body:
Jelly, 1 byte

b

Jelly supports negative bases with its base conversion builtin.

Try it online!

(bV at two bytes if the output must be a single integer.)


Title: Transform a matrix

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

document.write("<pre>"+(

m=>m.map((a,r)=>a.map((_,c)=>(s=(x,y=0)=>(n=(m[r+y]||0)[c+x])>0&&n)(1)+s(-1)+s(0,1)+s(0,-1)))

)([[  1,  2,  3 ],
   [  4, -1, -2 ],
   [ -3, -4, 10 ],
   [  1,  2, 10 ]])

.join`\n`)


问:
Find the program that prints this integer sequence (Robbers' thread)
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

答:
05AB1E, 1 byte, mnbvc, A004085

Code:

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

Sequence is the sum of digits of Euler totient function of n.

Body:
05AB1E, 1 byte, mnbvc, A004085

Code:

Õ

Sequence is the sum of digits of Euler totient function of n.


答:
LiveCode, 35 bytes, mnbvc, A001477

I/O:

```<code>oeis (0) = 0
oeis (2) = 2
</code>```

Code:

```<code>function oeis n
    return n*1
End oeis
</code>```

Sequence returns the non-negative integers.

Title: Find the program that prints this integer sequence (Robbers' thread)

Body:
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

Body:
LiveCode, 35 bytes, mnbvc, A001477

I/O:

oeis (0) = 0
oeis (2) = 2

Code:

function oeis n
    return n*1
End oeis

Sequence returns the non-negative integers.


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

Rules:

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

The code can't take input of any kind

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

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

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

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

Lower score is better.

答:
C C++ Python Ruby, 163 bytes

Score = 163/4^3 = 2.55

```<code>#include <stdio.h>
#if 0
C = 3
""" "
C = 4;\
" """
#endif
#ifdef __cplusplus
#define A 49
#else
#define A 50
#endif
#define print(X) main(){putchar(A);}
print(C);
</code>```

ContentLicense: CC BY-SA 4.0

Title: The Versatile Integer Printer

Body:
C C++ Python Ruby, 163 bytes

Score = 163/4^3 = 2.55

#include <stdio.h>
#if 0
C = 3
""" "
C = 4;\
" """
#endif
#ifdef __cplusplus
#define A 49
#else
#define A 50
#endif
#define print(X) main(){putchar(A);}
print(C);


Body:
This is the cops' thread. The robbers' thread goes here.

The last cops-and-robbers thread was already 4 months ago.

The cop's task

The cop's task is to write a program/function that takes a positive (or non-negative) integer and outputs/returns another integer.

The cop must state it if the program is intolerant towards zero.

The cop will provide at least 2 sample inputs/outputs.

For example, if I have decided to write the Fibonacci sequence, I would write this in my answer:

```
a(0) returns 0
a(3) returns 2
```

The number of examples is up to the cop's discretion.

However, the sequence must actually exist in the On-Line Encyclopedia of Integer Sequences®, so no pseudo-random number generator for you. :(

The cop can hide as many characters as is so wished.

For example, if my program is:

```<code>function a(n)
    if n>2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Then I would hide these characters as I want:

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

The robber's task

is obviously to find the original source code.

However, any proposed source code that produces the same set of output also counts as valid, as long as it is also found in OEIS.

Tips for the cops

<s>The search function in the OEIS only works for consecutive terms, so if you want to hide your sequence, then just leave a hole anywhere.</s>

Apparently there is no way to hide the sequence. Put this in mind when you choose the sequence.

Your score is the number of bytes in your code.

The winner will be the submission with the lowest score that hasn't been cracked in 7 days.

Only submissions that are posted in 2016 April are eligible for the win. Submissions that are posted later than this are welcome, but cannot win.

In order to claim the win you need to reveal the full code and the OEIS sequence (after 7 days).

Your post should be formatted like this (NN is the number of characters):

Lua, 98 bytes

Output:

```<code>a(0) returns 0
a(3) returns 2
</code>```

Code (# marks unrevealed characters):

```<code>function a(n)
    if ### then
        ########
    else
        ######################
    end
end
</code>```

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

Body:
Python, 37 bytes, cracked

def a(n):
    return ______!______n____*_

a(2)==4
a(4)==16


答:
Julia, <s>60</s> <s>59</s> <s>58</s> 56 bytes

```<code>A%B=hvcat(sum(A^0),sum(i->map(a->a*B^i,A'^-~-i),0:1)...)
</code>```

Try it online!

How it works

For matrices A and B, map(a->a*B,A') computes the Kronecker product A⊗B.

The result is a vector of matrix blocks with the dimensions of B.

We have to transpose A (with ') since matrices are stored in column-major order.

Since bitwise NOT with two's complement satisfies the identity ~n = -(n + 1) for all integers n, we have that -~-n = -(~(-n)) = --((-n) + 1) = 1 - n, so -~-0 = 1 and -~-1 = 0.

This way the anonymous function i->map(a->a*B^i,A'^-~-i) applies the above map to B⁰ (the identity matrix with B's dimensions) and A¹ = A when i = 0, and to B¹ and A⁰ when i = 1.

sum(i->map(a->a*B^i,A'^-~-i),0:1) sums over {0,1} with the above anonymous function, computing the Kronecker sum A⊕B as A¹⊗B⁰ + A⁰⊗B¹.

The result is a vector of matrix blocks with the dimensions of B.

sum(A^0) computes the sum of all entries of the identity matrix of A's dimensions. For an n×n matrix A, this yields n.

Finally, hvcat(sum(A^0),sum(i->map(a->a*B^i,A'^-~-i),0:1)...) concatenates the matrix blocks that form A⊕B.

With first argument n, hvcat concatenates n matrix blocks horizontally, and the resulting (larger) blocks vertically.

Title: Calculate the Kronecker sum of two matrices

Body:
In the examples below, A and B will be 2-by-2 matrices, and the matrices are one-indexed.

A Kronecker product has the following properties:

```<code>A⊗B =  A(1,1)*B   A(1,2)*B
        A(2,1)*B   A(2,2)*B

     =  A(1,1)*B(1,1)   A(1,1)*B(1,2)   A(1,2)*B(1,1)   A(1,2)*B(1,2)
        A(1,1)*B(2,1)   A(1,1)*B(2,2)   A(1,2)*B(2,1)   A(1,2)*B(2,2)
        A(2,1)*B(1,1)   A(2,1)*B(1,2)   A(2,2)*B(1,1)   A(2,2)*B(1,2)
        A(2,2)*B(2,1)   A(2,2)*B(1,2)   A(2,2)*B(2,1)   A(2,2)*B(2,2)
</code>```

A Kronecker sum has the following properties:

```<code>A⊕B = A⊗Ib + Ia⊗B
</code>```

Ia and Ib are the identity matrices with the dimensions of A and B respectively. A and B are square matrices. Note that A and B can be of different sizes.

```<code>A⊕B =  A(1,1)+B(1,1)  B(1,2)         A(1,2)         0
        B(2,1)         A(1,1)+B(2,2)  0              A(1,2)
        A(2,1)         0              A(2,2)+B(1,1)  B(1,2)
        0              A(2,1)         B(2,1)         A(2,2)+B(2,2)
</code>```

Given two square matrices, A and B, calculate the Kronecker sum of the two matrices.

The size of the matrices will be at least 2-by-2. The maximum size will be whatever your computer / language can handle by default, but minimum 5-by-5 input (5 MB output).

All input values will be non-negative integers

Builtin functions that calculate the Kronecker sum or Kronecker products are not allowed

In general: Standard rules regarding I/O format, program & functions, loopholes etc.

Test cases:

```<code>A =
     1     2
     3     4
B =
     5    10
     7     9

A⊕B =
     6    10     2     0
     7    10     0     2
     3     0     9    10
     0     3     7    13

----

A =
    28    83    96
     5    70     4
    10    32    44
B =
    39    19    65
    77    49    71
    80    45    76

A⊕B =
    67    19    65    83     0     0    96     0     0
    77    77    71     0    83     0     0    96     0
    80    45   104     0     0    83     0     0    96
     5     0     0   109    19    65     4     0     0
     0     5     0    77   119    71     0     4     0
     0     0     5    80    45   146     0     0     4
    10     0     0    32     0     0    83    19    65
     0    10     0     0    32     0    77    93    71
     0     0    10     0     0    32    80    45   120

----

A =
    76    57    54
    76     8    78
    39     6    94
B =
    59    92
    55    29

A⊕B =
   135    92    57     0    54     0
    55   105     0    57     0    54
    76     0    67    92    78     0
     0    76    55    37     0    78
    39     0     6     0   153    92
     0    39     0     6    55   123
</code>```

Body:
Julia, <s>60</s> <s>59</s> <s>58</s> 56 bytes

A%B=hvcat(sum(A^0),sum(i->map(a->a*B^i,A'^-~-i),0:1)...)

<a href="http://julia.tryitonline.net/#code=QSVCPWh2Y2F0KHN1bShBXjApLHN1bShpLT5tYXAoYS0-YSpCXmksQSdeLX4taSksMDoxKS4uLikKClMoQSxCKSA9IEElQgoKZGlzcGxheShTKFsxICAgICAyCiAgICAgICAgICAgMyAgICAgNF0sCgogICAgICAgICAgWzUgICAgMTAKICAgICAgICAgICA3ICAgICA5XSkpCgpwcmludCgiXG5cbiIpCgpkaXNwbGF5KFMoWzI4ICAgIDgzICAgIDk2CiAgICAgICAgICAgIDUgICAgNzAgICAgIDQKICAgICAgICAgICAxMCAgICAzMiAgICA0NF0sCgogICAgICAgICAgWzM5ICAgIDE5ICAgIDY1CiAgICAgICAgICAgNzcgICAgNDkgICAgNzEKICAgICAgICAgICA4MCAgICA0NSAgICA3Nl0pKQoKcHJpbnQoIlxuXG4iKQoKZGlzcGxheShTKFs3NiAgICA1NyAgICA1NAogICAgICAgICAgIDc2ICAgICA4ICAgIDc4CiAgICAgICAgICAgMzkgICAgIDYgICAgOTRdLAoKICAgICAgICAgIFs1OSAgICA5MgogICAgICAgICAgIDU1ICAgIDI5XSkp&input=" rel="nofollow">Try it online!

How it works

For matrices A and B, map(a->a*B,A') computes the Kronecker product A⊗B.

The result is a vector of matrix blocks with the dimensions of B.

We have to transpose A (with ') since matrices are stored in column-major order.

Since bitwise NOT with two's complement satisfies the identity ~n = -(n + 1) for all integers n, we have that -~-n = -(~(-n)) = --((-n) + 1) = 1 - n, so -~-0 = 1 and -~-1 = 0.

This way the anonymous function i->map(a->a*B^i,A'^-~-i) applies the above map to B⁰ (the identity matrix with B's dimensions) and A¹ = A when i = 0, and to B¹ and A⁰ when i = 1.

sum(i->map(a->a*B^i,A'^-~-i),0:1) sums over {0,1} with the above anonymous function, computing the Kronecker sum A⊕B as A¹⊗B⁰ + A⁰⊗B¹.

The result is a vector of matrix blocks with the dimensions of B.

sum(A^0) computes the sum of all entries of the identity matrix of A's dimensions. For an n×n matrix A, this yields n.

Finally, hvcat(sum(A^0),sum(i->map(a->a*B^i,A'^-~-i),0:1)...) concatenates the matrix blocks that form A⊕B.

With first argument n, hvcat concatenates n matrix blocks horizontally, and the resulting (larger) blocks vertically.


问:
Palindromic palindrome generator
Create a program, that converts input string to a palindrome starting with the input string. The program itself must be a palindrome.

For example input: neverod, print neveroddoreven. You should handle multi-word, multi-line inputs as well.

答:
Vitsy, 9 bytes

```<code>z:Zr?rZ:z
z          Grab all string input from the command line arguments.
 :         Duplicate this stack.
  Z        Print all elements in this stack as a string.
   r       Reverse (reverses an empty stack).
    ?      Go right a stack.
     r     Reverse (reverses the input).
      Z    Print all elements in this stack as a string.
       :   Duplicate the stack (duplicates an empty stack).
        z  Grab all input from the command line (the command line arguments stack is already empty).
</code>```

Try it online!

Title: Palindromic palindrome generator

Body:
Vitsy, 9 bytes

z:Zr?rZ:z
z          Grab all string input from the command line arguments.
 :         Duplicate this stack.
  Z        Print all elements in this stack as a string.
   r       Reverse (reverses an empty stack).
    ?      Go right a stack.
     r     Reverse (reverses the input).
      Z    Print all elements in this stack as a string.
       :   Duplicate the stack (duplicates an empty stack).
        z  Grab all input from the command line (the command line arguments stack is already empty).

Try it online!


答:
Python, 37 bytes, mnbvc, A000290

I/O:

```<code>a(2) = 4
a(4) = 16
</code>```

Code:

```<code>def a(n):
    return n*n#__!______n____*_
</code>```

Sequence return square of input

Body:
Python, 37 bytes, mnbvc, A000290

I/O:

a(2) = 4
a(4) = 16

Code:

def a(n):
    return n*n#__!______n____*_

Sequence return square of input


答:
Python with SciPy, 127 bytes

from scipy.signal import*
lambda A,r=range(3):convolve2d([[x*(x>0)for x in y]for y in A],[[0,1,0],[1,0,1],[0,1,0]],mode='same')
```

This computes the result using Luis Mendo's method.

Try it online

Title: Transform a matrix

Body:
Write a program or function where a matrix A (maximum value of dimensions of the matrix is 100) is transformed to a new matrix B. Each element of the new matrix B is the sum of the positive neighbors of the corresponding element of the matrix A.

Only neighbors in the four orthogonal directions are considered, and the edges do not wrap around.

Example input:

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

Output:

```<code> 6  4  2
 1  6 13
 5 12 10
 2 11 12
</code>```

Rules:

As input use integers.

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

Body:
Python with SciPy, 127 bytes

from scipy.signal import*
lambda A,r=range(3):convolve2d([[x*(x>0)for x in y]for y in A],[[0,1,0],[1,0,1],[0,1,0]],mode='same')

This computes the result using Luis Mendo's method.

Try it online


问:
Convert from binary to negabinary
Given a binary integer inclusively between 0 and 1111111111111111 (i.e. a 16-bit unsigned integer) as input, output the same integer in negabinary.

The input can be in whatever format is most convenient for your language; for example, if it is easier for the program to handle input with 16 digits, like 0000000000000101, rather than simply 101, you can write the program to only accept input that way.

Sample I/O

```<code>> 1
1
> 10
110
> 1010
11110
> 110111001111000
11011001110001000
> 1001001
1011001
</code>```

Here is a sample program I wrote that does base conversions, including negative and non-integer bases. You can use it to check your work.

答:
JavaScript, 68 bytes

```<code>function(b){for(r='',n=parseInt(b,2);r=(n&1)+r,n>>=1;n=-n);return r}
</code>```

Would be 52 bytes in ES6, but that post-dates the challenge:

```<code>b=>eval(`for(r='',n=0b${b};r=(n&1)+r,n>>=1;n=-n);r`)
</code>```

Title: Convert from binary to negabinary

Body:
JavaScript, 68 bytes

function(b){for(r='',n=parseInt(b,2);r=(n&1)+r,n>>=1;n=-n);return r}

Would be 52 bytes in ES6, but that post-dates the challenge:

b=>eval(`for(r='',n=0b${b};r=(n&1)+r,n>>=1;n=-n);r`)


问:
Taylor Series of a Function with Periodic Derivatives
Taylor series are a very useful tool in calculating values of analytic functions that cannot be expressed in terms of elementary functions, using only information about that function at a single point.

In this challenge, you won't be actually doing any math with them, but merely making string representations of taylor series of functions with periodic derivatives.

Specs

You will takes a input three things:

A cycle of the derivatives of the function, including the original function as a list of strings, e.g. ["sin(x)", "cos(x)", "-sin(x)", "-cos(x)"].

A number a, the point around which to center the approximation.

A positive integer n, the number of terms of the series to output.

The general form for the nth term of a taylor series is:

```<code>f^(n)(a)/n!*(x-a)^n
</code>```

where f^(n) is the nth derivative of f. Here is the taylor series of f in a better formatted image from wikipedia:

.

The above example with sin(x), and a of 1, and n of 6, would have an output of:

```<code>sin(1) + cos(1)*(x-1) - sin(1)/2*(x-1)^2 - cos(1)/6*(x-1)^3 + sin(1)/24*(x-1)^4 + cos(1)/120*(x-1)^5
</code>```

You can do the whitespace want. However, you have to replace + - and - - with - and + respectively. Also, if the series is a maclaurin series, and a is 0, you cannot have (x-0). (x) and just x is fine, but not (x-0). Niether can you have ^0 nor ^1 nor /1 . Additionally, you must expand out the factorials in the denominators. Multiplication by juxtaposition is not allowed.

Test cases

```<code>["e^x"], 0, 4  ->  e^0 + e^0*x + e^0*x^2/2 + e^0*x^3/6
["sin(x)", "cos(x)", "-sin(x)", "-cos(x)"], 1, 6 -> sin(1) + cos(1)*(x-1) - sin(1)/2*(x-1)^2 - cos(1)/6*(x-1)^3 + sin(1)/24*(x-1)^4 + cos(1)/120*(x-1)^5
["e^(i*x)", "i * e^(i*x)", "-e^(i*x)", "-i*e^(i*x)"], 0, 7 -> e^(i*0) + i*e^(i*0)*x - e^(i*0)*x^2/2 - i*e^(i*0)*x^3/6 + e^(i*0)*x^4/24 + i*e^(i*0)*x^5/120 - e^(i*0)*x^6/720
</code>```

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

答:
Python 3.5, 308 299 bytes:

```<code>def g(f,a,n,L=len,S=str):import math,re;A=S(a);print('+'.join(t.replace('x',A)+re.sub('(\W\(x-\d+\)\^0|/1|\*1|\^1|\*0)(?!\d+)','',g)for t,g in zip(f*(n//L(f))+f[:n%L(f)],['*'+A+'/'+S(math.factorial(n))+'*'+'(x-'+A+')^'+S(n)for n in range(n)])).replace('+-','-').replace('--','+').replace('x-0','x'))
</code>```

This always outputs in the order according to the equation f^(n)(a)/n!*(x-a)^n. For instance, if the expected output for one of the terms is e^0*x^2/2, it instead outputs e^0/2*x^2. However, they are both basically the same answer, so I hope this is okay. Confirmed by OP that this is okay. This works perfectly as I have had no issues with it. I will shorten this over time wherever I can.

Note: In the output, all (x-0) are replaced with (x).

Try it online! (Ideone) (Accepts input on 3 lines, where the first line is the input list, f, the second line is a, and the third line is n)

Explanation

For the purposes of this explanation, assume the function is executed with the values "e^(i*x)", "i*e^(i*x)", "-e^(i*x)", "-i*e^(i*x)"],0,7. That being said, basically, what's going on in the main part, step-by-step, is:

'+'.join(t.replace('x',A)+re.sub('(\W\(x-\d+\)\^0|/1|\*1|\^1|\*0)(?!\d+)','',g)for t,g in zip(f*(n//L(f))+f[:n%L(f)],['*'+A+'/'+S(math.factorial(n))+'*'+'(x-'+A+')^'+S(n)for n in range(n)]))

A list is created from each item pair in a zip object containing the input list, f, with n number of items, and another list which contains each term in the sequence except the items in f. In this second list, *+a is added, followed by a /+ n! for each value, n, in the range n, and finally, a lone * followed by (x-a)^n. After all this is done, for each item pair in this zip object, t corresponding to each object in f and g corresponding to each value in the second list, each 'x' in t is replaced with a, and every g goes through a regular expression substitution, namely (\W\(x-\d+\)\^0|/1|\*1|\^1|\*0)(?!\d+), in which every (x-a)^0, /1,*1,^1, and *0 is matched and replaced with '' as long as each of those are not followed by any more integers. After all this substitution is done, each t and g are concatenated together, and each term created using this method is joined with +s and returned. For this particular case in which "e^(i*x)", "i*e^(i*x)", "-e^(i*x)", "-i*e^(i*x)"],0,7 is the input, this part would return:

```<code>e^(i*0)+i*e^(i*0)*(x-0)+-e^(i*0)/2*(x-0)^2+-i*e^(i*0)/6*(x-0)^3+e^(i*0)/24*(x-0)^4+i*e^(i*0)/120*(x-0)^5+-e^(i*0)/720*(x-0)^6
</code>```

As you can see, those +-s, --s, and (x-0)s exist. However, these will all be replaced with -,+,and (x) respectively in the next part.

'+'.join(t.replace('x',A)+re.sub('(\W\(x-\d+\)\^0|/1|\*1|\^1|\*0)(?!\d+)','',g)for t,g in zip(f*(n//L(f))+f[:n%L(f)],['*'+A+'/'+S(math.factorial(n))+'*'+'(x-'+A+')^'+S(n)for n in range(n)])).replace('+-','-').replace('--','+').replace('x-0','x')

Here is where those substrings such as +-,++,and (x-0) in the now joined string are replaced with their correct substitutes using Python's built-in sub-string replacement function. After all the replacing has been done, this finally returns the finished product, which in this case would be:

```<code>e^(i*0)+i*e^(i*0)*(x)-e^(i*0)/2*(x)^2-i*e^(i*0)/6*(x)^3+e^(i*0)/24*(x)^4+i*e^(i*0)/120*(x)^5-e^(i*0)/720*(x)^6
</code>```

Body:
Python 3.5, 308 299 bytes:

def g(f,a,n,L=len,S=str):import math,re;A=S(a);print('+'.join(t.replace('x',A)+re.sub('(\W\(x-\d+\)\^0|/1|\*1|\^1|\*0)(?!\d+)','',g)for t,g in zip(f*(n//L(f))+f[:n%L(f)],['*'+A+'/'+S(math.factorial(n))+'*'+'(x-'+A+')^'+S(n)for n in range(n)])).replace('+-','-').replace('--','+').replace('x-0','x'))

This always outputs in the order according to the equation f^(n)(a)/n!*(x-a)^n. For instance, if the expected output for one of the terms is e^0*x^2/2, it instead outputs e^0/2*x^2. However, they are both basically the same answer, so I hope this is okay. Confirmed by OP that this is okay. This works perfectly as I have had no issues with it. I will shorten this over time wherever I can.

Note: In the output, all (x-0) are replaced with (x).

Try it online! (Ideone) (Accepts input on 3 lines, where the first line is the input list, f, the second line is a, and the third line is n)

Explanation

For the purposes of this explanation, assume the function is executed with the values "e^(i*x)", "i*e^(i*x)", "-e^(i*x)", "-i*e^(i*x)"],0,7. That being said, basically, what's going on in the main part, step-by-step, is:

'+'.join(t.replace('x',A)+re.sub('(\W\(x-\d+\)\^0|/1|\*1|\^1|\*0)(?!\d+)','',g)for t,g in zip(f*(n//L(f))+f[:n%L(f)],['*'+A+'/'+S(math.factorial(n))+'*'+'(x-'+A+')^'+S(n)for n in range(n)]))

A list is created from each item pair in a zip object containing the input list, f, with n number of items, and another list which contains each term in the sequence except the items in f. In this second list, *+a is added, followed by a /+ n! for each value, n, in the range n, and finally, a lone * followed by (x-a)^n. After all this is done, for each item pair in this zip object, t corresponding to each object in f and g corresponding to each value in the second list, each 'x' in t is replaced with a, and every g goes through a regular expression substitution, namely (\W\(x-\d+\)\^0|/1|\*1|\^1|\*0)(?!\d+), in which every (x-a)^0, /1,*1,^1, and *0 is matched and replaced with '' as long as each of those are not followed by any more integers. After all this substitution is done, each t and g are concatenated together, and each term created using this method is joined with +s and returned. For this particular case in which "e^(i*x)", "i*e^(i*x)", "-e^(i*x)", "-i*e^(i*x)"],0,7 is the input, this part would return:

e^(i*0)+i*e^(i*0)*(x-0)+-e^(i*0)/2*(x-0)^2+-i*e^(i*0)/6*(x-0)^3+e^(i*0)/24*(x-0)^4+i*e^(i*0)/120*(x-0)^5+-e^(i*0)/720*(x-0)^6

As you can see, those +-s, --s, and (x-0)s exist. However, these will all be replaced with -,+,and (x) respectively in the next part.

'+'.join(t.replace('x',A)+re.sub('(\W\(x-\d+\)\^0|/1|\*1|\^1|\*0)(?!\d+)','',g)for t,g in zip(f*(n//L(f))+f[:n%L(f)],['*'+A+'/'+S(math.factorial(n))+'*'+'(x-'+A+')^'+S(n)for n in range(n)])).replace('+-','-').replace('--','+').replace('x-0','x')

Here is where those substrings such as +-,++,and (x-0) in the now joined string are replaced with their correct substitutes using Python's built-in sub-string replacement function. After all the replacing has been done, this finally returns the finished product, which in this case would be:

e^(i*0)+i*e^(i*0)*(x)-e^(i*0)/2*(x)^2-i*e^(i*0)/6*(x)^3+e^(i*0)/24*(x)^4+i*e^(i*0)/120*(x)^5-e^(i*0)/720*(x)^6


答:
 Common Lisp, 87

```<code>(lambda(s p)(=(mod(reduce'+(mapcar'logcount(map'list'char-code s)))2)(position p"oe")))
</code>```

Sum the logcount of char-codes of s.

The remainder of this, when divided by 2, is compared to the position of the parity argument p in the string "oe" (either 0 or 1). For example, if there are 4 ones, the remainder is zero. If p is o, then no additional bit should be added, and the test return false.

Pretty-printed

```<code>(lambda (s p)
  (= (mod (reduce '+ (mapcar 'logcount (map 'list 'char-code s))) 2)
     (position p "oe")))
</code>```

Title: Generate a parity bit

Body:
A parity bit, is one of the simplest forms of a checksum. First, you have to pick the parity, even or odd. Let's say we pick even. Now, we need a message to transmit. Let's say our message is "Foo". This is written in binary as:

```<code>01000110 01101111 01101111
</code>```

Now, we count the total number of 1's in there, which is 15. Since 15 is an odd number, we must add one extra bit to the end of our message, and we will now have an even number of 'on' bits. This last added bit is known as the "parity bit". If we had picked an odd parity for our checksum, we would have to add an extra '0' so that the number of on bits remains odd.

The challenge:

You must write a program or function that determines what the correct parity bit for a string is. Your program must take two inputs:

A string, s. This is the message that the checksum will be calculated on. This will be restricted to the 95 printable ASCII characters.

A character or single character string p, that will either be e for even parity, or o for odd parity.

and produce a truthy-falsey value representing the correct parity bit. Truthy if it's a 1, and falsey if it's a 0.

Builtins that count the number of "on" bits in a string or character are not allowed. For example, a function f that does this: f('a') == 3 or f('foo') == 16 is banned. Anything else, such as base conversion, is fair game.

Test IO:

```<code>(without the quotes)
s: "0"
p: 'e'
output: 0

s: "Foo"
p: 'e'
output: 1

s: "Hello World!"
p: 'o'
output: 0

s: "Alex is right"
p: 'e'
output: 1

s: "Programming Puzzles and Code-Golf"
p: 'e'
output: 0

s: "Programming Puzzles and Code-Golf"
p: 'o'
output: 1
</code>```

This is codegolf, so standard loopholes apply, and the shortest answer in bytes wins.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
 Common Lisp, 87

(lambda(s p)(=(mod(reduce'+(mapcar'logcount(map'list'char-code s)))2)(position p"oe")))

Sum the logcount of char-codes of s.

The remainder of this, when divided by 2, is compared to the position of the parity argument p in the string "oe" (either 0 or 1). For example, if there are 4 ones, the remainder is zero. If p is o, then no additional bit should be added, and the test return false.

Pretty-printed

(lambda (s p)
  (= (mod (reduce '+ (mapcar 'logcount (map 'list 'char-code s))) 2)
     (position p "oe")))