答:
Jelly, <s>32</s> <s>31</s> <s>30</s> 22 bytes

```<code>ị“.4<F(”Oæ«Ḥ:¥:⁴×µ×>?⁵
</code>```

Uses the astute observation from @xnor's answer, which saved 8 bytes.

Try it online! or verify all test cases.

How it works

```<code>ị“.4<F(”Oæ«Ḥ:¥:⁴×µ×>?⁵  Main link. Argument: n (integer)

                   >?⁵  If n is greater than 10:
                 µ   ⁵    Execute the chain to µ's left dyadically, with arguments
                          n (left) and 10 (right).
 “.4<F(”                    Yield the string of code points [46, 52, 60, 70, 40].
ị                           Retrieve the character at index n.
                            Indexing is modular and 1-based, so 1, 6, 11, etc. map
                            to the first character, 0, 5, 10, etc. to the last.
        O                   Ordinal; yield the code point of the character.
             ¥              Combine the two links to the left into a dyadic chain.
           Ḥ                  Yield 2n.
            :                 Divide 2n by 10, flooring the result.
                            This yields n : 5 (integer division).
         æ«                 Shift the code point n : 5 bits to the left.
              :⁴            Divide the result by 16.
                ×           Multiply the result by 10.
                        Else:
                  ×  ⁵    Multiply n by 10.
</code>```

Title: Find the number I/O shortest algorithm

Body:
Jelly, <s>32</s> <s>31</s> <s>30</s> 22 bytes

ị“.4<F(”Oæ«Ḥ:¥:⁴×µ×>?⁵

Uses the astute observation from @xnor's answer, which saved 8 bytes.

Try it online! or verify all test cases.

How it works

ị“.4<F(”Oæ«Ḥ:¥:⁴×µ×>?⁵  Main link. Argument: n (integer)

                   >?⁵  If n is greater than 10:
                 µ   ⁵    Execute the chain to µ's left dyadically, with arguments
                          n (left) and 10 (right).
 “.4<F(”                    Yield the string of code points [46, 52, 60, 70, 40].
ị                           Retrieve the character at index n.
                            Indexing is modular and 1-based, so 1, 6, 11, etc. map
                            to the first character, 0, 5, 10, etc. to the last.
        O                   Ordinal; yield the code point of the character.
             ¥              Combine the two links to the left into a dyadic chain.
           Ḥ                  Yield 2n.
            :                 Divide 2n by 10, flooring the result.
                            This yields n : 5 (integer division).
         æ«                 Shift the code point n : 5 bits to the left.
              :⁴            Divide the result by 16.
                ×           Multiply the result by 10.
                        Else:
                  ×  ⁵    Multiply n by 10.


问:
Is this figure connected?
You are given a list of (x,y) grid coordinates.  Your function should decide whether the figure obtained by coloring in the squares of the grid with the given coordinates is connected or not.

Squares adjacent diagonally are not considered connected.

Example input:

```<code>(0,0),(1,0),(2,0),(3,0),(3,1),(3,2),(2,2),
(1,2),(0,2),(0,3),(0,4),(1,4),(2,4),(3,4)
</code>```

which looks like:

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

Output:

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

Example input:

```<code>(0,0),(1,0),(2,0),(0,1),(0,2),(2,2),(3,2),(4,2),(0,3),
(4,3),(0,4),(1,4),(2,4),(4,4),(4,5),(2,6),(3,6),(4,6)
</code>```

which looks like:

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

Output:

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

Your function must take as input a list of pairs of integers (e.g. in C++, maybe vector<pair<int,int>>) and return a boolean.  You may not assume any particular ordering of the input points.  The coordinates will be between 0 and 99 inclusive.

Smallest code wins.

ContentLicense: CC BY-SA 2.5

Title: Is this figure connected?

Body:
My first python version (loosely) translated into golfscript. Urgh. 80 chars.

{1$!!1$!!&{(~:v;:u;[1u+v u 1v+u 1- v u v 1-]2/@.@&.@\-\@|g}{;!}if}:g;{([.;]g}:f;

test cases:

# test cases
[[0 0] [1 0] [2 0] [3 0] [3 1] [3 2] [2 2] [1 2] [0 2] [0 3] [0 4] [1 4] [2 4] [3 4]]:a0;
[[0 0] [1 0] [2 0] [0 1] [0 2] [2 2] [3 2] [4 2] [0 3] [4 3] [0 4] [1 4] [2 4] [4 4] [4 5] [2 6] [3 6] [4 6]]:a1;
a0 f p
a1 f p

python 2.6;  second attempt

def f(a):
    a = set(a)
    e = lambda (x, y) : set([(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)])
    p = lambda k : a.discard(k) or map(p, e(k) & a)
    p(a.pop())
    return not a

python 2.6;  first attempt

def f(a):
    a = set(a)
    e = lambda (x, y) : set([(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)])
    b = set([a.pop()])
    while b and a:
        c = a & e(b.pop())
        a -= c
        b |= c
    return not a

usage:

a_0 = [
    (0,0),(1,0),(2,0),(3,0),(3,1),(3,2),(2,2),
    (1,2),(0,2),(0,3),(0,4),(1,4),(2,4),(3,4)
]
a_1 = [
    (0,0),(1,0),(2,0),(0,1),(0,2),(2,2),(3,2),(4,2),(0,3),
    (4,3),(0,4),(1,4),(2,4),(4,4),(4,5),(2,6),(3,6),(4,6)
]
for a in (a_0, a_1):
    print 'YES' if f(a) else 'NO'


问:
Will the beam hit?
A laser shoots a straight beam in one of the four orthogonal directions, indicated by <>^v. Determine whether it will hit the target O on a rectangular grid.

Each of these will hit (True):

```<code>.....
...O.
.....
...^.
.....

>O.
...

v....
O....

...........
...........
O.........<
...........
</code>```

These will miss (False):

```<code>......
......
.^..O.

......
.....>
O.....
......
......

.O.
...
.v.

.....<.
..O....
</code>```

Input: A rectangular grid of ., sized at least 2x2, with exactly one target O and one laser that's one of <>^v. The lines can be a list of strings, a 2D array or nested list of characters, or a single newline-separated string with an optional trailing newline.

Output: A consistent truthy value if the laser beam hits the target, and a consistent falsy value if it misses.

I'll consider submissions that don't use regular expressions (or built-in pattern-based string matching) as a separate category. If you put (no regex) after the language name, your answer will appear separately in the leaderboard.

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

```

答:
C# (No Regex), 282 bytes

```<code>bool F(char[,]b){int k=0,l=1,m=1,n=0,o=0;for(int x=0;x<b.GetLength(0);x++)for(int y=0;y<b.GetLength(1);y++){char i=b[x,y];if(i=='O'){k=x;l=y;}if(new[]{'<','>','^','v'}.Contains(i)){m=x;n=y;o=i;}}return(o==60&&k==m&&l<n)||(o==62&&k==m&&l>n)||(o==94&&l==n&&k<m)||(o==118&&l==n&&k>m);}
</code>```

Works like the java version but transpiled and reduced

Expanded (Explanation included):

```<code>bool F(char[,] b)
{
    // declare variables for goal x, goal y, laser x, laser y, and laser direction respectively (laser direction is char code for directions)
    int k = 0, l = 0, m = 0, n = 0, o = 0;
    // go through each cell
    for (int x = 0; x < b.GetLength(0); x++)
    {
        for (int y = 0; y < b.GetLength(1); y++)
        {
            // get cell contents
            char i = b[x, y];
            // set goal position if goal
            if (i == 'O')
            {
                k = x;
                l = y;
            }
            // set laser position and direction if laser
            if (new[]{ '<', '>', '^', 'v' }.Contains(i))
            {
                m = x;
                n = y;
                o = i;
            }
        }
    }
    // check everything is on the same line and in right direction
    return (o == 60 && k == m && l < n) ||
           (o == 62 && k == m && l > n) ||
           (o == 94 && l == n && k < m) ||
           (o == 118 && l == n && k > m);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Will the beam hit?

Body:
C# (No Regex), 282 bytes

bool F(char[,]b){int k=0,l=1,m=1,n=0,o=0;for(int x=0;x<b.GetLength(0);x++)for(int y=0;y<b.GetLength(1);y++){char i=b[x,y];if(i=='O'){k=x;l=y;}if(new[]{'<','>','^','v'}.Contains(i)){m=x;n=y;o=i;}}return(o==60&&k==m&&l<n)||(o==62&&k==m&&l>n)||(o==94&&l==n&&k<m)||(o==118&&l==n&&k>m);}

Works like the java version but transpiled and reduced

Expanded (Explanation included):

bool F(char[,] b)
{
    // declare variables for goal x, goal y, laser x, laser y, and laser direction respectively (laser direction is char code for directions)
    int k = 0, l = 0, m = 0, n = 0, o = 0;
    // go through each cell
    for (int x = 0; x < b.GetLength(0); x++)
    {
        for (int y = 0; y < b.GetLength(1); y++)
        {
            // get cell contents
            char i = b[x, y];
            // set goal position if goal
            if (i == 'O')
            {
                k = x;
                l = y;
            }
            // set laser position and direction if laser
            if (new[]{ '<', '>', '^', 'v' }.Contains(i))
            {
                m = x;
                n = y;
                o = i;
            }
        }
    }
    // check everything is on the same line and in right direction
    return (o == 60 && k == m && l < n) ||
           (o == 62 && k == m && l > n) ||
           (o == 94 && l == n && k < m) ||
           (o == 118 && l == n && k > m);
}


问:
Toggle a string

The challenge involve simply toggling a string within another string.

Explanation

If the toggle string is a substring of the main string, remove all instances of the toggle string from the main string; otherwise, append the toggle string at the end of the main string.

Rules

All string are composed of printable ASCII characters

The function should take two parameters: the main string and the toggle string.

The main string can be empty.

The toggle string cannot be empty.

The result should be a string, which can be empty.

The shortest answer wins.

Examples

```<code>function toggle(main_string, toggle_string){ ... }

toggle('this string has 6 words ', 'now')
=> 'this string has 6 words now'

toggle('this string has 5 words now', ' now')
=> 'this string has 5 words'
</code>```

Tests cases

```<code>'','a'          => 'a'
'a','a'         => ''

'b','a'         => 'ba'
'ab','a'        => 'b'

'aba','a'       => 'b'
'ababa', 'aba'  => 'ba'
</code>```

答:
Ruby, <s>33 bytes</s> <s>27 bytes (28 if using global subtitution)</s> definitely 28 bytes

```<code>->u,v{u[v]?u.gsub(v,''):u+v}
</code>```

Title: Toggle a string

Body:
Ruby, <s>33 bytes</s> <s>27 bytes (28 if using global subtitution)</s> definitely 28 bytes

->u,v{u[v]?u.gsub(v,''):u+v}


问:
Find the number I/O shortest algorithm
Find the shortest function/algorithm to translate these numbers to the ones after the dash:

```<code>0 - 0
1 - 10
2 - 20
3 - 30
4 - 40
5 - 50
6 - 60
7 - 70
8 - 80
9 - 90
10 - 100
11 - 115
12 - 130
13 - 150
14 - 175
15 - 200
16 - 230
17 - 260
18 - 300
19 - 350
20 - 400
</code>```

Every integer higher than 20 is calculated by subtracting 10, calculating the corresponding number like done above and then multiplying that by 4.

Some examples (input will be between []):

```<code>[10] -> 100
[17] -> 260
[21] -> 4*115 -> 460
[32] -> 4*[22] -> 4*(4*130)) -> 2080
</code>```

var QUESTION_ID=80271,OVERRIDE_USER=53878;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="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

```

答:
Julia 0.4, <s>49</s> 42 bytes

n->n>9?5Int("(.4<F"[n%5+1])*2^(n÷5)/8:10n
```

<p>Uses the astute observation from @xnor's answer, which saved 7 bytes. Try it online!</p>

<hr>

<h1>Julia 0.3, 38 bytes</h1>

<pre class="lang-julia prettyprint-override"><code>n->2.5max("(.4<F"[n%5+1]<<(n÷5-2),4n)
</code>```

This requires a call to Int in Julia 0.4, which makes it longer than the other approach.

Title: Find the number I/O shortest algorithm

Body:
Julia 0.4, <s>49</s> 42 bytes

n->n>9?5Int("(.4<F"[n%5+1])*2^(n÷5)/8:10n

Uses the astute observation from @xnor's answer, which saved 7 bytes. Try it online!

Julia 0.3, 38 bytes

n->2.5max("(.4<F"[n%5+1]<<(n÷5-2),4n)

This requires a call to Int in Julia 0.4, which makes it longer than the other approach.


问:
Normal and visual string reversion
Write some code that acts as a cat program. That is, to input a string and output it as is. But the normal reversion of your code must output the normal reversion of the input string. And the visual reversion of your code must output the visual reversion of the input string.

The normal reversion is the reversed character sequence of a string. The visual reversion is the normal reversion with the characters ()[]{}<> replaced by )(][}{>< respectively.

You could use any codepage that has the characters ()[]{}<> and is published before this challenge to define characters. You must use the same codepage for all your code. Your original code must be valid in this codepage, and applying either of your reversed code to that should yield itself.

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

Example

For the string AB(XY), its normal and visual reversions are )YX(BA and (YX)BA respectively.

If your code (in a hypothetical language) is AB(XY), then the code )YX(BA and (YX)BA should output the normal and visual reversions of the input string respectively. And AB(XY) should act as a cat program.

答:
Python 2.7, 208 bytes

Forward

import sys#
print''.join(sys.stdin)#
#0:tpecxe
#"]1-::[)nidts.sys(nioj.'' tnirp"cexe:yrt
#0:tpecxe
#"(('<>{}[]()','><}{][)(')snartekam.s)etalsnart.[1-::](nidts.sys)nioj.'' tnirp"cexe:yrt
#s sa gnirts,sys tropmi
```

<p><strong>Normal reversion</strong></p>

<pre class="lang-py prettyprint-override"><code>import sys,string as s#
try:exec"print''.join)sys.stdin(]::-1[.translate)s.maketrans)'()[]{}<>',')(][}{><'(("#
except:0#
try:exec"print''.join(sys.stdin)[::-1]"#
except:0#
#)nidts.sys(nioj.''tnirp
#sys tropmi
</code>```

https://eval.in/574639

Visual reversion

import sys,string as s#
try:exec"print''.join(sys.stdin)[::-1].translate(s.maketrans(')(][}{><','()[]{}<>'))"#
except:0#
try:exec"print''.join)sys.stdin(]::-1["#
except:0#
#(nidts.sys)nioj.''tnirp
#sys tropmi
```

https://eval.in/574638

All directions read from stdin until EOF.

Nothing super clever here. Trailing comments to only execute the forward vs the backward code, then an exec statement in a try block to catch syntax errors for the two different reversions.

Title: Normal and visual string reversion

Body:
Python 2.7, 208 bytes

Forward

import sys#
print''.join(sys.stdin)#
#0:tpecxe
#"]1-::[)nidts.sys(nioj.'' tnirp"cexe:yrt
#0:tpecxe
#"(('<>{}[]()','><}{][)(')snartekam.s)etalsnart.[1-::](nidts.sys)nioj.'' tnirp"cexe:yrt
#s sa gnirts,sys tropmi

Normal reversion

import sys,string as s#
try:exec"print''.join)sys.stdin(]::-1[.translate)s.maketrans)'()[]{}<>',')(][}{><'(("#
except:0#
try:exec"print''.join(sys.stdin)[::-1]"#
except:0#
#)nidts.sys(nioj.''tnirp
#sys tropmi

https://eval.in/574639

Visual reversion

import sys,string as s#
try:exec"print''.join(sys.stdin)[::-1].translate(s.maketrans(')(][}{><','()[]{}<>'))"#
except:0#
try:exec"print''.join)sys.stdin(]::-1["#
except:0#
#(nidts.sys)nioj.''tnirp
#sys tropmi

https://eval.in/574638

All directions read from stdin until EOF.

Nothing super clever here. Trailing comments to only execute the forward vs the backward code, then an exec statement in a try block to catch syntax errors for the two different reversions.


答:
Perl, <s>37</s> 30 bytes

{$_=shift;s/\Q@_//g?$_:"$_@_"}
```

<p>Regular expressions inside the toggle string are not evaluate because of the quoting with <code>\Q</code>...<code>\E</code>.</p>

<p><code>sub F</code> and <code>\E</code> are  removed  according to the comment by  msh210.</p>

<p>It is not entirely free of side effects because of setting <code>$_</code>. Using a local variable will cost six additional bytes:</p>

<pre class="lang-perl prettyprint-override"><code>{my$a=shift;$a=~s/\Q@_//g?$a:"$a@_"}
</code>```

On the other hand, with switched input parameters two bytes can be saved by using pop instead of shift (28 bytes):

{$_=pop;s/\Q@_//g?$_:"$_@_"}
```

<p>Test file:</p>

<pre class="lang-perl prettyprint-override"><code>#!/usr/bin/env perl

sub F{$_=shift;s/\Q@_//g?$_:"$_@_"}

sub test ($$$) {
  my ($m, $t, $r) = @_;
  my $result = F($m, $t);
  print "F('$m', '$t') -> '$result' ",
    ($result eq $r ? '=OK=' : '<ERROR>'), " '$r'\n";
}
test '', 'a', 'a';
test 'a', 'a', '';
test 'b', 'a', 'ba';
test 'ab', 'a', 'b';
test 'aba', 'a', 'b';
test 'ababa', 'aba', 'ba';
test 'ababa', 'a*', 'ababaa*';
test 'foobar', '.', 'foobar.';
__END__
</code>```

Test result:

F('', 'a') -> 'a' =OK= 'a'
F('a', 'a') -> '' =OK= ''
F('b', 'a') -> 'ba' =OK= 'ba'
F('ab', 'a') -> 'b' =OK= 'b'
F('aba', 'a') -> 'b' =OK= 'b'
F('ababa', 'aba') -> 'ba' =OK= 'ba'
F('ababa', 'a*') -> 'ababaa*' =OK= 'ababaa*'
F('foobar', '.') -> 'foobar.' =OK= 'foobar.'
```

Title: Toggle a string

Body:
The challenge involve simply toggling a string within another string.

Explanation

If the toggle string is a substring of the main string, remove all instances of the toggle string from the main string; otherwise, append the toggle string at the end of the main string.

Rules

All string are composed of printable ASCII characters

The function should take two parameters: the main string and the toggle string.

The main string can be empty.

The toggle string cannot be empty.

The result should be a string, which can be empty.

The shortest answer wins.

Examples

```<code>function toggle(main_string, toggle_string){ ... }

toggle('this string has 6 words ', 'now')
=> 'this string has 6 words now'

toggle('this string has 5 words now', ' now')
=> 'this string has 5 words'
</code>```

Tests cases

```<code>'','a'          => 'a'
'a','a'         => ''

'b','a'         => 'ba'
'ab','a'        => 'b'

'aba','a'       => 'b'
'ababa', 'aba'  => 'ba'
</code>```

Body:
Perl, <s>37</s> 30 bytes

{$_=shift;s/\Q@_//g?$_:"$_@_"}

Regular expressions inside the toggle string are not evaluate because of the quoting with \Q...\E.

sub F and \E are  removed  according to the comment by  msh210.

It is not entirely free of side effects because of setting $_. Using a local variable will cost six additional bytes:

{my$a=shift;$a=~s/\Q@_//g?$a:"$a@_"}

On the other hand, with switched input parameters two bytes can be saved by using pop instead of shift (28 bytes):

{$_=pop;s/\Q@_//g?$_:"$_@_"}

Test file:

#!/usr/bin/env perl

sub F{$_=shift;s/\Q@_//g?$_:"$_@_"}

sub test ($$$) {
  my ($m, $t, $r) = @_;
  my $result = F($m, $t);
  print "F('$m', '$t') -> '$result' ",
    ($result eq $r ? '=OK=' : '<ERROR>'), " '$r'\n";
}
test '', 'a', 'a';
test 'a', 'a', '';
test 'b', 'a', 'ba';
test 'ab', 'a', 'b';
test 'aba', 'a', 'b';
test 'ababa', 'aba', 'ba';
test 'ababa', 'a*', 'ababaa*';
test 'foobar', '.', 'foobar.';
__END__

Test result:

F('', 'a') -> 'a' =OK= 'a'
F('a', 'a') -> '' =OK= ''
F('b', 'a') -> 'ba' =OK= 'ba'
F('ab', 'a') -> 'b' =OK= 'b'
F('aba', 'a') -> 'b' =OK= 'b'
F('ababa', 'aba') -> 'ba' =OK= 'ba'
F('ababa', 'a*') -> 'ababaa*' =OK= 'ababaa*'
F('foobar', '.') -> 'foobar.' =OK= 'foobar.'


答:
Mathematica, 45 bytes

```<code>If[StringContainsQ@##,StringDelete@##,#<>#2]&
</code>```

Anonymous function that takes the main string and the toggle string (in that order) and returns the result. Explanation:

```<code>                                            &  Anonymous function returning...

If[StringContainsQ@##,               ,     ]    if its first argument contains
                                                its second argument, then...
                      StringDelete@##            its first argument with its
                                                 second argument removed, else...
                                      #<>#2      its second argument appended to
                                                 its first argument.
</code>```

Title: Toggle a string

Body:
Mathematica, 45 bytes

If[StringContainsQ@##,StringDelete@##,#<>#2]&

Anonymous function that takes the main string and the toggle string (in that order) and returns the result. Explanation:

                                            &  Anonymous function returning...

If[StringContainsQ@##,               ,     ]    if its first argument contains
                                                its second argument, then...
                      StringDelete@##            its first argument with its
                                                 second argument removed, else...
                                      #<>#2      its second argument appended to
                                                 its first argument.


答:
Jolf, 12 bytes

```<code>?=iγρiIE+iIγ
</code>```

Or, if we must include regex-sensitive chars:

```<code>?=iγρiLeIE+iIγ
</code>```

Try it here!

Explanation

```<code>?=iγρiIE+iIγ    if(i === (γ = i.replace(I, E))) alert(i + I); else alert(γ);
  i                i
 =                   ===
    ρ                          .replace( ,  )
     iI                       i         I
       E                                   E
   γ                     (γ =                )
?               if(                           )
        +iI                                     alert(i + I);
                                                              else
           γ                                                       alert(γ);
</code>```

Title: Toggle a string

Body:
Jolf, 12 bytes

?=iγρiIE+iIγ

Or, if we must include regex-sensitive chars:

?=iγρiLeIE+iIγ

Try it here!

Explanation

?=iγρiIE+iIγ    if(i === (γ = i.replace(I, E))) alert(i + I); else alert(γ);
  i                i
 =                   ===
    ρ                          .replace( ,  )
     iI                       i         I
       E                                   E
   γ                     (γ =                )
?               if(                           )
        +iI                                     alert(i + I);
                                                              else
           γ                                                       alert(γ);


答:
JavaScript (ES6), 37 Bytes

```<code>(m,t)=>(w=m.split(t).join``)==m?m+t:w
</code>```

Slightly shorter than @nobe4 's answer by taking advantage of split and join

Title: Toggle a string

Body:
JavaScript (ES6), 37 Bytes

(m,t)=>(w=m.split(t).join``)==m?m+t:w

Slightly shorter than @nobe4 's answer by taking advantage of split and join


问:
Adding up the digits and the digits reversed
Given a number > 0, output the sum with all digits (1 .. n) concatenated and reversed and add them up. For example, with n = 6:

The numbers 1 to 6 concatenated:

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

Reversed:

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

Adding them up together will result in: 777777. Another example is n = 11:

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

and

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

Adding them up together will result in 2345555545332. This is also known as A078262.

Shortest code wins!

答:
Haskell, <s>57</s> <s>56</s> 48 bytes

This could probably be golfed a bit more, but here it goes:

```<code>f x=read y+(read.reverse$y)where y=[1..x]>>=show
</code>```

Edit: shaved off a space before the where.

Body:
Haskell, <s>57</s> <s>56</s> 48 bytes

This could probably be golfed a bit more, but here it goes:

f x=read y+(read.reverse$y)where y=[1..x]>>=show

Edit: shaved off a space before the where.


问:
Output the alphabet using the alphabet
The title is pretty self-explanatory, isn't it?

Your task is to output the alphabet (the string "abcdefghijklmnopqrstuvwxyz") to STDOUT, using each and every letter of the alphabet in your program once and only once.

Oh, and for a bit of extra fun?

The letters "g", "o", "l" and "f" must be in order (just for the code to be a bit more code-y).

Rules:

Only standard letters of the alphabet from ASCII count as letters (ë != e).

Both uppercase and lowercase characters count as letters (if you have E, you are not allowed to have e).

You are allowed to use comments, but every character in the comment is equal to 2 bytes.

Your final score will be the byte-count of your program, subtracted by 26.

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

答:
Jelly, 29 - 26 = 3 bytes

```<code>“golfabcdehijkmnpqrstuvwxyz”Ṣ
</code>```

Try it online!

Title: Output the alphabet using the alphabet

Body:
Jelly, 29 - 26 = 3 bytes

“golfabcdehijkmnpqrstuvwxyz”Ṣ

Try it online!


Title: Descending digit sequences

Body:
Introduction

As an example, let's take the number 7. We then duplicate this and place 7 spaces in between. We get this:

```<code>7_______7
</code>```

After that, we are going to decrease the number, until there are no spaces left. We get the following for the number 7:

```<code>7_______7
 6543210
</code>```

Then, we just merge the two of them, so:

```<code>7_______7
 6543210  becomes

765432107
</code>```

This will be out output for N = 7.

Looks easy, right? Now let's take N = 12. We again insert 12 spaces between the two numbers, which gives us:

```<code>12____________12
</code>```

Then we start the decrement:

```<code>12____________12
  111098765432
</code>```

And this finally gives us:

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

As you can see, the descending part ends at 2, not at 0.

Task

Given an integer, greater than 1, output the descending sequence as shown above.

Test cases

```<code>Input   Output

2       2102
3       32103
4       432104
5       5432105
6       65432106
7       765432107
8       8765432108
9       98765432109
10      10987654321010
11      111098765432111
12      1211109876543212
13      13121110987654313
14      141312111098765414
15      1514131211109876515
20      201918171615141312111020
99      9998979695949392919089888786858483828180797877767574737271706968676665646362616059585756555453525150499
100     1009998979695949392919089888786858483828180797877767574737271706968676665646362616059585756555453525150100
</code>```

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

Body:
Brainfuck, 265 Bytes

This is only going to work with numbers < 10

Try the golfed version here:

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

Ungolfed. Try it <a href="http://fatiherikli.github.io/brainfuck-visualizer/#PgosCi0tLS0tLS0tLS0gQ29udmVydCB0byBiYXNlIDEwCi0tLS0tLS0tLS0KLS0tLS0tLS0tLQotLS0tLS0tLS0tCi0tLS0tLS0tIAoKClstPis+Kzw8XT4+Wy08PCs+Pl08CgpGaWxsIHVwIHRoZSBncmlkClsKWy0+Kz4rPDxdPj5bLTw8Kz4+XSAvL3R1cm4gOCBpbnRvIFs4XVs4XQo8LQpdCgo8WzxdPiBHbyB0byBjZWxsIDEKWwoKPls+XSBTY2FuIGZvciB6ZXJvCj4gTW92ZSBvbmUgbW9yZQorIEFkZCBvbmUKPDwgTW92ZSB0d28gYmFjawpbPF0gU2NhbiBmb3IgemVybwo+IE1vdmUgb25lIGZvcndhcmQKLSBTdWJ0cmFjdCBPbmUKXQoKPiBNb3ZlIG9uZSBmb3J3YXJkIGludG8gYWN0dWFsIG51bWJlcnMKWworKysrKysrKysrIENvbnZlcnQgdG8gYXNjaWkKKysrKysrKysrKworKysrKysrKysrCisrKysrKysrKysKKysrKysrKysKLgo+Cl0KKysrKysrKysrKyBDb252ZXJ0IHRvIGFzY2lpCisrKysrKysrKysKKysrKysrKysrKworKysrKysrKysrCisrKysrKysrCi4KPgorKysrKysrKysrIENvbnZlcnQgdG8gYXNjaWkKKysrKysrKysrKworKysrKysrKysrCisrKysrKysrKysKKysrKysrKysKLgoK" rel="nofollow noreferrer">here:

>
,
---------- Convert to base 10
----------
----------
----------
--------

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

Fill up the grid
[
[->+>+<<]>>[-<<+>>] //duplicate number like [5][0] -> [5][5]
<-
]

<[<]> Go to cell 1
[

>[>] Scan for zero
> Move one more
+ Add one
<< Move two back
[<] Scan for zero
> Move one forward
- Subtract One
]

> Move one forward into actual numbers
[
++++++++++ Convert to ascii
++++++++++
++++++++++
++++++++++
++++++++
.
>
]
++++++++++ Convert to ascii
++++++++++
++++++++++
++++++++++
++++++++
.
>
++++++++++ Convert to ascii
++++++++++
++++++++++
++++++++++
++++++++
.


Title: Output the alphabet using the alphabet

Body:
The title is pretty self-explanatory, isn't it?

Your task is to output the alphabet (the string "abcdefghijklmnopqrstuvwxyz") to STDOUT, using each and every letter of the alphabet in your program once and only once.

Oh, and for a bit of extra fun?

The letters "g", "o", "l" and "f" must be in order (just for the code to be a bit more code-y).

Rules:

Only standard letters of the alphabet from ASCII count as letters (ë != e).

Both uppercase and lowercase characters count as letters (if you have E, you are not allowed to have e).

You are allowed to use comments, but every character in the comment is equal to 2 bytes.

Your final score will be the byte-count of your program, subtracted by 26.

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

Body:
Brainfuck, 67 - 26 + 26 (comment) = <s>41</s> 67 bytes

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

Try it online!


答:
CJam, 29 - 26 = 3 bytes

```<code>"golfabcdehijkmnpqrstuvwxyz"$
</code>```

Try it online!

Title: Output the alphabet using the alphabet

Body:
CJam, 29 - 26 = 3 bytes

"golfabcdehijkmnpqrstuvwxyz"$

Try it online!


答:
Actually, 29 - 26 = 3 bytes

```<code>"golfabcdehijkmnpqrstuvwxyz"S
</code>```

Try it online!

Title: Output the alphabet using the alphabet

Body:
Actually, 29 - 26 = 3 bytes

"golfabcdehijkmnpqrstuvwxyz"S

Try it online!


答:
Racket, 70 bytes

Pretty straight forward.

(λ(s t)((if(string-contains? s t)string-replace string-append)s t""))
```

Title: Toggle a string


问:
Manage Trash So
It's become somewhat of a tradition in PPCG that some users temporarily change their names by an anagram (a new name formed by reordering the letters of the old).

Sometimes it gets difficult to find out who is who. I could use a program or function to tell if two phrases are anagrams of each other.

The challenge

The program or function should take two strings and produce a truthy result if they are anagrams of each other, and falsy otherwise.

Rules

Input will only contain letters (ASCII 65 to 90 and 97 to 122), digits (ASCII 48 to 57) or space (ASCII 32).

The anagram relation is independendent of case. So "Arm" and "RAM" are anagrams.

Spaces don't count either. So "keyboard" and "Barked Yo" are anagrams

All builtins allowed

Input format is flexible (two strings, an array of two strings, a string containing both phrases with a suitable separator ...)

Code golf. Fewest bytes wins.

Test cases

Truthy:

```<code>Lynn, Nyl N
Digital Trauma, Tau Digital Arm
Sp3000, P S 3000
Manage Trash So, Those anagrams
</code>```

Falsy

```<code>Calvins Hobbies, Helka Homba
Android, rains odd
In between days, bayed entwine
Code golf, cod elf got
</code>```

答:
Q, 25 Bytes

```<code>f:{~/{x@<x:x@&~^x:_x}'x}
</code>```

NOTE.- counting include function name f: to facilitate tests (as lambda we can decrement 2 Bytes)

Readable version

match over {ascending not null lower x} each x

```<code>{.. x ..} is an anonymous function with arg x
_x        lowers string x
&~^x      where not null x (space is considered null)
x@..      selects elements of x according to indexes ..
<x        ascending indexes of x (not values). Ex <"cab" is 1 2 0
x@<x      ascending values of x (x at ascending indexes of x)
~         match (diad function). Ex "one"~"one" is true
f'..      applies function f for each argument ..
f/..      applies function f over elements of sequence (fold)
</code>```

Test

```<code>f("Lynn";"Nyl N")
f("Digital Trauma";"Tau Digital Arm")
f("Sp3000";"P S 3000")
f("Manage Trash So";"Those anagrams")
f("Calvins Hobbies";"Helka Homba")
f("Android";"rains odd")
f("In between days";"bayed entwine")
f("Code golf";"cod elf got")
</code>```

generates (1b = true, 0b = false)

```<code>1b
1b
1b
1b
0b
0b
0b
0b
</code>```

About Q

General-purpose language (APL derivative, specialized in data processing) developed by kx.com. Free full functional evaluation version for Windows/Linux/MacOS.

Title: Manage Trash So

Body:
Q, 25 Bytes

f:{~/{x@<x:x@&~^x:_x}'x}

NOTE.- counting include function name f: to facilitate tests (as lambda we can decrement 2 Bytes)

Readable version

match over {ascending not null lower x} each x

{.. x ..} is an anonymous function with arg x
_x        lowers string x
&~^x      where not null x (space is considered null)
x@..      selects elements of x according to indexes ..
<x        ascending indexes of x (not values). Ex <"cab" is 1 2 0
x@<x      ascending values of x (x at ascending indexes of x)
~         match (diad function). Ex "one"~"one" is true
f'..      applies function f for each argument ..
f/..      applies function f over elements of sequence (fold)

Test

f("Lynn";"Nyl N")
f("Digital Trauma";"Tau Digital Arm")
f("Sp3000";"P S 3000")
f("Manage Trash So";"Those anagrams")
f("Calvins Hobbies";"Helka Homba")
f("Android";"rains odd")
f("In between days";"bayed entwine")
f("Code golf";"cod elf got")

generates (1b = true, 0b = false)

1b
1b
1b
1b
0b
0b
0b
0b

About Q

General-purpose language (APL derivative, specialized in data processing) developed by kx.com. Free full functional evaluation version for Windows/Linux/MacOS.


答:
Python 3, 45 bytes

lambda n:[16*n,b'(.4<F'[n%5]<<n//5][n>9]//8*5
```
<p>Sticking to printable ASCII and int output. Uses that the values double every 5 steps, which can be computed with a bit shift.</p>
<pre class="lang-python prettyprint-override"><code>10 - 100
11 - 115
12 - 130
13 - 150
14 - 175

15 - 200
16 - 230
17 - 260
18 - 300
19 - 350
</code>```

So, for n>9, the output is [20,23,26,30,35][n%5]<<n/5-2. These values are doubled and packed in a printable ASCII bytearray. The -2 in the bit shift is pushed to the outside to avoid a negative shift error when n<=9 -- this is an ugly hack that can probably be handled better.

Title: Find the number I/O shortest algorithm

Body:
Find the shortest function/algorithm to translate these numbers to the ones after the dash:

```<code>0 - 0
1 - 10
2 - 20
3 - 30
4 - 40
5 - 50
6 - 60
7 - 70
8 - 80
9 - 90
10 - 100
11 - 115
12 - 130
13 - 150
14 - 175
15 - 200
16 - 230
17 - 260
18 - 300
19 - 350
20 - 400
</code>```

Every integer higher than 20 is calculated by subtracting 10, calculating the corresponding number like done above and then multiplying that by 4.

Some examples (input will be between []):

```<code>[10] -> 100
[17] -> 260
[21] -> 4*115 -> 460
[32] -> 4*[22] -> 4*(4*130)) -> 2080
</code>```

var QUESTION_ID=80271,OVERRIDE_USER=53878;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="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:
Python 3, 45 bytes

lambda n:[16*n,b'(.4<F'[n%5]<<n//5][n>9]//8*5

Sticking to printable ASCII and int output. Uses that the values double every 5 steps, which can be computed with a bit shift.

10 - 100
11 - 115
12 - 130
13 - 150
14 - 175

15 - 200
16 - 230
17 - 260
18 - 300
19 - 350

So, for n>9, the output is [20,23,26,30,35][n%5]<<n/5-2. These values are doubled and packed in a printable ASCII bytearray. The -2 in the bit shift is pushed to the outside to avoid a negative shift error when n<=9 -- this is an ugly hack that can probably be handled better.


问:
Locate and rotate

The task

This is a simple challenge.
Your input is a single non-empty string, containing only digits 0123456789 and hashes #.
It will contain exactly one run of digits, which encodes a nonnegative integer and may wrap around the end of the string, and at least one #.
The integer may have leading zeroes.
For example, ##44##, 013#### and 23###1 are valid inputs, while ###, 0099 and #4#4 are not.

Your task is to extract the integer n from the string, and output the string rotated n steps to the right.

Examples

The input #1## should be rotated 1 step to the right, so the correct output is ##1#.

The input #026### should be rotated 26 steps to the right, since the leading 0 is ignored. The correct output is 26####0.

The input 1####2 contains the integer 21 wrapped over the end, so it should be rotated 21 steps to the right. The correct output is ##21##.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

You can assume that the number n fits into the standard int type of your language.
Conversely, if that standard int type implements arbitrary-precision integers, you must support (in theory) an arbitrarily large n.

Test cases

```<code>#1## -> ##1#
##4## -> #4###
1####1 -> ####11
1####2 -> ##21##
#026### -> 26####0
#000### -> #000###
###82399 -> ##82399#
51379#97 -> #9751379
#98##### -> ###98###
#######4## -> #4########
60752#1183 -> 8360752#11
####99366800## -> 366800######99
########9##### -> ###9##########
91#####515694837 -> 1#####5156948379
###6114558###### -> #6114558########
######219088736090042#### -> 9088736090042##########21
#46055080150577874656291186550000138168########### -> 0138168############4605508015057787465629118655000
568375993099127531613012513406622393034741346840434468680494753262730615610086255892915828812820699971764142551702608639695081452206500085233149468399533981039485419872101852######################3680 -> 99533981039485419872101852######################36805683759930991275316130125134066223930347413468404344686804947532627306156100862558929158288128206999717641425517026086396950814522065000852331494683
</code>```

答:
matlab<s>(86)</s>72

```<code> @(n)circshift(n,[0 str2num(circshift(n(n~='#'),[0,-find(n=='#',1)+1]))])
</code>```

The function totates the string two times, once for integer extraction, second for the desired task, it doesnt take too much time because matlab proceeds to rotate by (Dim)modulus(Length) to the exception that it falls in segmentation failure for bigger ranges.

Will struggle how to golf it more ....

(86)

```<code>  @(n)circshift(n,[0 str2num([strtok(n(find(n=='#',1,'last'):end),'#') strtok(n,'#')])])
</code>```

The difference between this function and the previous, this one does concatenate two distant occurences of integers way backwards, while the first one just rotates it.

Title: Locate and rotate

Body:
matlab<s>(86)</s>72

 @(n)circshift(n,[0 str2num(circshift(n(n~='#'),[0,-find(n=='#',1)+1]))])

The function totates the string two times, once for integer extraction, second for the desired task, it doesnt take too much time because matlab proceeds to rotate by (Dim)modulus(Length) to the exception that it falls in segmentation failure for bigger ranges.

Will struggle how to golf it more ....

(86)

  @(n)circshift(n,[0 str2num([strtok(n(find(n=='#',1,'last'):end),'#') strtok(n,'#')])])

The difference between this function and the previous, this one does concatenate two distant occurences of integers way backwards, while the first one just rotates it.


答:
Pyke, 29 - 26 = 3 bytes

```<code>"golfabcdehijkmnpqrstuvwxyz"S
</code>```

Title: Output the alphabet using the alphabet

Body:
Pyke, 29 - 26 = 3 bytes

"golfabcdehijkmnpqrstuvwxyz"S


答:
Matlab(73)

```<code>  @(a)regexprep(a,'(\d*)#*(\d*)#*','${circshift($0,[0 str2num([$2 $1])])}')
</code>```

This is using another approach that i wonder if @luis used it, because refering to his description there is some points in common while (un)?fortunately i dont understand the cropped Matl language.

Title: Locate and rotate

Body:
The task

This is a simple challenge.
Your input is a single non-empty string, containing only digits 0123456789 and hashes #.
It will contain exactly one run of digits, which encodes a nonnegative integer and may wrap around the end of the string, and at least one #.
The integer may have leading zeroes.
For example, ##44##, 013#### and 23###1 are valid inputs, while ###, 0099 and #4#4 are not.

Your task is to extract the integer n from the string, and output the string rotated n steps to the right.

Examples

The input #1## should be rotated 1 step to the right, so the correct output is ##1#.

The input #026### should be rotated 26 steps to the right, since the leading 0 is ignored. The correct output is 26####0.

The input 1####2 contains the integer 21 wrapped over the end, so it should be rotated 21 steps to the right. The correct output is ##21##.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

You can assume that the number n fits into the standard int type of your language.
Conversely, if that standard int type implements arbitrary-precision integers, you must support (in theory) an arbitrarily large n.

Test cases

```<code>#1## -> ##1#
##4## -> #4###
1####1 -> ####11
1####2 -> ##21##
#026### -> 26####0
#000### -> #000###
###82399 -> ##82399#
51379#97 -> #9751379
#98##### -> ###98###
#######4## -> #4########
60752#1183 -> 8360752#11
####99366800## -> 366800######99
########9##### -> ###9##########
91#####515694837 -> 1#####5156948379
###6114558###### -> #6114558########
######219088736090042#### -> 9088736090042##########21
#46055080150577874656291186550000138168########### -> 0138168############4605508015057787465629118655000
568375993099127531613012513406622393034741346840434468680494753262730615610086255892915828812820699971764142551702608639695081452206500085233149468399533981039485419872101852######################3680 -> 99533981039485419872101852######################36805683759930991275316130125134066223930347413468404344686804947532627306156100862558929158288128206999717641425517026086396950814522065000852331494683
</code>```

Body:
Matlab(73)

  @(a)regexprep(a,'(\d*)#*(\d*)#*','${circshift($0,[0 str2num([$2 $1])])}')

This is using another approach that i wonder if @luis used it, because refering to his description there is some points in common while (un)?fortunately i dont understand the cropped Matl language.


答:
Batch, 36  + 13 + 9 - 26 = 32 bytes

```<code>:g
@echo ab%0pqrstuvwxyz
:lfdijkmn
</code>```

Requires that the batch file itself be named cdefghijklmno. Scored as 36 (size of file cdefghijklmno) + 13 (size of filename cdefghijklmno) + 9 (commented letters) - 26.

Edit: Saved 29 bytes even under my scoring scheme thanks to @ΈρικΚωνσταντόπουλος.

Title: Output the alphabet using the alphabet

Body:
Batch, 36  + 13 + 9 - 26 = 32 bytes

:g
@echo ab%0pqrstuvwxyz
:lfdijkmn

Requires that the batch file itself be named cdefghijklmno. Scored as 36 (size of file cdefghijklmno) + 13 (size of filename cdefghijklmno) + 9 (commented letters) - 26.

Edit: Saved 29 bytes even under my scoring scheme thanks to @ΈρικΚωνσταντόπουλος.


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

答:
ListSharp

factoid: ListSharp is an interpeted langauge for list manipulation and web scraping, still in development yet it can already do some neat stuff!

syntax is heavily word based so a good amount of votes will be needed for functional snipplets

Length 4 snipplet:

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

SHOW is the standard STDOUT of ListSharp and lets you display a variable in complete disregard to its type

Ex:

```<code>SHOW = "Hello world"
SHOW = {"1","2"} + "3"
SHOW = variable_name
</code>```

Title: Showcase of Languages

Body:
ListSharp

factoid: ListSharp is an interpeted langauge for list manipulation and web scraping, still in development yet it can already do some neat stuff!

syntax is heavily word based so a good amount of votes will be needed for functional snipplets

Length 4 snipplet:

SHOW

SHOW is the standard STDOUT of ListSharp and lets you display a variable in complete disregard to its type

Ex:

SHOW = "Hello world"
SHOW = {"1","2"} + "3"
SHOW = variable_name


答:
TSQL(Sqlserver 2012), 49 bytes

```<code>DECLARE @ VARCHAR(10) = 'hello',@x VARCHAR(10) = 'o'

PRINT IIF(@ LIKE'%'+@x+'%',REPLACE(@,@x,''),@+@x)
</code>```

Try it online!

Title: Toggle a string

Body:
The challenge involve simply toggling a string within another string.

Explanation

If the toggle string is a substring of the main string, remove all instances of the toggle string from the main string; otherwise, append the toggle string at the end of the main string.

Rules

All string are composed of printable ASCII characters

The function should take two parameters: the main string and the toggle string.

The main string can be empty.

The toggle string cannot be empty.

The result should be a string, which can be empty.

The shortest answer wins.

Examples

```<code>function toggle(main_string, toggle_string){ ... }

toggle('this string has 6 words ', 'now')
=> 'this string has 6 words now'

toggle('this string has 5 words now', ' now')
=> 'this string has 5 words'
</code>```

Tests cases

```<code>'','a'          => 'a'
'a','a'         => ''

'b','a'         => 'ba'
'ab','a'        => 'b'

'aba','a'       => 'b'
'ababa', 'aba'  => 'ba'
</code>```

Body:
TSQL(Sqlserver 2012), 49 bytes

DECLARE @ VARCHAR(10) = 'hello',@x VARCHAR(10) = 'o'

PRINT IIF(@ LIKE'%'+@x+'%',REPLACE(@,@x,''),@+@x)

Try it online!


答:
MATL, 29-26 = 3 bytes

```<code>'abcdehijkmnpqrstuvwxyzgolf'S
</code>```

Try it Online!

Title: Output the alphabet using the alphabet

Body:
MATL, 29-26 = 3 bytes

'abcdehijkmnpqrstuvwxyzgolf'S

Try it Online!


问:
How should you arrange your chairs?
You teach a class of students with interesting preferences for how their chairs are arranged. There are 3 very specific requirements they have for how the chairs are arranged:

They most be arranged in a rectangle, even if it means some chairs go empty.

There must be as few empty chairs as possible.

They must be as "squarey" as possible. Squarey-ness is determined by the distance between the width and the height of the rectangle, lower is better. For example, a rectangle that is 4x7 has a squarey-ness of 3.

To be more specific, the "score" of an arrangement is the distance between the width and height plus the number of chairs that would go empty.

Let's take an example. Let's say you have 13 students. You could arrange the chairs any of these ways:

```<code>1x13
2x7
3x5
4x4
</code>```

1x13 is not very squarey. In fact, 1 and 13 are 12 apart, so we give this arrangement 12 points. It also has 0 empty chairs, so we add 0 points, giving this arrangement a score of 12. Not that great.

2x7 is certainly better. 2 and 7 are only 5 apart, so we give this arrangement 5 points. However, if you actually arranged 2 rows of seven chairs, that would take 14 chairs, meaning one chair would be empty. So we add one point, giving this arrangement a score of 6.

We could also do 3x5. 3 and 5 are 2 apart, so +2 points. It takes 15 chairs, meaning we'd have two extra chairs, so another +2 points, for a score of 4.

Last option, 4x4. 4 and 4 are 0 apart, so we give this +0 points. 4x4 takes 16 chairs, so 3 chairs go empty, for a total score of 3. This is the optimal solution.

In case of a tie, the optimal solution is the one with less empty chairs.

The challenge

You must write a program or function that takes an integer and outputs the optimal arrangement of chairs for that number of students. IO can be in any reasonable format. Here is sample output for any number of students from 1 to 100:

```<code>1:  (1, 1)
2:  (1, 2)
3:  (2, 2)
4:  (2, 2)
5:  (2, 3)
6:  (2, 3)
7:  (3, 3)
8:  (3, 3)
9:  (3, 3)
10: (2, 5)
11: (3, 4)
12: (3, 4)
13: (4, 4)
14: (4, 4)
15: (4, 4)
16: (4, 4)
17: (3, 6)
18: (3, 6)
19: (4, 5)
20: (4, 5)
21: (3, 7)
22: (5, 5)
23: (5, 5)
24: (5, 5)
25: (5, 5)
26: (4, 7)
27: (4, 7)
28: (4, 7)
29: (5, 6)
30: (5, 6)
31: (4, 8)
32: (4, 8)
33: (6, 6)
34: (6, 6)
35: (6, 6)
36: (6, 6)
37: (5, 8)
38: (5, 8)
39: (5, 8)
40: (5, 8)
41: (6, 7)
42: (6, 7)
43: (5, 9)
44: (5, 9)
45: (5, 9)
46: (7, 7)
47: (7, 7)
48: (7, 7)
49: (7, 7)
50: (5, 10)
51: (6, 9)
52: (6, 9)
53: (6, 9)
54: (6, 9)
55: (7, 8)
56: (7, 8)
57: (6, 10)
58: (6, 10)
59: (6, 10)
60: (6, 10)
61: (8, 8)
62: (8, 8)
63: (8, 8)
64: (8, 8)
65: (6, 11)
66: (6, 11)
67: (7, 10)
68: (7, 10)
69: (7, 10)
70: (7, 10)
71: (8, 9)
72: (8, 9)
73: (7, 11)
74: (7, 11)
75: (7, 11)
76: (7, 11)
77: (7, 11)
78: (9, 9)
79: (9, 9)
80: (9, 9)
81: (9, 9)
82: (7, 12)
83: (7, 12)
84: (7, 12)
85: (8, 11)
86: (8, 11)
87: (8, 11)
88: (8, 11)
89: (9, 10)
90: (9, 10)
91: (7, 13)
92: (8, 12)
93: (8, 12)
94: (8, 12)
95: (8, 12)
96: (8, 12)
97: (10, 10)
98: (10, 10)
99: (10, 10)
100: (10, 10)
</code>```

As usual, this is code-golf, so standard loopholes apply, and the winner is the shortest answer in bytes.

答:
Q 58 Bytes

```<code>{c@d?&/d:+/(-/;*/)@\:+c:{((b<a)?1b)#+(b:-_-x%a;a:1+!x)}x}
</code>```

Lamba that calculates minimal cost for a given value (x) and returns a sequence of two values (width,height)

Adding name to that lambda requires other two char (ex f:{..} instead of {..})

Test

```<code>{..}'1+!100
</code>```

where {..} is the lambda. Read as "applies lambda to each value of 1+first 100 ints" (in other words to each value 1..100)

Generates

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

Explanation

Nested lamdba {((b<a)?1b)#+(b:-_-x%a;a:1+!x)} generates all candidates (widht,height) pairs for x chairs as two sequences (w1 w2 w3 ..; h1 h2 h3 ..) (widths and heights). Read from left to right, but evaluates from right to left

a:1+!x generates values 1..x and assign that sequence to a

-_- is negate floor negate, and implements ceil (ceil is not a primitive of the language)

b:-_-x%a applies ceil to each value of x divided by any item im a, and assign the resulting sequence to b. In other words, b is ceil each x dividedBy each 1..x

+(b;a) return a secuence composed of seq a and seq b, an then flips it (the result is a sequence of pair where i-pair contains element i of a and element i of b)

b<a compares item by item of b and a, and generates a secuence of logical values (true=1b for each index where b[i]

s?x returns the first position of item x in sequence s. With (b<a)?1b We look for 1b (true value) in sequence resulting of compare b and a, and get first position where b

n#s takes n first n items from seq s. We want to discard duplicate pairs, so we stop when first item of a pair < second item (ex. consider 13,1 but not 1,13).

As a side effect, each pair of the resulting sequence are of decreasing distance between a and b (ex (13 1; 7 2; 5 3; 4 4)

The candidate pair generated by nested lambda are assigned to c. We then flip c (obtains b,a again) and applies two functions to that argument: */ multiplies over, and -/ subtract over. The result of (-/;*/)@\:+c is the difference and product of each pair. +/ is sum over, and calculares final cost. The cost of each patir is assigned to d

&/ is minimum over, so &/d is the minimum cost. With d?&/d we find the first occurrence of minimum cost in d, and with c@.. we retrieve the pair at that position. As each pair is of decreasing distante between a and n, the first minimum found has the maximum distante betwwen other minimum pairs, so we apply tie rule correctly

Title: How should you arrange your chairs?

Body:
Q 58 Bytes

{c@d?&/d:+/(-/;*/)@\:+c:{((b<a)?1b)#+(b:-_-x%a;a:1+!x)}x}

Lamba that calculates minimal cost for a given value (x) and returns a sequence of two values (width,height)

Adding name to that lambda requires other two char (ex f:{..} instead of {..})

Test

{..}'1+!100

where {..} is the lambda. Read as "applies lambda to each value of 1+first 100 ints" (in other words to each value 1..100)

Generates

1 1
2 1
2 2
2 2
3 2
3 2
3 3
3 3
3 3
5 2
4 3
4 3
4 4
4 4
4 4
4 4
6 3
6 3
5 4
5 4
7 3
5 5
..

Explanation

Nested lamdba {((b<a)?1b)#+(b:-_-x%a;a:1+!x)} generates all candidates (widht,height) pairs for x chairs as two sequences (w1 w2 w3 ..; h1 h2 h3 ..) (widths and heights). Read from left to right, but evaluates from right to left

a:1+!x generates values 1..x and assign that sequence to a

-_- is negate floor negate, and implements ceil (ceil is not a primitive of the language)

b:-_-x%a applies ceil to each value of x divided by any item im a, and assign the resulting sequence to b. In other words, b is ceil each x dividedBy each 1..x

+(b;a) return a secuence composed of seq a and seq b, an then flips it (the result is a sequence of pair where i-pair contains element i of a and element i of b)

b<a compares item by item of b and a, and generates a secuence of logical values (true=1b for each index where b[i]

s?x returns the first position of item x in sequence s. With (b<a)?1b We look for 1b (true value) in sequence resulting of compare b and a, and get first position where b

n#s takes n first n items from seq s. We want to discard duplicate pairs, so we stop when first item of a pair < second item (ex. consider 13,1 but not 1,13).

As a side effect, each pair of the resulting sequence are of decreasing distance between a and b (ex (13 1; 7 2; 5 3; 4 4)

The candidate pair generated by nested lambda are assigned to c. We then flip c (obtains b,a again) and applies two functions to that argument: */ multiplies over, and -/ subtract over. The result of (-/;*/)@\:+c is the difference and product of each pair. +/ is sum over, and calculares final cost. The cost of each patir is assigned to d

&/ is minimum over, so &/d is the minimum cost. With d?&/d we find the first occurrence of minimum cost in d, and with c@.. we retrieve the pair at that position. As each pair is of decreasing distante between a and n, the first minimum found has the maximum distante betwwen other minimum pairs, so we apply tie rule correctly


问:
Find all the Solutions to this Number Puzzle in the Shortest Time Possible

History

My company sends out a weekly newsletter to everyone within the company. Included in these newsletters is a riddle, along with a shoutout to whomever in the company was the first to email/provide a solution to last week's riddle. Most of these riddles are quite trivial, and honestly pretty dull for a tech company, but there was one, several months back, that caught my attention.

The Original Riddle:

Given the shape below:

You have the Natural Numbers from 1 to 16. Fit them all into this shape, such that all the contiguous rows and contiguous columns sum up to 29.

For example, one such solution to this puzzle (which was the "canonical" solution I submitted to the newsletter) was the following:

However, in the course of solving it, I found some rather interesting information:

There are significantly more solutions than just that one; in fact, there are 9,368 Solutions.

If you expand the ruleset to only require that rows and columns be equal to each other, not necessarily 29, you get 33,608 solutions:

4,440 Solutions for a sum of 27.

7,400 Solutions for a sum of 28.

9,368 Solutions for a sum of 29.

6,096 Solutions for a sum of 30.

5,104 Solutions for a sum of 31.

1,200 Solutions for a sum of 32.

So me and my coworkers (though mostly just my manager, since he was the only other person than me with "General Purpose" programming skills) set out on a challenge, that lasted for most of the month—we had other, actual job-related obligations we had to attend to—to try to write a program which would find every single solution in the fastest way possible.

Original Statistics

The very first program I wrote to solve the problem simply checked random solutions over and over, and stopped when it found a solution. If you've done Mathematical analysis on this problem, you probably already know that this shouldn't have worked; but somehow I got lucky, and it took the program only a minute to find a single solution (the one I posted above). Repeat runs of the program often took as much as 10 or 20 minutes, so obviously this wasn't a rigorous solution to the problem.

I switched over to a Recursive Solution which iterated through every possible permutation of the puzzle, and discarded lots of solutions at once by eliminating sums that weren't adding up. I.E. if the first row/column I was comparing already weren't equal, I could stop checking that branch immediately, knowing that nothing else permuted into the puzzle would change that.

Using this algorithm, I got the first "proper" success: the program could generate and spit out all 33,608 solutions in about 5 minutes.

My manager had a different approach: knowing based on my work that the only possible solutions had sums of 27, 28, 29, 30, 31, or 32, he wrote a multi-threaded solution which checked possible sums only for those specific values. He managed to get his program to run in only 2 minutes. So I iterated again; I hashed all possible 3/4 digit sums (at the start of the program; it's counted in the total runtime) and used the "partial sum" of a row to look-up the remaining value based on a previously completed row, rather than testing all remaining values, and brought the time down to 72 seconds. Then with some multi-threading logic, I got it down to 40 seconds. My manager took the program home, performed some optimizations on how the program ran, and got his down to 12 seconds. I reordered the evaluation of the rows and columns, and got mine down to 8 seconds.

The fastest either of us got our programs after a month was 0.15 seconds for my manager, and 0.33 seconds for me. I ended up claiming that my program was faster though, since my manager's program, while it did find all solutions, wasn't printing them out into a text file. If he added that logic to his code, it often took upwards of 0.4-0.5 seconds.

We've since allowed our intra-personal challenge to subsist, but of course, the question remains: can this program be made faster?

That's the challenge I'm going to pose to you guys.

Your Challenge

The parameters we worked under relaxed the "sum of 29" rule to instead be "all rows/columns' sums equal", and I'm going to set that rule for you guys too. The Challenge, therefore, is: Write a program that finds (and Prints!) all solutions to this riddle in the shortest time possible. I'm going to set a ceiling on submitted solutions: If the program takes more than 10 seconds on a relatively decent computer (<8 years old), it's probably too slow to be counted.

Also, I have a few Bonuses for the puzzle:

Can you generalize the solution so that it works for any set of 16 numbers, not just int[1,16]? Timing score would be evaluated based on the original prompt number set, but passed through this codepath. (-10%)

Can you write the code in a way that it gracefully handles and solves with duplicate numbers? This isn't as straightforward as it might seem! Solutions which are "visually identical" should be unique in the result set. (-5%)

Can you handle negative numbers? (-5%)

You can also try to generate a solution that handles Floating-Point Numbers, but of course, don't be shocked if that fails utterly. If you do find a robust solution though, that might be worth a large bonus!

For all intents and purposes, "Rotations" are considered to be unique solutions. So a solution that is just a rotation of a different solution counts as its own solution.

The IDEs I have working on my computer are Java and C++. I can accept answers from other languages, but you may need to also provide a link to where I can get an easy-to-setup runtime environment for your code.

答:
C - near 0.5 sec

This very naive program give all the solutions in half a second on my 4 years old laptop. No multithread, no hashing.

Windows 10, Visual Studio 2010, CPU core I7 64 bit

Try online on ideone

#include <stdio.h>
#include <time.h>

int inuse[16];
int results[16+15+14];

FILE *fout;

int check(int number)
{
    if (number > 0 && number < 17 && !inuse[number-1])
    {
        return inuse[number-1]=1;
    }
    return 0;
}

void free(int number)
{
    inuse[number-1]=0;
}

void out(int t, int* p)
{
    int i;
    fprintf(fout, "\n%d",t);
    for(i=0; i< 16; i++) fprintf(fout, " %d",*p++);
}

void scan()
{
    int p[16];
    int t,i;
    for (p[0]=0; p[0]++<16;) if (check(p[0]))
    {
        for (p[1]=0; p[1]++<16;) if (check(p[1]))
        {
            for (p[2]=0; p[2]++<16;) if (check(p[2]))
            {
                t = p[0]+p[1]+p[2]; // top horiz: 0,1,2
                for (p[7]=0; p[7]++<16;) if (check(p[7]))
                {
                    if (check(p[11] = t-p[7]-p[2])) // right vert: 2,7,11
                    {
                        for(p[9]=0; p[9]++<16;) if (check(p[9]))
                        {
                            for (p[10]=0; p[10]++<16;) if (check(p[10]))
                            {
                                if (check(p[12] = t-p[9]-p[10]-p[11])) // right horiz: 9,10,11,12
                                {
                                    for(p[6]=0; p[6]++<16;) if (check(p[6]))
                                    {
                                        if (check(p[15] = t-p[0]-p[6]-p[9])) // middle vert: 0,6,9,15
                                        {
                                            for(p[13]=0; p[13]++<16;) if (check(p[13]))
                                            {
                                                if (check(p[14] = t-p[13]-p[15])) // bottom horiz:  13,14,15
                                                {
                                                    for(p[4]=0; p[4]++<16;) if (check(p[4]))
                                                    {
                                                        if (check(p[8] = t-p[4]-p[13])) // left vert: 4,8,13
                                                        {
                                                            for(p[3]=0; p[3]++<16;) if (check(p[3]))
                                                            {
                                                                if (check(p[5] = t-p[3]-p[4]-p[6])) // left horiz: 3,4,5,6
                                                                {
                                                                    ++results[t];
                                                                    out(t,p);
                                                                    free(p[5]);
                                                                }
                                                                free(p[3]);
                                                            }
                                                            free(p[8]);
                                                        }
                                                        free(p[4]);
                                                    }
                                                    free(p[14]);
                                                }
                                                free(p[13]);
                                            }
                                            free(p[15]);
                                        }
                                        free(p[6]);
                                    }
                                    free(p[12]);
                                }
                                free(p[10]);
                            }
                            free(p[9]);
                        }
                        free(p[11]);
                    }
                    free(p[7]);
                }
                free(p[2]);
            }
            free(p[1]);
        }
        free(p[0]);
    }
    for(i=0;i<15+16+14;i++)
    {
        if(results[i]) printf("%d %d\n", i, results[i]);
    }
}

void main()
{
    clock_t begin, end;
    double time_spent;
    begin = clock();

    fout = fopen("c:\\temp\\puzzle29.txt", "w");
    scan();
    fclose(fout);

    end = clock();
    time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
    printf("Time %g sec\n", time_spent);
}
```


答:
05AB1E, <s>27</s> 26 - 26 = 0 bytes

Thanks to Katenkyo for saving 1 byte :). Code:

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

Try it online!.

Title: Output the alphabet using the alphabet

Body:
The title is pretty self-explanatory, isn't it?

Your task is to output the alphabet (the string "abcdefghijklmnopqrstuvwxyz") to STDOUT, using each and every letter of the alphabet in your program once and only once.

Oh, and for a bit of extra fun?

The letters "g", "o", "l" and "f" must be in order (just for the code to be a bit more code-y).

Rules:

Only standard letters of the alphabet from ASCII count as letters (ë != e).

Both uppercase and lowercase characters count as letters (if you have E, you are not allowed to have e).

You are allowed to use comments, but every character in the comment is equal to 2 bytes.

Your final score will be the byte-count of your program, subtracted by 26.

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

Body:
05AB1E, <s>27</s> 26 - 26 = 0 bytes

Thanks to Katenkyo for saving 1 byte :). Code:

golfAqbcdehijkmnprstuvwxyz

Try it online!.


问:
Shortest infinite loop producing no output
Your task is to create the shortest infinite loop!

The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.

The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.

The program must not write anything to STDERR.

Feel free to use a language (or language version) even if it's newer than this challenge.
-Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. :D

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.

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

There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like #[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes.

Standard loopholes are not allowed.

(I have taken some of these rules from Martin Büttner's "Hello World" challenge)

Please feel free to post in the comments to tell me how this challenge could be  improved.

Catalogue

This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:

```<code># Language name, X bytes
</code>```

Obviously replacing Language name and X bytes with the proper items. If you want to link to the languages' website, use this template, as posted above:

```<code>#[Language name](http://link.to/the/language), X bytes
</code>```

Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)

var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"//api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+lang+'').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang,user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;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">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Glypho, 3 bytes

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

Pushes 1 to the stack, then loops while the top of the stack isn't 0. Uses the Java interpreter. This is shorthand for the following "real" Glypho program:

```<code>  !" ! " !"!
</code>```

Body:
Glypho, 3 bytes

1[]

Pushes 1 to the stack, then loops while the top of the stack isn't 0. Uses the Java interpreter. This is shorthand for the following "real" Glypho program:

  !" ! " !"!


问:
Calculator that adds char values

Task

Build a calculator, that takes any string, from a file, stdin or whatever, and adds up all the values of the chars.

Example

```<code>Input
Hello World!

Output
1085
</code>```

Rules

The calculator needs to accept just ASCII encoding.

The shortest code wins.

Notes

Regarding to the comment of m.buettner, I need to say, I didn't thought of the multibyte part.

So I leave it as a bonus thing aswell.

The calculator should be run as written, so no need to modify before compiling or interpreting.

Bonus

Thanks to Synthetica, here is one more bonus,

The program that has the lowest output when you use its code as its input wins gets a star.

I don't want to modify it completly.

If you write it additional to output the (right) value in UTF-8 you get a star.

The code that executes fastest on my Laptop (Lenovo Yoga 13 Intel Core i5 3317U 1.7Ghz, 8GB RAM, 128GB SSD, Intel HD 4000, Windows 8) gets a star.

Web codes will run first under IE11 with chakra and then in FireFox 29.0.1 with SpiderMonkey

Linux code will run on a Raspberry Pi with Raspbian.

The teststring is this:

```<code>q/%8hnp>T%y?'wNb\},9krW &D9']K$n;l.3O+tE*$*._B^s!@k\&Cl:EO1zo8sVxEvBxCock_I+2o6 yeX*0Xq:tS^f)!!7=!tk9K<6#/E`ks(D'$z$\6Ac+MT&[s[]_Y(`<g%"w%cW'`c&q)D$0#C$QGf>?A$iawvc,}`9!('`c&q)D$0#C$QGf>?A$iawvc,}`9!(
</code>```

Have fun coding :)

Bonusscoring

I plan to do the scoring at this Saturday so the 07.06.14, all answers after that date won't get bonus points ;)

You can download the code I gonna use for testing here feel free to fork and improve it :)

Little update because of the bonus, my laptop is partially broken so I will do it probably next weekend, I am really sorry for that :(

答:
Python 3, 37 bytes

```<code>print(sum([ord(c) for c in input()]))
</code>```

There's a shorter one, but this is possible as well. It converts the string into a list will all the ASCII values of the characters and adds them together using sum().

Star version, 55 bytes

```<code>a=sum([ord(c) for c in input()]);print(a);print(chr(a))
</code>```

Now gimme my gold star.

Title: Calculator that adds char values

Body:
Python 3, 37 bytes

print(sum([ord(c) for c in input()]))

There's a shorter one, but this is possible as well. It converts the string into a list will all the ASCII values of the characters and adds them together using sum().

Star version, 55 bytes

a=sum([ord(c) for c in input()]);print(a);print(chr(a))

Now gimme my gold star.


问:
What's the chance that I'll win a door prize?
My local ACM chapter gives out door prizes to people who come to the meetings. You get an increased chance of winning if you solve the programming puzzle, however (but I always solve that puzzle). Thus, some people have 1 entry, while others have 2. But wait! The way the raffle program works is not by adding in another entry when someone solves the puzzle. Instead, it keeps track of the number of "lives" a person has, decrementing that if that person is chosen in each pass of it's random sampling algorithm. So it works like this:

```<code>Doorknob: 1.  xnor: 2.  Justin: 2.  Alex: 1.  Dennis: 2.
</code>```

Then the program randomly chooses one of [Doorknob, xnor, Justin, Alex, Dennis], decrements the number (say it chooses Justin):

```<code>Doorknob: 1.  xnor: 2.  Justin: 1.  Alex: 1. Dennis: 2.
</code>```

And repeats. If someone's number of "lives" goes to 0 (let's choose Justin again), they're removed from the list:

```<code>Doorknob: 1.  xnor: 2.  Alex: 1.  Dennis: 2.
</code>```

This continues until there's one person left; that person is the winner.

Now the real question is, what was the probability that I would have won?

You will be given two inputs:

n. This is the number of people entered into the challenge

k. This is the number of people (of those n) who have 2 lives. This number always includes you.

So if I had a function p and called p(10, 5), that would be the probability of winning the prize where there are 10 people total, 5 of which only have 1 life, whereas 5 (including you) have 2 lives.

You are expected to output the probability of winning either exactly, or as a decimal. At any rate, answers must be accurate up to and including the 4th decimal place after the decimal point. Whether or not you round to that digit is up to you.

Your solution may be a randomized solution which outputs the answer to the 4th decimal place with high probability. You may assume that the built in RNG you use is truly random, and it must output the correct answer with at least 90% probability.

Furthermore, your code need only work for n, k <= 1000, although I did provide test cases larger than that for those curious.

Test Cases

Note: some of these are general formulae.

```<code>n,    k   |  output
----------+---------
1,    1   |  1
2,    2   |  0.5
2,    1   |  0.75
3,    1   |  11/18 = 0.611111111
1000, 1   |  0.007485470860550352
4,    3   |  0.3052662037037037
k,    k   |  1/k
n,    1   |  (EulerGamma + PolyGamma[1 + n])/n    (* Mathematica code *)
          |  (γ + ψ(1 + n))/n
10,   6   |  0.14424629234373537
300,  100 |  0.007871966408910648
500,  200 |  0.004218184180294532
1000, 500 |  0.0018008560286627948
---------------------------------- Extra (not needed to be a valid answer)
5000, 601 |  0.0009518052922680399
5000, 901 |  0.0007632938197806958
</code>```

For another few checks, take p(n, 1) * n as follows:

```<code>n     |  output
------+---------
1     | 1
2     | 1.5
3     | 1.8333333333333335
10    | 2.928968253968254
100   | 5.1873775176396215
-------------------------- Extra (not needed to be a valid answer)
100000| 12.090146129863305
</code>```

答:
MATL, 42 bytes

```<code>:<~QXJx`J`tf1Zry0*1b(-tzq]f1=vts3e8<]6L)Ym
</code>```

This uses a probabilistic (Monte Carlo ) approach. The experiment is run a large number of times, from which the probability is estimated. The number of realizations is selected to ensure that the result is correct up to the fourth decimal with probability at least 90%. However, this takes a very long time and a lot of memory. In the link below the number of realizations has been reduced by a factor of 106 so that the program ends in a reasonable amout of
time; and only the first decimal is guaranteed to be accurate with at least 90% probability.

EDIT (July 29, 2016): due to changes in the language, 6L needs to be replaced by 3L. The link below incorporates that modification.

Try it online!

Background

Let p denote the probability to be computed. The experiment described in the challenge will be run for a number n of times. Each time, either you win the prize (“success”) or you don't. Let N be the number of successes. The desired probability can be estimated from N and n. The larger n is, the more accurate the estimation will be. The key question is how to select n to fulfill to the desired accuracy, namely, to assure that at least 90% of times the error will be less than 10−4.

Monte Carlo methods can be

Fixed-size: a value of n is fixed in advance (and then N is random);

Variable-size: n is determined on the fly by the simulation results.

Among the second category, a common used method is to fix N (desired number of successes) and keep simulating until that number of successes is achieved. Thus n is random. This technique, called inverse binomial sampling or negative-binomial Monte Carlo, has the advantage that the accuracy of the estimator can be bounded. For this reason it will be used here.

Specifically, with negative-binomial Monte Carlo x = (N−1)/(n−1) is an unbiased estimator of p; and the probability that x deviates from p by more than a given ratio can be upper-bounded. According to equation (1) in this paper (note also that the conditions (2) are satisfied), taking N = 2.75·108 or larger ensures that p/x belongs to the interval [1.0001, 0.9999] with at least 90% probability. In particular, this implies that x is correct up to the 4th decimal place with at least 90% probability, as desired.

Code explained

The code uses N = 3e8 to save one byte. Note that doing this many simulations would take a long time. The code in the link uses N = 300, which runs in a more reasonable amount of time (less than 1 minute in the online compiler for the first test cases); but this only assures that the first decimal is correct with probability at least 90%.

```<code>:        % Take k implicitly. Range [1 ... k]
<~       % Take n implicitly. Determine if each element in the previous array is
         % less than or equal than n
Q        % Add 1. This gives an array [2 ... 2 1 ... 1]
XJx      % Copy to clipboard J. Delete from stack
`        % Do...while. Each iteration is a Monte Carlo realization, until the
         % desired nunber of successes is reached
  J      %   Push previously computed array [2 ... 2 1 ... 1]
  `      %   Do...while. Each iteration picks one door and decrements it, until
         %   there is only one
    t    %     Duplicate
    f    %     Indices of non-zero elements of array
    1Zr  %     Choose one of them randomly with uniform distribution
    y0*  %     Copy of array with all values set to 0
    1b(  %     Assign 1 to chosen index
    -    %     Subtract
    tzq  %     Duplicate. Number of nonzero elements minus 1. This is falsy if
         %     there was only one nonzero value; in this case the loop is exited
  ]      %   End do...while
  f1=    %   Index of chosen door. True if it was 1 (success), 0 otherwise
  v      %   Concatenate vertically to results from previous realizations
  ts3e8< %   Duplicate. Is the sum less than 3e8? If so, the loop is exited
]        % End do...while
6L)      % Remove last value (which is always 1)
Ym       % Compute mean. This gives (N-1)/(n-1). Implicitly display
</code>```

Body:
MATL, 42 bytes

:<~QXJx`J`tf1Zry0*1b(-tzq]f1=vts3e8<]6L)Ym

This uses a probabilistic (Monte Carlo ) approach. The experiment is run a large number of times, from which the probability is estimated. The number of realizations is selected to ensure that the result is correct up to the fourth decimal with probability at least 90%. However, this takes a very long time and a lot of memory. In the link below the number of realizations has been reduced by a factor of 106 so that the program ends in a reasonable amout of
time; and only the first decimal is guaranteed to be accurate with at least 90% probability.

EDIT (July 29, 2016): due to changes in the language, 6L needs to be replaced by 3L. The link below incorporates that modification.

Try it online!

Background

Let p denote the probability to be computed. The experiment described in the challenge will be run for a number n of times. Each time, either you win the prize (“success”) or you don't. Let N be the number of successes. The desired probability can be estimated from N and n. The larger n is, the more accurate the estimation will be. The key question is how to select n to fulfill to the desired accuracy, namely, to assure that at least 90% of times the error will be less than 10−4.

Monte Carlo methods can be

Fixed-size: a value of n is fixed in advance (and then N is random);

Variable-size: n is determined on the fly by the simulation results.

Among the second category, a common used method is to fix N (desired number of successes) and keep simulating until that number of successes is achieved. Thus n is random. This technique, called inverse binomial sampling or negative-binomial Monte Carlo, has the advantage that the accuracy of the estimator can be bounded. For this reason it will be used here.

Specifically, with negative-binomial Monte Carlo x = (N−1)/(n−1) is an unbiased estimator of p; and the probability that x deviates from p by more than a given ratio can be upper-bounded. According to equation (1) in this paper (note also that the conditions (2) are satisfied), taking N = 2.75·108 or larger ensures that p/x belongs to the interval [1.0001, 0.9999] with at least 90% probability. In particular, this implies that x is correct up to the 4th decimal place with at least 90% probability, as desired.

Code explained

The code uses N = 3e8 to save one byte. Note that doing this many simulations would take a long time. The code in the link uses N = 300, which runs in a more reasonable amount of time (less than 1 minute in the online compiler for the first test cases); but this only assures that the first decimal is correct with probability at least 90%.

:        % Take k implicitly. Range [1 ... k]
<~       % Take n implicitly. Determine if each element in the previous array is
         % less than or equal than n
Q        % Add 1. This gives an array [2 ... 2 1 ... 1]
XJx      % Copy to clipboard J. Delete from stack
`        % Do...while. Each iteration is a Monte Carlo realization, until the
         % desired nunber of successes is reached
  J      %   Push previously computed array [2 ... 2 1 ... 1]
  `      %   Do...while. Each iteration picks one door and decrements it, until
         %   there is only one
    t    %     Duplicate
    f    %     Indices of non-zero elements of array
    1Zr  %     Choose one of them randomly with uniform distribution
    y0*  %     Copy of array with all values set to 0
    1b(  %     Assign 1 to chosen index
    -    %     Subtract
    tzq  %     Duplicate. Number of nonzero elements minus 1. This is falsy if
         %     there was only one nonzero value; in this case the loop is exited
  ]      %   End do...while
  f1=    %   Index of chosen door. True if it was 1 (success), 0 otherwise
  v      %   Concatenate vertically to results from previous realizations
  ts3e8< %   Duplicate. Is the sum less than 3e8? If so, the loop is exited
]        % End do...while
6L)      % Remove last value (which is always 1)
Ym       % Compute mean. This gives (N-1)/(n-1). Implicitly display