答:
CJam (60 bytes)

```<code>{:Pmr<1/2P,#{:z{_:+\,/}f%:C,{P{C\f{.-Yf#:+}_:e<#1$=},\;}%}*}
</code>```

This is a function which takes its input in the form k p on the stack. It assumes that the points are represented with doubles, not ints. It doesn't implicitly assume anything about the dimension of the points, so it would cluster equally well in 6-D Euclidean space as in the specified 2-D.

Online demo

Title: Golf the K-means algorithm

Body:
K-means is a standard unsupervised clustering algorithm, which, given a set of "points" and a number of clusters K, will assign each "point" to one of K clusters.

Pseudo-Code of K-means

Note that there are many variants of K-means. You have to implement the algorithm I am describing below. You may have some variation on the algorithm or use built-ins as long as you would get the same result as this algorithm given the same initial points.

In this challenge, all inputs will be points on the 2D plane (each point is represented by its coordinates in x and y).

```<code>Inputs: K, the number of clusters
        P, the set of points

Choose K points of P uniformly at random
Each chosen point is the initial centroid of its cluster

Loop:
     For each point in P:
         Assign to the cluster whose centroid is the nearest (Euclidean distance)
         In case of a tie, any of the tied cluster can be chosen

     Recompute the centroid of each cluster:
         Its x coordinate is the average of all x's of the points in the cluster
         Its y coordinate is the average of all y's of the points in the cluster

Until the clusters don't change from one iteration to the next

Output: the set of clusters
</code>```

Inputs and Outputs

You may take K and P through STDIN, or as a function argument, etc.

P and the points in P can be represented using any structure that is natural for set/lists in your language of choice.

K is a strictly positive integer.

You may assume that inputs are valid.

There will always be at least K points in P.

You may output the clusters to STDOUT, return them from a function, etc.

The ordering of the clusters and the ordering inside the clusters is unimportant.
-You can either return groups of points to represent clusters, or each point labeled with an identifier for the cluster (e.g. an integer).

Test cases

Since the resulting clusters depend on which points were initially chosen, you may not all get the same results (or the same result each time you run your code).

Therefore, only take the output as an example output.

```<code>Input:
  K = 1
  P = [[1,2.5]]
Output:
  [[[1,2.5]]]

Input:
  K = 3
  P = [[4,8], [15,16], [23,42], [-13.37,-12.1], [666,-666]]
Output:
  [[[666,-666]],[[-13.37,-12.1],[4,8]],[[15,16],[23,42]]]

Input:
  K = 2
  P = [[1,1], [1,1], [1,1]]
Output:
  [[[1,1]],[[1,1],[1,1]]]
</code>```

Scoring

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

Body:
CJam (60 bytes)

{:Pmr<1/2P,#{:z{_:+\,/}f%:C,{P{C\f{.-Yf#:+}_:e<#1$=},\;}%}*}

This is a function which takes its input in the form k p on the stack. It assumes that the points are represented with doubles, not ints. It doesn't implicitly assume anything about the dimension of the points, so it would cluster equally well in 6-D Euclidean space as in the specified 2-D.

Online demo


问:
Find the remaining side of the tangential quadrilateral
(Taken from https://en.wikipedia.org/wiki/File:Tangential_quadrilateral.svg)

A tangential quadrilateral (see example above) is a quadrilateral in which a circle can be inscribed.

Your task is to find the possible value of d given a, b, and c.

Specs

a, b, c will all be positive integers.

If no possible value of d exists, output 0.

Scoring

This is code-golf. Shortest solution in bytes wins.

Testcases

```<code>a b c d
3 4 4 3
1 2 3 2
1 5 3 0
</code>```

答:
Python, 25 bytes

```<code>lambda a,b,c:max(0,a-b+c)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Python, 25 bytes

lambda a,b,c:max(0,a-b+c)


问:
The rice and chess problem
An Indian legend tells the story of the alleged inventor of the chess game, who impressed the emperor of India with his game so much that he would get rewarded with anything asked.

The man said he wanted to be paid in rice. He wanted a grain of rice for the first square of the chessboard, two for the second, four for the third, eight for the fourth, and so on, until the 64th square.

The emperor was amazed that the man asked for such a small reward, but as his mathematicians started counting, he ended up losing one of his provinces.

Task

Given the length of the side of a hypothetical chessboard (which is 8 on a default chessboard) and the multiplier between squares (which is 2 in the legend), calculate the number of grains of rice the emperor must pay to the man.

Notes

The side length will always be a positive integer. The multiplier could instead be any kind of rational number.

If your language of choice can't display very large numbers, it's okay as long as your program can correctly process smaller inputs.

Also if your language of choice rounds larger values (with exponential notations), it's okay if those values are approximately correct.

Testcases

```<code>Input (side length, multiplier) => Output
8, 2                            => 18446744073709551615
3, 6                            => 2015539
7, 1.5                          => 850161998.2854
5, -3                           => 211822152361
256, 1                          => 65536
2, 2                            => 15
2, -2                           => -5
</code>```

Please note that the explicit formula

```<code>result = (multiplier ^ (side ^ 2) - 1) / (multiplier - 1)
</code>```

Performs wrong on multiplier = 1, as

```<code>1 ^ (side ^ 2) - 1 = 0
1 - 1 = 0
0 / 0 != side ^ 2 (as it should be)
</code>```

Scoring

This is code-golf. Shortest answer in bytes wins.

答:
PHP, <s>58</s> 54 bytes

```<code><?function a($n,$m){$n*=$n;echo(1-$m**$n)/(1-$m)?:$n;}
</code>```

This just uses the summation formula to show the value, after checking if the multiplier is 1 (which returns NAN in the formula).

Title: The rice and chess problem

Body:
PHP, <s>58</s> 54 bytes

<?function a($n,$m){$n*=$n;echo(1-$m**$n)/(1-$m)?:$n;}

This just uses the summation formula to show the value, after checking if the multiplier is 1 (which returns NAN in the formula).


问:
Swap the Alphabet
In this challenge, you will be "reversing" the alphabet or swapping a-z with z-a. This is commonly known as the Atbash cypher.

Because this transformation makes the output look like some foreign language, your code will need to be as short as possible.

Examples

```<code>abcdefghijklmnopqrstuvwxyz
zyxwvutsrqponmlkjihgfedcba

Programming Puzzles & Code Golf
Kiltiznnrmt Kfaaovh & Xlwv Tlou

Hello, World!
Svool, Dliow!
</code>```

Specification

The input may contain multiple lines, and will be ASCII-only

No additional whitespace should be added to the output

Case must be preserved

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

This is code-golf so shortest code in bytes wins

答:
05AB1E, 5 bytes

```<code>žnžo‡
</code>```

Uses CP-1252 character set.

Try it online!

Explanation:

```<code>žn    - Push [A-Za-z]
  žo  - Push [Z-Az-a]
    ‡ - Transliterate.
</code>```

Title: Swap the Alphabet

Body:
05AB1E, 5 bytes

žnžo‡

Uses CP-1252 character set.

Try it online!

Explanation:

žn    - Push [A-Za-z]
  žo  - Push [Z-Az-a]
    ‡ - Transliterate.

ContentLicense: CC BY-SA 4.0


问:
Filter this string!
Your task is to write a program that will filter out some characters in a string, so that the remaining spells out (part of) the other string.

Let's say we received the string "123456781234567812345678", and the second string is "314159".

First, we put a pointer on the second string:

```<code>314159
^
</code>```

So the pointer is now on 3, and we replace the not-3 characters with a hashtag until the first 3:

```<code>##3456781234567812345678
</code>```

We then move the pointer to the next character until we have iterated through the string.

Specs

You may use any character to replace "#", and the first string will not contain the hashtag (or the replaced hashtag).

The second string will always be longer than enough.

Both strings will only contain ASCII printable characters (U+0020-U+007F).

Testcases

```<code>input1: 123456781234567812345678
input2: 314159
output: ##3#####1##4####1###5###

input1: abcdefghijklmnopqrstuvwxyz
input2: dilemma
output: ###d####i##l##############
</code>```

答:
Mathcad, [tbd] bytes

Mathcad byte equivalence to be determined.   Note that the programming operators "while", "break" and "on error" only require 1 key-combination to enter (ctl-], ctl-{ and ctl-', respectively) - they cannot be typed verbatim.  What you see in the image is exactly what gets entered onto the Mathcad worksheet and the results are live - change a or b, or the function arguments, and the results update accordingly.

Title: Filter this string!


答:
PostgreSQL, 118 125 bytes

```<code>SELECT s,TRANSLATE(s,t||UPPER(t),REVERSE(t)||REVERSE(UPPER(t)))
FROM(SELECT text'Programming Puzzles & Code Golf's,text'abcdefghijklmnopqrstuvwxyz't)r
</code>```

SqlFiddleDemo

Output:

```<code>╔══════════════════════════════════╦═════════════════════════════════╗
║                s                 ║            translate            ║
╠══════════════════════════════════╬═════════════════════════════════╣
║ Programming Puzzles & Code Golf  ║ Kiltiznnrmt Kfaaovh & Xlwv Tlou ║
╚══════════════════════════════════╩═════════════════════════════════╝
</code>```

Input: SELECT text'...'s

EDIT:

Input as table:

```<code>SELECT s,TRANSLATE(s,t||UPPER(t),REVERSE(t)||REVERSE(UPPER(t)))
FROM i,(SELECT text'abcdefghijklmnopqrstuvwxyz't)r
GROUP BY s,t
</code>```

SqlFiddleDemo

Output:

```<code>╔══════════════════════════════════╦═════════════════════════════════╗
║                s                 ║            translate            ║
╠══════════════════════════════════╬═════════════════════════════════╣
║ Hello, World!                    ║ Svool, Dliow!                   ║
║ Programming Puzzles & Code Golf  ║ Kiltiznnrmt Kfaaovh & Xlwv Tlou ║
║ abcdefghijklmnopqrstuvwxyz       ║ zyxwvutsrqponmlkjihgfedcba      ║
╚══════════════════════════════════╩═════════════════════════════════╝
</code>```

Title: Swap the Alphabet

Body:
In this challenge, you will be "reversing" the alphabet or swapping a-z with z-a. This is commonly known as the Atbash cypher.

Because this transformation makes the output look like some foreign language, your code will need to be as short as possible.

Examples

```<code>abcdefghijklmnopqrstuvwxyz
zyxwvutsrqponmlkjihgfedcba

Programming Puzzles & Code Golf
Kiltiznnrmt Kfaaovh & Xlwv Tlou

Hello, World!
Svool, Dliow!
</code>```

Specification

The input may contain multiple lines, and will be ASCII-only

No additional whitespace should be added to the output

Case must be preserved

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

This is code-golf so shortest code in bytes wins

Body:
PostgreSQL, 118 125 bytes

SELECT s,TRANSLATE(s,t||UPPER(t),REVERSE(t)||REVERSE(UPPER(t)))
FROM(SELECT text'Programming Puzzles & Code Golf's,text'abcdefghijklmnopqrstuvwxyz't)r

SqlFiddleDemo

Output:

╔══════════════════════════════════╦═════════════════════════════════╗
║                s                 ║            translate            ║
╠══════════════════════════════════╬═════════════════════════════════╣
║ Programming Puzzles & Code Golf  ║ Kiltiznnrmt Kfaaovh & Xlwv Tlou ║
╚══════════════════════════════════╩═════════════════════════════════╝

Input: SELECT text'...'s

EDIT:

Input as table:

SELECT s,TRANSLATE(s,t||UPPER(t),REVERSE(t)||REVERSE(UPPER(t)))
FROM i,(SELECT text'abcdefghijklmnopqrstuvwxyz't)r
GROUP BY s,t

SqlFiddleDemo

Output:

╔══════════════════════════════════╦═════════════════════════════════╗
║                s                 ║            translate            ║
╠══════════════════════════════════╬═════════════════════════════════╣
║ Hello, World!                    ║ Svool, Dliow!                   ║
║ Programming Puzzles & Code Golf  ║ Kiltiznnrmt Kfaaovh & Xlwv Tlou ║
║ abcdefghijklmnopqrstuvwxyz       ║ zyxwvutsrqponmlkjihgfedcba      ║
╚══════════════════════════════════╩═════════════════════════════════╝


答:
Jolf, 4 bytes

```<code>\r0m4
</code>```

Replace \r with a literal return, or try it here! Explanation:

```<code>\r0m4
   m4  anti-sum of implicit input
\r0    max of `0` and the anti-sum
</code>```

Title: Find the remaining side of the tangential quadrilateral

Body:
(Taken from https://en.wikipedia.org/wiki/File:Tangential_quadrilateral.svg)

A tangential quadrilateral (see example above) is a quadrilateral in which a circle can be inscribed.

Your task is to find the possible value of d given a, b, and c.

Specs

a, b, c will all be positive integers.

If no possible value of d exists, output 0.

Scoring

This is code-golf. Shortest solution in bytes wins.

Testcases

```<code>a b c d
3 4 4 3
1 2 3 2
1 5 3 0
</code>```

Body:
Jolf, 4 bytes

\r0m4

Replace \r with a literal return, or try it here! Explanation:

\r0m4
   m4  anti-sum of implicit input
\r0    max of `0` and the anti-sum


答:
Java, 136 bytes

void i(int[]a,int[]b){int i=0,j=0,n=a.length;for(;i<b.length;i++)for(;j<n;j++)if(a[j]==b[i]){j++;break;}else a[j]=0;for(;j<n;)a[j++]=0;}
```

<h3>Ungolfed</h3>

<pre class="lang-java prettyprint-override"><code>void i(int[] a, int[] b) {
    int i = 0, j = 0, n = a.length;
    for (; i < b.length; i++)
        for (; j < n; j++)
            if (a[j] == b[i]) {
                j++;
                break;
            } else a[j] = 0;
    for (; j < n; ) a[j++] = 0;
}
</code>```

Notes

Uses the NUL character as replacement, any of the first 10 would do. If you wanted a visible replacement character, this would be one byte longer.

Input are two integer arrays of charcodes. int[] is one byte shorter than char[].

Outputs

```<code>Input 1:    123456781234567812345678
Input 2:    314159
Output:       3     1  4    1   5
Input 1:    abcdefghijklmnopqrstuvwxyz
Input 2:    dilemma
Output:        d    i  l
Input 1:    314asd159asdasd
Input 2:    314159
Output:     314   159
</code>```

Title: Filter this string!

Body:
Your task is to write a program that will filter out some characters in a string, so that the remaining spells out (part of) the other string.

Let's say we received the string "123456781234567812345678", and the second string is "314159".

First, we put a pointer on the second string:

```<code>314159
^
</code>```

So the pointer is now on 3, and we replace the not-3 characters with a hashtag until the first 3:

```<code>##3456781234567812345678
</code>```

We then move the pointer to the next character until we have iterated through the string.

Specs

You may use any character to replace "#", and the first string will not contain the hashtag (or the replaced hashtag).

The second string will always be longer than enough.

Both strings will only contain ASCII printable characters (U+0020-U+007F).

Testcases

```<code>input1: 123456781234567812345678
input2: 314159
output: ##3#####1##4####1###5###

input1: abcdefghijklmnopqrstuvwxyz
input2: dilemma
output: ###d####i##l##############
</code>```

Body:
Java, 136 bytes

void i(int[]a,int[]b){int i=0,j=0,n=a.length;for(;i<b.length;i++)for(;j<n;j++)if(a[j]==b[i]){j++;break;}else a[j]=0;for(;j<n;)a[j++]=0;}

Ungolfed

void i(int[] a, int[] b) {
    int i = 0, j = 0, n = a.length;
    for (; i < b.length; i++)
        for (; j < n; j++)
            if (a[j] == b[i]) {
                j++;
                break;
            } else a[j] = 0;
    for (; j < n; ) a[j++] = 0;
}

Notes

Uses the NUL character as replacement, any of the first 10 would do. If you wanted a visible replacement character, this would be one byte longer.

Input are two integer arrays of charcodes. int[] is one byte shorter than char[].

Outputs

Input 1:    123456781234567812345678
Input 2:    314159
Output:       3     1  4    1   5
Input 1:    abcdefghijklmnopqrstuvwxyz
Input 2:    dilemma
Output:        d    i  l
Input 1:    314asd159asdasd
Input 2:    314159
Output:     314   159


问:
How much snow did you get?
My apologies for the wordiness. We had fun with it at work in our internal golfing, but it required a few emails for clarification, so I hope I captured most of that the first time.

PROBLEM

Given a “simulated” snowfall snapshot (as a string, stdin or parameter to your function/method), report on 4 values: minimum depth, maximum depth, average depth, and duration.

Here’s a formatted example to illustrate the input:

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

The ‘*’ is a snowflake and the ‘-‘ is the ground. Imagine all of those “snowflakes” falling toward the ground. This is the final “snapshot”:

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

You need to report on:

Minimum depth - count the shortest “pile” (1, in example above)

Maximum depth - count the tallest “pile” (4, in example above)

Average depth - average count of all “piles” (1.9, in example above - rounding to tenths)

Duration - (each “fall” = 1 second) - time from the first snapshot to the last snapshot (3 seconds, in example above)

Another example for reference:

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

Final snapshot:

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

INPUT

The starting “snapshot” will have 8 “rows”, 8 “columns”, and be pipe-delimited (the pipes separate the rows). For example (excluding quotes):

```<code>“        |        |        |        |     *  |   *   *|      * |*       |--------”
</code>```

OUTPUT

The 4 values pipe-delimited on a single line: 0|1|.6|3 or 0|5|1|1

答:
Windows PowerShell, 180 <s>189</s>

```<code>$a=(0..7|%{$x=$_;-join(0..7|%{$s[$_*9+$x]})})
$b=$a-replace' '|%{$_.length}|sort
"{0}|{1}|{2:.0}|{3}"-f($b[-1..0]+(($b-join'+'|iex)/8),($a|%{($_-replace'^ +|\*').length}|sort)[-1])
</code>```

Input comes in as $s.

History:

2011-02-10 01:53 (189) – First attempt.

2011-02-10 02:03 (180) – Format string to the rescue. Only downside: It outputs numbers in regional format, no longer strictly conforming to the task specification. Still, that's a problem shared by the C# solution as well so I guess that's ok.

ContentLicense: CC BY-SA 2.5

Title: How much snow did you get?

Body:
Windows PowerShell, 180 <s>189</s>

$a=(0..7|%{$x=$_;-join(0..7|%{$s[$_*9+$x]})})
$b=$a-replace' '|%{$_.length}|sort
"{0}|{1}|{2:.0}|{3}"-f($b[-1..0]+(($b-join'+'|iex)/8),($a|%{($_-replace'^ +|\*').length}|sort)[-1])

Input comes in as $s.

History:

2011-02-10 01:53 (189) – First attempt.

2011-02-10 02:03 (180) – Format string to the rescue. Only downside: It outputs numbers in regional format, no longer strictly conforming to the task specification. Still, that's a problem shared by the C# solution as well so I guess that's ok.


问:
Traveling on a flat Earth
Coordinates in the flat-Earth world consist of latitude (x) and longitude (y), which are integers in the range 0...9999. Much like Gaussian integers, but they are always written using this notation:

```<code>411S 370E
</code>```

That is, with S or N appended to the latitude, and E or W appended to the longitude, with space(s) between the two components.

Goal

Write a program (not a function) that reads two coordinates, separated by whitespace, and outputs their sum. The first coordinate is a starting point, the second one is a displacement, and the output is the resulting position.

Input/Output

Since this challenge is partially about formatting, I'll try to define the input and output formats unambiguously.

The preferred input format has 1 space between the coordinate components, no leading zeros, and a newline character between the two coordinates. The program must be able to read the preferred format.

The output can contain any amount of whitespace and leading zeros. If it's different from the preferred input format, the program must be able to read this format too.

Just to make it clear, the input cannot (will not) contain any additional formatting characters. Just spaces and newlines where needed.

Scoring

This is an experiment on a new winning condition. I'll choose the winner by accepting an answer in a few weeks. If a better answer appears afterwards, I'll change the accepted answer.

The score for the program is its byte count. The winning program is one that is shorter than 400 bytes, has the fewest byte count, but is written in the most verbose programming language. To determine the winner:

Remove programs with byte count 400 or more (they can participate but cannot win)

Consider only the shortest program for each programming language

The longest program wins

Polyglots compete against programs in all languages in which they are valid (e.g. if a program is valid in both bash and sh, it competes against programs in both languages).

Test cases

In the test cases, the first two lines are the input, and the third line is the output.

```<code>0S 0E
0S 0W
0N 0E
</code>```

(the direction of zero doesn't matter, both in input and output)

```<code>0S 9999E
9999N 9999W
9999N 0E
</code>```

(maximal values)

```<code>42S 314W
42N 2718W
0N 3032W
</code>```

(the direction of zero doesn't matter in the output)

```<code>5555N 8888W
7777S 0E
2222S 8888W
</code>```

(no negative values; change the direction if you need to change the sign)

```<code>0001N        4545W
0999N        5454W
1000N        9999W
</code>```

(if the program outputs leading zeros and several spaces, it must be able to read them; it must also be able to read input that doesn't contain them)

```<code>8888N 8888W
9999N 9999W
</code>```

(invalid input - any behavior is acceptable, including crash and infinite loop)

答:
Java, 308 bytes

```<code>import java.util.*;class x{public static void main(String[]a){Scanner r=new Scanner(System.in);int[]v=new int[2];int l,x,g,i;for(i=5;i-->1;System.out.println(i<3?""+x*g+"ENWS".charAt(i-g):"")){String s=r.next();x=Integer.parseInt(s.substring(0,l=s.length()-1));x=v[i%2]+=x*=s.charAt(l)>80?-1:1;g=x<0?-1:1;}}}
</code>```

A more readable version:

```<code>import java.util.*;
class x
{
    public static void main(String[]args)
    {
        Scanner r = new Scanner(System.in);
        int[] v = new int[2];
        for (int i = 5; i-->1; )
        {
            String s = r.next();
            int l = s.length() - 1;
            int x = Integer.parseInt(s.substring(0, l));
            x = v[i%2] += x *= s.charAt(l) > 'N' ? -1 : 1;
            int g = x < 0 ? -1 : 1;
            System.out.println(i < 3?"" + x * g + "ENWS".charAt(i-g):"");
        }
    }
}
</code>```

Golfing in Java is a special kind of fun. The following two lines of code do the same, but the first one is shorter:

```<code>(x<0?-x:x)
Math.abs(x)
</code>```

The code reads 4 tokens from standard input. For each token, the part up to the last character is converted to int, and the last character optionally flips its sign.

Then it adds the value that was read 2 iterations ago. Java initializes arrays to 0, so at the first two iterations this will do the right thing.

Then it will format the values and print them. However, in the first two iterations, it prints the empty string instead (so two extra linebreaks appear in the output).

It uses some funky arithmetic so the iteration variable (4,3,2 or 1) and the sign (-1 or 1) can be combined to a zero-based index into the string "ENWS".

Title: Traveling on a flat Earth

Body:
Java, 308 bytes

import java.util.*;class x{public static void main(String[]a){Scanner r=new Scanner(System.in);int[]v=new int[2];int l,x,g,i;for(i=5;i-->1;System.out.println(i<3?""+x*g+"ENWS".charAt(i-g):"")){String s=r.next();x=Integer.parseInt(s.substring(0,l=s.length()-1));x=v[i%2]+=x*=s.charAt(l)>80?-1:1;g=x<0?-1:1;}}}

A more readable version:

import java.util.*;
class x
{
    public static void main(String[]args)
    {
        Scanner r = new Scanner(System.in);
        int[] v = new int[2];
        for (int i = 5; i-->1; )
        {
            String s = r.next();
            int l = s.length() - 1;
            int x = Integer.parseInt(s.substring(0, l));
            x = v[i%2] += x *= s.charAt(l) > 'N' ? -1 : 1;
            int g = x < 0 ? -1 : 1;
            System.out.println(i < 3?"" + x * g + "ENWS".charAt(i-g):"");
        }
    }
}

Golfing in Java is a special kind of fun. The following two lines of code do the same, but the first one is shorter:

(x<0?-x:x)
Math.abs(x)

The code reads 4 tokens from standard input. For each token, the part up to the last character is converted to int, and the last character optionally flips its sign.

Then it adds the value that was read 2 iterations ago. Java initializes arrays to 0, so at the first two iterations this will do the right thing.

Then it will format the values and print them. However, in the first two iterations, it prints the empty string instead (so two extra linebreaks appear in the output).

It uses some funky arithmetic so the iteration variable (4,3,2 or 1) and the sign (-1 or 1) can be combined to a zero-based index into the string "ENWS".


答:
Reng v.3.3, 33 bytes

```<code>ii+i-:²1#x1ø
:x²eq!vx1+#x
 ~n%2+<
</code>```

Takes input like a c b. Try it here!

The calculation is simple. i gets input, so ii+ is a + c, and i- is then (a + c) - b. Very simple stuff.

The hard part is taking the max with 0. "What!? How could it be that hard?" Well, I didn't implement inequality in Reng. So we'll have to use math!

Observation 1: max(a,b) = (a+b+|a-b|)/2

Observation 2: max(a,0) = (a+|a|)/2

Observation 3: |a| = Sqrt[a^2]

Observation 4: Reng doesn't have square roots, either. Nor does it have power. But knowing that we'll only be taking the square roots of perfect squares, we can use trial and error, starting at 1. That is, our algorithm can look like this:

```<code>x = 1 to a, iterate:
  if x * x == a break, return X
</code>```

Since we always have k being a perfect square, this algorithm always terminates.

So, into the rest of the code explanation!

```<code>ii+i-:²1#x1ø
:x²eq!vx1+#x
 ~n%2+<
</code>```

part 1: initialization

I've already explained how ii+i- works, so let's look at the rest of the line.

```<code>     :²1#x1ø
</code>```

: duplicates this number. The bottom number will be a in (a + |a|)/2. Now, we need to take the absolute value of the top value. We can do this using observations 3 and 4. ² squares the top value, and 1#x initializes our counter x with 1. Then we go to the next line with 1ø

part 2: square root loop

```<code>:x²eq!vx1+#x
</code>```

: duplicates our maximum value a from the top of the stack (for the equality check). x² squares our counter x and e pushes a Boolean representing the equality of x² and a. If they are equal, q! breaks out of the loop by going down (v), leaving |a| on the stack. Otherwise, we increment x (x1+) and set x to that value (#x).

finalization

```<code> ~n%2+<
</code>```

< redirects the program to look left. shhh it saves bytes. It's equivalent to this series of steps:

```<code>+2%n~
</code>```

+ adds the top two of the stack, thus implementing the first part of (a + |a|)/2. 2% divides that sum by two (% is division here because / is a mirror). Lastly, we output this as a number (n) and terminates the program (~).

Body:
Reng v.3.3, 33 bytes

ii+i-:²1#x1ø
:x²eq!vx1+#x
 ~n%2+<

Takes input like a c b. Try it here!

The calculation is simple. i gets input, so ii+ is a + c, and i- is then (a + c) - b. Very simple stuff.

The hard part is taking the max with 0. "What!? How could it be that hard?" Well, I didn't implement inequality in Reng. So we'll have to use math!

Observation 1: max(a,b) = (a+b+|a-b|)/2

Observation 2: max(a,0) = (a+|a|)/2

Observation 3: |a| = Sqrt[a^2]

Observation 4: Reng doesn't have square roots, either. Nor does it have power. But knowing that we'll only be taking the square roots of perfect squares, we can use trial and error, starting at 1. That is, our algorithm can look like this:

x = 1 to a, iterate:
  if x * x == a break, return X

Since we always have k being a perfect square, this algorithm always terminates.

So, into the rest of the code explanation!

ii+i-:²1#x1ø
:x²eq!vx1+#x
 ~n%2+<

part 1: initialization

I've already explained how ii+i- works, so let's look at the rest of the line.

     :²1#x1ø

: duplicates this number. The bottom number will be a in (a + |a|)/2. Now, we need to take the absolute value of the top value. We can do this using observations 3 and 4. ² squares the top value, and 1#x initializes our counter x with 1. Then we go to the next line with 1ø

part 2: square root loop

:x²eq!vx1+#x

: duplicates our maximum value a from the top of the stack (for the equality check). x² squares our counter x and e pushes a Boolean representing the equality of x² and a. If they are equal, q! breaks out of the loop by going down (v), leaving |a| on the stack. Otherwise, we increment x (x1+) and set x to that value (#x).

finalization

 ~n%2+<

< redirects the program to look left. shhh it saves bytes. It's equivalent to this series of steps:

+2%n~

+ adds the top two of the stack, thus implementing the first part of (a + |a|)/2. 2% divides that sum by two (% is division here because / is a mirror). Lastly, we output this as a number (n) and terminates the program (~).


答:
PowerShell v2+, 72 bytes

```<code>param($a,$b)$i=0;-join([char[]]$a|%{if($_-ceq$b[$i]){$_;$i++}else{'#'}})
</code>```

Takes input $a and $b, sets $i to 0 (our pointer). Then, we cast $a as a char-array and pump it through a loop |%{...}. Each iteration, we check if the current character is case-sensitive-equal to the character in $b under the pointer. If it is, add it to the pipeline with $_ and increment our counter. Otherwise, add a '#' to the pipeline. All of those characters are then gathered up (...) and -joined into one string, which is then re-placed onto the pipeline. Output is implicit.

Example

```<code>PS C:\Tools\Scripts\golfing> .\filter-this-string.ps1 "Programming Puzzles & Code Golf" "PPCG"
P###########P#########C####G###
</code>```

Title: Filter this string!

Body:
PowerShell v2+, 72 bytes

param($a,$b)$i=0;-join([char[]]$a|%{if($_-ceq$b[$i]){$_;$i++}else{'#'}})

Takes input $a and $b, sets $i to 0 (our pointer). Then, we cast $a as a char-array and pump it through a loop |%{...}. Each iteration, we check if the current character is case-sensitive-equal to the character in $b under the pointer. If it is, add it to the pipeline with $_ and increment our counter. Otherwise, add a '#' to the pipeline. All of those characters are then gathered up (...) and -joined into one string, which is then re-placed onto the pipeline. Output is implicit.

Example

PS C:\Tools\Scripts\golfing> .\filter-this-string.ps1 "Programming Puzzles & Code Golf" "PPCG"
P###########P#########C####G###


答:
JavaScript (ES6), 22 bytes

```<code>(a,b,c)=>a+c>b?a+c-b:0
</code>```

Math.max is too long and there isn't a long enough common subexpression to deduplicate, so that's basically it. If a falsy value had been acceptable, then 21 bytes: (a,b,c)=>a+c>b&&a+c-b.

Body:
JavaScript (ES6), 22 bytes

(a,b,c)=>a+c>b?a+c-b:0

Math.max is too long and there isn't a long enough common subexpression to deduplicate, so that's basically it. If a falsy value had been acceptable, then 21 bytes: (a,b,c)=>a+c>b&&a+c-b.


答:
><>, 7 bytes

```<code>-+:0)*n
</code>```

Input assumed to be on the stack, in the order a, c, b.

It does c-b+a, and compares that with zero. Then it outputs either 0 or the answer before it terminates.

Try it online!

Body:
><>, 7 bytes

-+:0)*n

Input assumed to be on the stack, in the order a, c, b.

It does c-b+a, and compares that with zero. Then it outputs either 0 or the answer before it terminates.

Try it online!


答:
C#6, 112 bytes

string c(string h,string n)=>h==""?"":h[0]==n[0]?h[0]+c(h.Substring(1),n.Substring(1)):"#"+c(h.Substring(1),n);
```

Recursive function, takes haystack h (input1) and needles n (input2).

If Haystack is empty, return it.

if first characters of haystack and needle are equal, keep the first character and call recursively while skipping the first char on both parameters

else return the replacement character (fixed to # here) followed by a recursive call again skipping the first character from haystack only.

Major factor for the length is the long name of Substring, but it's not long enough (compared to the number of usages) that a wrapping function would help to reduce further.

Title: Filter this string!

Body:
C#6, 112 bytes

string c(string h,string n)=>h==""?"":h[0]==n[0]?h[0]+c(h.Substring(1),n.Substring(1)):"#"+c(h.Substring(1),n);

Recursive function, takes haystack h (input1) and needles n (input2).

If Haystack is empty, return it.

if first characters of haystack and needle are equal, keep the first character and call recursively while skipping the first char on both parameters

else return the replacement character (fixed to # here) followed by a recursive call again skipping the first character from haystack only.

Major factor for the length is the long name of Substring, but it's not long enough (compared to the number of usages) that a wrapping function would help to reduce further.


答:
Cubix, 12 <s>9</s> bytes

This turned out longer than I wanted and then I messed up the spec. I might be able to knock out a byte or 2.

```<code>@w+?II-.\0O@
</code>```

Wraps onto a cube with side length 2

```<code>    @ w
    + ?
I I - . \ 0 O @
. . . . . . . .
    . .
    . .
</code>```

Gets II integer input twice, -. subtract followed by noop, \ redirect down (in this case around), hits the second I input again, + adds, ? conditional that turns left on negative, right on positive and straight through for zero.
Turning left (invalid negative) w change lane to the right onto the literal 0 heading right through the O@ output and terminate.

Straight through (invalid zero) hits \ reflector and head right onto the literal 0 and the O@ output terminate.

Turning right (valid positive) travels around the cube, hitting the O output on the bottom face, onto the w change lane right, that switches the lane to the @ terminate.

Try it here

Body:
Cubix, 12 <s>9</s> bytes

This turned out longer than I wanted and then I messed up the spec. I might be able to knock out a byte or 2.

@w+?II-.\0O@

Wraps onto a cube with side length 2

    @ w
    + ?
I I - . \ 0 O @
. . . . . . . .
    . .
    . .

Gets II integer input twice, -. subtract followed by noop, \ redirect down (in this case around), hits the second I input again, + adds, ? conditional that turns left on negative, right on positive and straight through for zero.
Turning left (invalid negative) w change lane to the right onto the literal 0 heading right through the O@ output and terminate.

Straight through (invalid zero) hits \ reflector and head right onto the literal 0 and the O@ output terminate.

Turning right (valid positive) travels around the cube, hitting the O output on the bottom face, onto the w change lane right, that switches the lane to the @ terminate.

Try it here


答:
MATL, 6 bytes

```<code>-+OvX>
</code>```

My very first MATL answer! It can probably be shorter, I'd love tips! Input is backwards, e.g.:

```<code>c
b
a
</code>```

Try it online!.

Explanation:

```<code>-        #Subtract the top two numbers (c and b)
 +       #Add the top two numbers (c-b and a)
  O      #Push a 0
   v     #Concatenate this into a array
    X>   #Print the smallest value of the array
</code>```

Body:
MATL, 6 bytes

-+OvX>

My very first MATL answer! It can probably be shorter, I'd love tips! Input is backwards, e.g.:

c
b
a

Try it online!.

Explanation:

-        #Subtract the top two numbers (c and b)
 +       #Add the top two numbers (c-b and a)
  O      #Push a 0
   v     #Concatenate this into a array
    X>   #Print the smallest value of the array


问:
Building a Bridge
Your task is to build a bridge to connect two cliffs given an input d, the distance apart. d will always be even

However, the bridge needs columns to hold it up. Each column can hold a max of 6 spaces on each side.

For this example:

```<code>________                        ________
        |                      |
   A    |                      |   B

        |----------------------|
                d = 22
</code>```

The bridge for d = 20should look like this with two columns. Columns do not count in d.

```<code>_____|__________|_____
12345|1234554321|12345
     |          |
</code>```

Rules:

Must have enough columns to stand up.

Must have minimum number of columns needed to stand up.

Must be symmetrical

Lowest amount of Bytes Wins

Examples: (#s are only to help you count spaces. Should not be included in your output)

d = 10

```<code>_____|_____
12345|12345
     |
</code>```

d = 32

```<code>_____|___________|___________|_____
12345|12345654321|           |
     |           |           |
</code>```

d = 8

```<code>____|____
1234|1234
    |
</code>```

d = 4

```<code>__|__
12|34
  |
</code>```

d = 22

```<code>_____|____________|_____
12345|123456654321|
     |            |
</code>```

or

```<code>______|__________|______
123456|1234554321|123456
      |          |
</code>```

Title: Building a Bridge

Body:
JavaScript (ES6), 92 bytes

d=>[..."_  "].map(c=>(s=c+c[r='repeat'](n%6))+'|'+(c[r](12)+'|')[r](n/6)+s,n=d-1>>1).join`\n`

Where \n represents the literal newline character. If d can be odd, it takes me 128 bytes:

d=>[..."_  "].map(c=>[...Array(d+1)].map((_,i)=>(d&1?i&&d-i&&(i>m)+5+i-m:((d-1)%24>11)*6+i-m)%12?'':'|',m=d>>1).join(c)).join`\n`


问:
KOTH: Everybody loves tokens
In this game two players compete to eat the most points worth of tokens, but there's a twist! Eating multiple tokens in a row of the same color gives an ever-growing bonus, but watch out, or your opponent will thwart your plans by eating the tokens you want before you can!

Rules:

1 versus 1

n by n board (random size between 5x5 and 15x15)

You and your opponent will spawn in the same random cell

Throughout the board will be randomly generated numbers in some cells ranging in value from 1-3

2 * (the width of the board) tokens will be generated, but there can be overrides, so there may be fewer by chance.

Each number will be one of 3 colors: Red, Green, or Blue, in hex RGB format

Each round, player 1 moves and the board is updated, then player 2 moves, and the board is updated. So each player can effectively tell what move the previous player made based on the change in the board state. This continues until the game ends, as described later.

You have 6 possible actions for a turn: UP, RIGHT, DOWN, LEFT, EAT, and PASS

The 4 move commands are self-explanatory, and you CAN pass your turn. If you return a nonsensical move, we will assume you meant pass. If you try to move off the edge of the board, you will not move. The edges don't wrap.

EAT consumes the number you are currently in the same space as

You gain as many points as the number you consume

If you eat 2 numbers in a row of the same color, you get +1

If you eat 3 numbers in a row of the same color, you get +2

If you eat m numbers in a row of the same color, you get +(m-1)

These bonuses are added cumulatively, so getting m numbers in a row leads to m*(m-1)/2 in total bonus by the time you eat a different color.

Game end conditions:

All numbers are consumed

4 * (the width of the board) turns have gone by with no effective eating (just saying “EAT” with no token where you are doesn't count) occurring by either player (any token is reachable in 2 * (the width) moves, so this bound will only be surpassed if both players have no single target token in mind)

Your AI should take less than a second to make a move, else PASS will be assumed as your choice.

The tournament will be round robin with a large number of rounds, say 100 or 1000. A random board is generated, and each ordered pair of different players is run on that board. After the tournament completes we will rank people by their total score. So even if you are player 2 for a game, your goal is still to get as many points as possible.

AI Submission: The language my controller supports is Javascript. Multiple submissions are allowed. Everyone submits a constructor for an object like this:

```<code>function (player1) {
    this.yourMove = function (b) {
        return "MOVE";
    }
}
</code>```

The input player1 is a boolean saying whether you are player 1 or not.
Your constructor must have the yourMove function, but it can have
any number of additional functions or values as well. Don't define any
global variables, just put them as variables on your object. A new version
of your object will be created at the beginning of each match, and
yourMove will be called on it, with the current board as input, on each of your turns, and should return a valid move.

b, the input to yourMove, is a copy of the current board, here are the
constructors, with input examples, though you can't call them yourself:

```<code>function token(color, points) {
    this.color = color; //"#FF0000"
    this.points = points; //5
}

function player(pos, score, colorBonus, lastColor) {
    this.pos = pos; //[5, 5]
    this.score = score; //9
    this.colorBonus = colorBonus; //i.e. 2 if you just ate 3 blue tokens in a row
                                  //0 if you just ate two different colors.
    this.lastColor = lastColor; //"#00FF00", is "#000000" at start
}

function board(player1, player2, tokens) {
    this.player1 = player1; //new player([5, 5], 9, 2, "#00FF00")
    this.player2 = player2; //new player([5, 5], 9, 2, "#00FF00")
    this.tokens = tokens; //[[new token("#0000FF", 5), false],
                      // [new token("#0000FF", 5), false]]
}
</code>```

The token array has "false" for any empty squares, and tokens[a][b] is
the token at x = a, y = b, numbered starting from the upper-left corner.

Controller:
Here's a link to the controller in GitHub. It's an html file that you can run to see how the game and the round-robin works, and it comes with two AIs, a random one that moves in a random direction each turn but eats tokens at its position, and a naive algorithm that goes for the nearest token that gives the most points. I will add in each AI as it is submitted.

Below is a snippet that allows you to run the controller on the default AI.
Current AIs:

KindaRandomAI

NaiveAI

MirrorBot

HungryBot

<!DOCTYPE html>

  <canvas id="myCanvas" width="700" height="600" style="border:1px solid #c3c3c3;">
    Your browser does not support the HTML5 canvas tag.
  </canvas>

```

答:
OneTarget

Finds the token that will give the most points in the least time and will go for that one. Ranks same color tokens a little higher because of the cumulative effect.

```<code>function (player1) {
    this.yourMove = function (b) {
        var me = player1? b.player1: b.player2;
        var him= player1? b.player2: b.player1;
        var x = me.pos[0];
        var y = me.pos[1];
        var maxVal = -1;
        var maxX = 0;
        var maxY = 0;
        for(var i = 0;i < b.tokens.length;i++){
            for(var j = 0;j < b.tokens.length;j++){
                if(b.tokens[i][j]){
                    var dist = Math.abs(x-i) + Math.abs(y-j);
                    var val = this.valueOf(b.tokens[i][j]);
                    val /= (dist + 1);
                    if(val > maxVal){
                        maxVal = val;
                        maxX = i;
                        maxY = j;
                    }
                }
            }
        }
        if(maxY < y)
            return "UP";
        if(maxX < x)
            return "LEFT";
        if(maxY > y)
            return "DOWN";
        if(maxX > x)
            return "RIGHT";
        return "EAT";
    }
    this.valueOf = function(t){
        //how many points would it give you?
        return t.points + (this.lastColor == t.color? 2 * this.colorBonus + 1 : 0);
    }
}
</code>```

Title: KOTH: Everybody loves tokens

Body:
OneTarget

Finds the token that will give the most points in the least time and will go for that one. Ranks same color tokens a little higher because of the cumulative effect.

function (player1) {
    this.yourMove = function (b) {
        var me = player1? b.player1: b.player2;
        var him= player1? b.player2: b.player1;
        var x = me.pos[0];
        var y = me.pos[1];
        var maxVal = -1;
        var maxX = 0;
        var maxY = 0;
        for(var i = 0;i < b.tokens.length;i++){
            for(var j = 0;j < b.tokens.length;j++){
                if(b.tokens[i][j]){
                    var dist = Math.abs(x-i) + Math.abs(y-j);
                    var val = this.valueOf(b.tokens[i][j]);
                    val /= (dist + 1);
                    if(val > maxVal){
                        maxVal = val;
                        maxX = i;
                        maxY = j;
                    }
                }
            }
        }
        if(maxY < y)
            return "UP";
        if(maxX < x)
            return "LEFT";
        if(maxY > y)
            return "DOWN";
        if(maxX > x)
            return "RIGHT";
        return "EAT";
    }
    this.valueOf = function(t){
        //how many points would it give you?
        return t.points + (this.lastColor == t.color? 2 * this.colorBonus + 1 : 0);
    }
}


答:
Pyke, 6 bytes

```<code>-+0]Se
</code>```

Explanation:

```<code>+-     - do the mathsy bit (a+c)-b
  0]  - create a list with [0, ^]
 Se - Get the maximum value
</code>```

Try it here!

Body:
Pyke, 6 bytes

-+0]Se

Explanation:

+-     - do the mathsy bit (a+c)-b
  0]  - create a list with [0, ^]
 Se - Get the maximum value

Try it here!


答:
SQL (PostGreSQL 9.4), 305 bytes

```<code>PREPARE p(char,char)AS
SELECT string_agg(abs(n)||substr('SNNEEW',i+sign(n)::int,1),' ')FROM(SELECT i,sum(to_number(v,'9999')*CASE right(v,1)WHEN'N'THEN 1 WHEN'E'THEN 1 ELSE -1 END)n
FROM(SELECT CASE WHEN v~'[NS]' THEN 2 ELSE 5 END i,v
FROM regexp_split_to_table($1||' '||$2,' ')v)i
GROUP BY i ORDER BY i)g
</code>```

Implemented as a prepared statement that takes 2 character parameters.  One parameter for each input line.

It is called as follows

```<code>execute p('0S 9999E','9999N 9999W');
</code>```

and outputs a row containing a single character column for the result.  9999N 0E

Title: Traveling on a flat Earth

Body:
Coordinates in the flat-Earth world consist of latitude (x) and longitude (y), which are integers in the range 0...9999. Much like Gaussian integers, but they are always written using this notation:

```<code>411S 370E
</code>```

That is, with S or N appended to the latitude, and E or W appended to the longitude, with space(s) between the two components.

Goal

Write a program (not a function) that reads two coordinates, separated by whitespace, and outputs their sum. The first coordinate is a starting point, the second one is a displacement, and the output is the resulting position.

Input/Output

Since this challenge is partially about formatting, I'll try to define the input and output formats unambiguously.

The preferred input format has 1 space between the coordinate components, no leading zeros, and a newline character between the two coordinates. The program must be able to read the preferred format.

The output can contain any amount of whitespace and leading zeros. If it's different from the preferred input format, the program must be able to read this format too.

Just to make it clear, the input cannot (will not) contain any additional formatting characters. Just spaces and newlines where needed.

Scoring

This is an experiment on a new winning condition. I'll choose the winner by accepting an answer in a few weeks. If a better answer appears afterwards, I'll change the accepted answer.

The score for the program is its byte count. The winning program is one that is shorter than 400 bytes, has the fewest byte count, but is written in the most verbose programming language. To determine the winner:

Remove programs with byte count 400 or more (they can participate but cannot win)

Consider only the shortest program for each programming language

The longest program wins

Polyglots compete against programs in all languages in which they are valid (e.g. if a program is valid in both bash and sh, it competes against programs in both languages).

Test cases

In the test cases, the first two lines are the input, and the third line is the output.

```<code>0S 0E
0S 0W
0N 0E
</code>```

(the direction of zero doesn't matter, both in input and output)

```<code>0S 9999E
9999N 9999W
9999N 0E
</code>```

(maximal values)

```<code>42S 314W
42N 2718W
0N 3032W
</code>```

(the direction of zero doesn't matter in the output)

```<code>5555N 8888W
7777S 0E
2222S 8888W
</code>```

(no negative values; change the direction if you need to change the sign)

```<code>0001N        4545W
0999N        5454W
1000N        9999W
</code>```

(if the program outputs leading zeros and several spaces, it must be able to read them; it must also be able to read input that doesn't contain them)

```<code>8888N 8888W
9999N 9999W
</code>```

(invalid input - any behavior is acceptable, including crash and infinite loop)

Body:
SQL (PostGreSQL 9.4), 305 bytes

PREPARE p(char,char)AS
SELECT string_agg(abs(n)||substr('SNNEEW',i+sign(n)::int,1),' ')FROM(SELECT i,sum(to_number(v,'9999')*CASE right(v,1)WHEN'N'THEN 1 WHEN'E'THEN 1 ELSE -1 END)n
FROM(SELECT CASE WHEN v~'[NS]' THEN 2 ELSE 5 END i,v
FROM regexp_split_to_table($1||' '||$2,' ')v)i
GROUP BY i ORDER BY i)g

Implemented as a prepared statement that takes 2 character parameters.  One parameter for each input line.

It is called as follows

execute p('0S 9999E','9999N 9999W');

and outputs a row containing a single character column for the result.  9999N 0E


问:
Tips for golfing in vim
I've recently realized how vim works great for golfing, especially for kolmogorov-complexity. Also, according to meta vim is a perfectly acceptable 'programming language' at least, for the scope of this site, that is.

What general tips do you have for golfing in Vim? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Vim (e.g. "remove comments" is not an answer).

Please post one tip per answer.

答:
Let's say you're in insert mode, and you want to make a single normal mode command. You might write that like this:

```<code>isome_text<esc><foobar>gisome_more_text
</code>```

Don't do it that way. Instead, use <C-o>, which executes a single normal command then immediately returns to insert mode.

```<code>isome_text<C-o><foobar>some_more_text
</code>```

Title: Tips for golfing in vim

Body:
Let's say you're in insert mode, and you want to make a single normal mode command. You might write that like this:

isome_text<esc><foobar>gisome_more_text

Don't do it that way. Instead, use <C-o>, which executes a single normal command then immediately returns to insert mode.

isome_text<C-o><foobar>some_more_text


问:
KOTH: Every coin has two sides
Final results available

Introduction

After my previous KOTH with heavy themes (fantasy war, worldwide pandemic...), I'm back with a new lighthearted game. This time, you are facing off in a "board game-like" situation. A pile of upside down coins is placed at the center of a really big table, and you are determined to get your share of the loot!

Glossary

Coins: Tokens that can either be flipped or unflipped.

  Unflipped: Coins placed on the table with their value pointing down. This is the default state of the coins.

  Flipped: Coins placed on the table with their value pointing up.

  Local: Refers to your pile of coins.

  Global: Refers to the pile of coins at the center.

Principle

At the start of the game, each player starts with 0 points and 0 coins (flipped or unflipped). The game is turn-based. During their turn, players can take up to 3 actions interacting either with the pile of coins at the center of the table, their own pile of coins or with other players.

Play order is defined randomly at the start of the game. The order of the players in the argument list represents the turn order, and it goes from left to right in that list. "Next" and "Previous" refer respectively to "on the right in that list" and "on the left in that list" with a loop if you're the last of either side.

The game lasts for 50 rounds or until there are 0 coins at the center at the end of a player turn (meaning that you will finish your 3 actions even if the pile is empty after your first action, and you can put back coins to let the game continue). The starting number of global coins is defined randomly with this formula:

```<code>(2 ^ nb_players) + (nb_players * 10) - random(1 + (nb_players ^ 2))`
</code>```

Each action will get you points (or make you lose some) and at the end of the game, each coin you have will be added to your points (-1 for unflipped, +2 for flipped). The player with the highest score wins.

The controller provides you with input via command arguments, and your program has to output via stdout.

Syntax

Input

Each time your program is called, it will receive arguments in this format:

Round;YourPlayerId;Coins;PlayerId_Points_Flipped_Unflipped;PlayerId_Points_Flipped_Unflipped;...

Rounds are 1-indexed.

Example input

6;2;52;1_20_3_12;0_-2_0_1;2_12_1_0

Here, you see it is the 6th round and you are player 2. There are 52 coins in the central pile. You have 12 points, 1 flipped coin and 0 unflipped coin. Points can be negative.

Output

You have to output three characters (no space, no separator), which each correspond to one action you'll take this turn. The order of the characters determine the order of the actions. You can output the same actions multiple times. In case there is not enough coins to complete your action, it will use the maximum of available coins and count points only for the coins used.

N: Do Nothing

1: Take 1 coin from the central pile [Effects: +1 local unflipped / -1 point / -1 global unflipped]

2: Take 2 coins from the central pile [Effects: +2 local unflipped / -2 points / -2 global unflipped]

3: Take 3 coins from the central pile [Effects: +3 local unflipped / -3 points / -3 global unflipped]

A: Put back 1 coin from your pile [Effects: -1 local unflipped / +1 point / +1 global unflipped]

B: Put back 2 coins from your pile [Effects: -2 local unflipped / +2 points / +2 global unflipped]

C: Put back 3 coins from your pile [Effects: -3 local unflipped / +3 points / +3 global unflipped]

X: Remove 1 coin from your pile [Effects: -1 local unflipped / 0 point]

Y: Remove 2 coins from your pile [Effects: -2 local unflipped / 0 point]

Z: Remove 3 coins from your pile [Effects: -3 local unflipped / 0 point]

R: Rotate coins to previous player [Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]

T: Rotate coins to next player [Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]

F: Flip 1 coin [Effects: -1 local unflipped / +1 local flipped / +2 point]

U: Unflip 1 coin [Effects: +1 local unflipped / -1 local flipped / -2 point]

Example output

2FF : Takes two coins and flips two coin, scoring -2 + 2 + 2 = 2 points

If your output is incorrect, controller will assume NNN.

Controller

You can find the controller on GitHub. It also contains two samplebots, written in Java.
To make it run, check out the project and open it in your Java IDE. The entry point in the main method of the class Game. Java 8 required.

To add bots, first you need either the compiled version for Java (.class files) or the sources for interpreted languages. Place them in the root folder of the project. Then, create a new Java class in the players package (you can take example on the already existing bots). This class must implement Player to override the method String getCmd(). The String returned is the shell command to run your bots. You can for example make a Ruby bot work with this command : return "C:\Ruby\bin\ruby.exe MyBot.rb";. Finally, add the bot in the players array at the top of the Game class.

Rules

Bots should not be written to beat or support specific other bots.

Writing to files is allowed. Please write to"yoursubmissionname.txt", the folder will be emptied before a game starts. Other external resources are disallowed.

Your submission has 1 second to respond.

Provide commands to compile and run your submissions.

Supported Languages

I'll try and support every language, but it needs to be available online for free. Please provide instructions for installation if you're not using a "mainstream" language.

As of right now, I can run : Java 6-7-8, PHP, Ruby, Perl, Python 2-3, Lua, R, node.js, Haskell, Kotlin, C++ 11.

Final results

These are the results of 100 games (points are added up) :

```<code>1. BirdInTheHand: 1017790
2. Balance: 851428
3. SecondBest: 802316
4. Crook: 739080
5. Jim: 723440
6. Flipper: 613290
7. Wheeler: 585516
8. Oracle: 574916
9. SimpleBot: 543665
10. TraderBot: 538160
11. EgoisticalBot: 529567
12. RememberMe: 497513
13. PassiveBot: 494441
14. TheJanitor: 474069
15. GreedyRotation: 447057
16. Devil: 79212
17. Saboteur: 62240
</code>```

Individual results of the games are available here : http://pasted.co/63f1e924 (with starting coins and number of rounds per game).

A bounty of 50 reputations is awarded to the winner : Bird In The Hand by Martin Büttner.

Thank you all for your participation, see you next KOTH~

答:
SecondBest, Python 3

This program will go through all possible 3 move combinations and choose the second-best one.

Because if you have the perfect move, it's probably a trap.

Edit: removed commented-out input

```<code>import sys
from copy import deepcopy
from random import randint
In=str(sys.argv[1])
def V(n,f=10,t=14):
 n=str(n);z=0;s='';d='0123456789';d1='N123ABCXYZRTFU'
 for i in n:z=z*f+d.index(i)
 while z:z,m=divmod(z,t);s=d1[m]+s
 while len(s)<3:s='N'+s
 return s
In=In.split(';')
number=In[0:3]
players=In[3:]
for x in range(0,len(players)):players[x]=players[x].split('_')
for x in players:
 if number[1] in x[0]:self=x
for x in range(0,len(players)):
 for y in range(0,len(players[x])):
  players[x][y]=int(players[x][y])
for x in range(0,len(number)):number[x]=int(number[x])
Pos=list(map(V,range(0,14**3)))
B=[]
C=[]
P1=deepcopy(players)
N1=deepcopy(number)
for x in range(len(Pos)):
    P=True
    y=Pos[x]
    if '1A'in y or '2B'in y or '3C'in y or 'FU'in y or 'A1'in y or 'B2'in y or 'C3'in y or 'UF'in y:
            P=False#stupid check
    if P:#legality check
        z=0
        players=deepcopy(P1)
        number=deepcopy(N1)
        for x in players:
            if str(number[1]) in str(x[0]):self=x
        for w in range(0,3):
            if y[w] in '3':
                if int(number[2])<3:P=False;break
                else:z-=3;self[3]+=3;number[2]-=3
            if y[w] in '2':
                if int(number[2])<2:P=False;break
                else:z-=2;self[3]+=2;number[2]-=2
            if y[w] in '1':
                if int(number[2])<1:P=False;break
                else:z-=1;self[3]+=1;number[2]-=1
            if y[w] in 'A':
                if int(self[3])<1:P=False;break
                else:z+=1;self[3]-=3;number[2]+=3
            if y[w] in 'B':
                if int(self[3])<2:P=False;break
                else:z+=2;self[3]-=2;number[2]+=2
            if y[w] in 'C':
                if int(self[3])<3:P=False;break
                else:z+=3;self[3]-=1;number[2]+=1
            if y[w] in 'X':
                if int(self[3])<1:P=False;break
                else:self[3]-=1
            if y[w] in 'Y':
                if int(self[3])<2:P=False;break
                else:self[3]-=2
            if y[w] in 'Z':
                if int(self[3])<3:P=False;break
                else:self[3]-=3
            if y[w] in 'F':
                if int(self[3])<1:P=False;break
                else:z+=2;self[3]-=1;self[2]+=1
            if y[w] in 'U':
                if int(self[3])<1:P=False;break
                else:z-=2;self[3]+=1;self[2]-=1
            if y[w] in 'R':
                self[2:4]=players[(players.index(self)+1)%len(players)][2:4]
                z+=int(self[3])*-1
                z+=int(self[2])*2
            if y[w] in 'T':
                self[2:4]=players[(players.index(self)-1)%len(players)][2:4]
                z+=int(self[3])*-1
                z+=int(self[2])*2
    if P:
        C.append(z);B.append((z,y))
c=list(set(C))
c.sort()
c=c[::-1][1];D=[]
for x in B:
    if c in x:D.append(x)
print(D[randint(0,len(D)-1)][1])
</code>```

Edit: The code was printing a random legal move. It should now be returning the second best result.

Title: KOTH: Every coin has two sides

Body:
SecondBest, Python 3

This program will go through all possible 3 move combinations and choose the second-best one.

Because if you have the perfect move, it's probably a trap.

Edit: removed commented-out input

import sys
from copy import deepcopy
from random import randint
In=str(sys.argv[1])
def V(n,f=10,t=14):
 n=str(n);z=0;s='';d='0123456789';d1='N123ABCXYZRTFU'
 for i in n:z=z*f+d.index(i)
 while z:z,m=divmod(z,t);s=d1[m]+s
 while len(s)<3:s='N'+s
 return s
In=In.split(';')
number=In[0:3]
players=In[3:]
for x in range(0,len(players)):players[x]=players[x].split('_')
for x in players:
 if number[1] in x[0]:self=x
for x in range(0,len(players)):
 for y in range(0,len(players[x])):
  players[x][y]=int(players[x][y])
for x in range(0,len(number)):number[x]=int(number[x])
Pos=list(map(V,range(0,14**3)))
B=[]
C=[]
P1=deepcopy(players)
N1=deepcopy(number)
for x in range(len(Pos)):
    P=True
    y=Pos[x]
    if '1A'in y or '2B'in y or '3C'in y or 'FU'in y or 'A1'in y or 'B2'in y or 'C3'in y or 'UF'in y:
            P=False#stupid check
    if P:#legality check
        z=0
        players=deepcopy(P1)
        number=deepcopy(N1)
        for x in players:
            if str(number[1]) in str(x[0]):self=x
        for w in range(0,3):
            if y[w] in '3':
                if int(number[2])<3:P=False;break
                else:z-=3;self[3]+=3;number[2]-=3
            if y[w] in '2':
                if int(number[2])<2:P=False;break
                else:z-=2;self[3]+=2;number[2]-=2
            if y[w] in '1':
                if int(number[2])<1:P=False;break
                else:z-=1;self[3]+=1;number[2]-=1
            if y[w] in 'A':
                if int(self[3])<1:P=False;break
                else:z+=1;self[3]-=3;number[2]+=3
            if y[w] in 'B':
                if int(self[3])<2:P=False;break
                else:z+=2;self[3]-=2;number[2]+=2
            if y[w] in 'C':
                if int(self[3])<3:P=False;break
                else:z+=3;self[3]-=1;number[2]+=1
            if y[w] in 'X':
                if int(self[3])<1:P=False;break
                else:self[3]-=1
            if y[w] in 'Y':
                if int(self[3])<2:P=False;break
                else:self[3]-=2
            if y[w] in 'Z':
                if int(self[3])<3:P=False;break
                else:self[3]-=3
            if y[w] in 'F':
                if int(self[3])<1:P=False;break
                else:z+=2;self[3]-=1;self[2]+=1
            if y[w] in 'U':
                if int(self[3])<1:P=False;break
                else:z-=2;self[3]+=1;self[2]-=1
            if y[w] in 'R':
                self[2:4]=players[(players.index(self)+1)%len(players)][2:4]
                z+=int(self[3])*-1
                z+=int(self[2])*2
            if y[w] in 'T':
                self[2:4]=players[(players.index(self)-1)%len(players)][2:4]
                z+=int(self[3])*-1
                z+=int(self[2])*2
    if P:
        C.append(z);B.append((z,y))
c=list(set(C))
c.sort()
c=c[::-1][1];D=[]
for x in B:
    if c in x:D.append(x)
print(D[randint(0,len(D)-1)][1])

Edit: The code was printing a random legal move. It should now be returning the second best result.


问:
Counting in bijective base 62
The task is to generate all the strings from 'a' to '999' including upper case characters like so:

```<code>'a', 'b', 'c' ... 'y', 'z', 'A', 'B', 'C' ... 'Y', 'Z', '0', '1', 2' ...
'8', '9', 'aa', 'ab', 'ac' ... 'az', 'aA', 'aB' ... 'aZ', 'a0' ... 'a9', 'ba'
</code>```

and so on (filling in the gaps), optionally starting with the empty string.

Input:

The amount of consecutive characters the program has to print up to.

Output:

An array containing each string OR one string per line

Clarifications:

The order doesn't matter, you can print uppercase or lowercase letters first if you want.

The output can return any type of enumerable, doesn't have to be an array specifically, although I doubt printing all the combinations won't be the easiest way to go.

An input of 3 would print all the string from 'a' (or '') to '999'‚ an input of 5 up to '99999' and so on.

答:
Bash + GNU utilities, 90

printf -vs %$1s
eval printf '%s\\n' ${s// /{=,{a..z\},{A..Z\},{0..9\}\}}|sed s/^=*//\;/=/d
```

Input as a command-line parameter.  Output is a whitespace-separated list.

Works for inputs upt and including 3.  Run out of memory with 4 - the eval printf takes an the entire set of 63n elements of the bash expansion.

Title: Counting in bijective base 62

Body:
Bash + GNU utilities, 90

printf -vs %$1s
eval printf '%s\\n' ${s// /{=,{a..z\},{A..Z\},{0..9\}\}}|sed s/^=*//\;/=/d

Input as a command-line parameter.  Output is a whitespace-separated list.

Works for inputs upt and including 3.  Run out of memory with 4 - the eval printf takes an the entire set of 63n elements of the bash expansion.


答:
Python, 115 Bytes

n,f=input()
for a in str(f):
 x,r=0,""
 for b in str(n):
  if x==0and b==a:c,x="#",1
  else:c=b
  r+=c
 n=r
print n
```

Title: Filter this string!

Body:
Your task is to write a program that will filter out some characters in a string, so that the remaining spells out (part of) the other string.

Let's say we received the string "123456781234567812345678", and the second string is "314159".

First, we put a pointer on the second string:

```<code>314159
^
</code>```

So the pointer is now on 3, and we replace the not-3 characters with a hashtag until the first 3:

```<code>##3456781234567812345678
</code>```

We then move the pointer to the next character until we have iterated through the string.

Specs

You may use any character to replace "#", and the first string will not contain the hashtag (or the replaced hashtag).

The second string will always be longer than enough.

Both strings will only contain ASCII printable characters (U+0020-U+007F).

Testcases

```<code>input1: 123456781234567812345678
input2: 314159
output: ##3#####1##4####1###5###

input1: abcdefghijklmnopqrstuvwxyz
input2: dilemma
output: ###d####i##l##############
</code>```


答:
Javascript ES6, 46 bytes

a=>b=>a.replace(/./g,x=>x==b[i]?(i++,x):0,i=0)
```

Uses 0 as the replacement char.

Title: Filter this string!

Body:
Javascript ES6, 46 bytes

a=>b=>a.replace(/./g,x=>x==b[i]?(i++,x):0,i=0)

Uses 0 as the replacement char.


问:
Between the Lines

While doodling around on square-ruled paper the other day, I came up with the above negative-space font for digits. In case you haven't spotted it yet, the spaces between the above shapes yield the golden ratio 1.618033988749. In this challenge, your task is to take a number as input and render it exactly as the example above shows.

Here is how these are created: all lines will be on a regular grid, so that the individual digits are made up of a small number of grid cells. Here are the shapes of the 10 digits (we'll ignore the decimal point for this challenge):

Yes, the 7 differs from the golden ratio example at the top. I kinda messed that up. We'll be going with this one.

Notice that each digit is five cells tall, and three cells wide. To render a number, you can imagine placing all its digits next to each other, such that there is exactly one empty column between each pair of digits. For example, taking 319 as input, we'd write:

Notice that we add one leading and trailing empty column. Now we invert the cells:

The output should then be the boundaries of the resulting polygons:

Of course you may generate the result in any other way, as long as the rendered output looks the same.

Input

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument, as a string, or list of digits. (You can't take a number as that wouldn't allow you to support leading zeros.)

You may assume that there will be no more than 16 digits in the input.

Output

Output may either be displayed on screen or written to a file in a common image format.

You may use both raster and vector graphics.

In either case, the aspect ratio of the cells of the underlying grid needs to be 1 (that is, the cells should be squares).

In the case of raster graphics, each cell should cover at least 20 by 20 pixels.

The lines must be no wider than 10% of the cell size. I'm willing to give one or two pixels leeway due to aliasing here.

Lines and background can be any two clearly distinguishable colours, but the shapes created by the lines must not be filled (that is the insides should be the background colour as well).

There must be no gaps within each closed loop.

Of course, the entire result must be visible.

Test Cases

Here are 10 inputs, which together cover all possible pairs of adjacent digits, as well as every possible leading and trailing digit:

```<code>07299361548
19887620534
21456837709
39284106657
49085527316
59178604432
69471338025
79581224630
89674235011
97518264003
</code>```

And here are the expected results for those:

Make sure that your code also works when given a single digit (I don't want to include the expected results here, because they should be obvious, and the test case section is bloated enough as it is).

答:
Mathematica 328 bytes

```<code>j@d_:=Partition[IntegerDigits[FromDigits[d/.Thread[ToString/@Range[0,9]->StringPartition["75557262277174771717557117471774757711117575775717",5]],16],2, 20]/.{0->1,1->0},4];j@"*"=Array[{1}&,5];
w@s_:=  ColorNegate@EdgeDetect@Rasterize@ArrayPlot[Thread[Join@@Transpose/@j/@Characters@(s<>"*")],Frame->False,ImageSize->Large]
</code>```

```<code>w["07299361548"]
w["19887620534"]
</code>```

Explanation

Four bits will be used in each of 5 lines of cells for each input digit.

"75557262277174771717557117471774757711117575775717"represents 0 to 9 as bitmaps.

The first 5 digits in the large integer above, namely 75557 indicate how each array row for zero should be displayed.  7 will represent {0,1,1,1}, that is, a white cell, followed, on its right, by 3 black cells; the leading 0 is a blank space to separate displayed digits.  5 corresponds to {0,1,0,1}, that is  white, black, white, black cells.

The following produces a list of replacement rules:

```<code>Thread[ToString /@ Range[0, 9] -> StringPartition["75557262277174771717557117471774757711117575775717", 5]]
</code>```

{"0" -> "75557", "1" -> "26227", "2" -> "71747", "3" -> "71717",
   "4" -> "55711", "5" -> "74717", "6" -> "74757", "7" -> "71111",
   "8" -> "75757", "9" -> "75717"}

Note that when 3 is input, it will be replaced by 71717
This representation is expressed in binary:

```<code>p = Partition[IntegerDigits[FromDigits["3" /. {"3" -> "71717"}, 16], 2, 20], 4]
</code>```

{{0, 1, 1, 1}, {0, 0, 0, 1}, {0, 1, 1, 1}, {0, 0, 0, 1}, {0, 1, 1, 1}}

Its black-white inverse is found by simply exchanging the 1s and 0s.

```<code>q = p /. {0 -> 1, 1 -> 0}
</code>```

{{1, 0, 0, 0}, {1, 1, 1, 0}, {1, 0, 0, 0}, {1, 1, 1, 0}, {1, 0, 0, 0}}

Let's see what p and q look like when displayed by ArrayPlot:

```<code>ArrayPlot[#, Mesh -> True, ImageSize -> Small, PlotLegends -> Automatic] & /@ {p, q}
</code>```

This simply joins the arrays of zeros and ones for each digit before rendering the big array via ArrayPlot.  * is defined in j as the final vertical space after the last digit.

```<code>Thread[Join @@ Transpose /@ j /@ Characters@(s <> "*")]
</code>```

Title: Between the Lines

Body:
Mathematica 328 bytes

j@d_:=Partition[IntegerDigits[FromDigits[d/.Thread[ToString/@Range[0,9]->StringPartition["75557262277174771717557117471774757711117575775717",5]],16],2, 20]/.{0->1,1->0},4];j@"*"=Array[{1}&,5];
w@s_:=  ColorNegate@EdgeDetect@Rasterize@ArrayPlot[Thread[Join@@Transpose/@j/@Characters@(s<>"*")],Frame->False,ImageSize->Large]

w["07299361548"]
w["19887620534"]

Explanation

Four bits will be used in each of 5 lines of cells for each input digit.

"75557262277174771717557117471774757711117575775717"represents 0 to 9 as bitmaps.

The first 5 digits in the large integer above, namely 75557 indicate how each array row for zero should be displayed.  7 will represent {0,1,1,1}, that is, a white cell, followed, on its right, by 3 black cells; the leading 0 is a blank space to separate displayed digits.  5 corresponds to {0,1,0,1}, that is  white, black, white, black cells.

The following produces a list of replacement rules:

Thread[ToString /@ Range[0, 9] -> StringPartition["75557262277174771717557117471774757711117575775717", 5]]

{"0" -> "75557", "1" -> "26227", "2" -> "71747", "3" -> "71717",
   "4" -> "55711", "5" -> "74717", "6" -> "74757", "7" -> "71111",
   "8" -> "75757", "9" -> "75717"}

Note that when 3 is input, it will be replaced by 71717
This representation is expressed in binary:

p = Partition[IntegerDigits[FromDigits["3" /. {"3" -> "71717"}, 16], 2, 20], 4]

{{0, 1, 1, 1}, {0, 0, 0, 1}, {0, 1, 1, 1}, {0, 0, 0, 1}, {0, 1, 1, 1}}

Its black-white inverse is found by simply exchanging the 1s and 0s.

q = p /. {0 -> 1, 1 -> 0}

{{1, 0, 0, 0}, {1, 1, 1, 0}, {1, 0, 0, 0}, {1, 1, 1, 0}, {1, 0, 0, 0}}

Let's see what p and q look like when displayed by ArrayPlot:

ArrayPlot[#, Mesh -> True, ImageSize -> Small, PlotLegends -> Automatic] & /@ {p, q}

This simply joins the arrays of zeros and ones for each digit before rendering the big array via ArrayPlot.  * is defined in j as the final vertical space after the last digit.

Thread[Join @@ Transpose /@ j /@ Characters@(s <> "*")]


答:
, 21 chars / 27 bytes

```<code>ⒶïⓜᵖɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)ė)
</code>```

Try it here (Firefox only).

Nope. Nope. Nope.

Explanation

```<code>ⒶïⓜᵖɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)ė) // implicit:
Ⓐïⓜ                    // [...Array(input)].map(($,_)=>...)
    ᵖ                   // push to stack:
     ɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)   // list of n-digit numbers in [a-zA-Z0-9]-ary
                     ė) // formatted into a matrix (no spaces)
                        // implicit stack output, newline-separated
</code>```

Title: Counting in bijective base 62

Body:
The task is to generate all the strings from 'a' to '999' including upper case characters like so:

```<code>'a', 'b', 'c' ... 'y', 'z', 'A', 'B', 'C' ... 'Y', 'Z', '0', '1', 2' ...
'8', '9', 'aa', 'ab', 'ac' ... 'az', 'aA', 'aB' ... 'aZ', 'a0' ... 'a9', 'ba'
</code>```

and so on (filling in the gaps), optionally starting with the empty string.

Input:

The amount of consecutive characters the program has to print up to.

Output:

An array containing each string OR one string per line

Clarifications:

The order doesn't matter, you can print uppercase or lowercase letters first if you want.

The output can return any type of enumerable, doesn't have to be an array specifically, although I doubt printing all the combinations won't be the easiest way to go.

An input of 3 would print all the string from 'a' (or '') to '999'‚ an input of 5 up to '99999' and so on.

Body:
, 21 chars / 27 bytes

ⒶïⓜᵖɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)ė)

Try it here (Firefox only).

Nope. Nope. Nope.

Explanation

ⒶïⓜᵖɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)ė) // implicit:
Ⓐïⓜ                    // [...Array(input)].map(($,_)=>...)
    ᵖ                   // push to stack:
     ɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)   // list of n-digit numbers in [a-zA-Z0-9]-ary
                     ė) // formatted into a matrix (no spaces)
                        // implicit stack output, newline-separated


答:
Mathematica, 13 bytes

```<code>Max[##2-#,0]&
</code>```

Anonymous function. Takes input in the order b, a, c. The ##2-# is just some crazy Sequencecraft that computes #2+#3-#. The Max[..,0] just takes the maximum of the result and 0.

Body:
(Taken from https://en.wikipedia.org/wiki/File:Tangential_quadrilateral.svg)

A tangential quadrilateral (see example above) is a quadrilateral in which a circle can be inscribed.

Your task is to find the possible value of d given a, b, and c.

Specs

a, b, c will all be positive integers.

If no possible value of d exists, output 0.

Scoring

This is code-golf. Shortest solution in bytes wins.

Testcases

```<code>a b c d
3 4 4 3
1 2 3 2
1 5 3 0
</code>```

Body:
Mathematica, 13 bytes

Max[##2-#,0]&

Anonymous function. Takes input in the order b, a, c. The ##2-# is just some crazy Sequencecraft that computes #2+#3-#. The Max[..,0] just takes the maximum of the result and 0.


答:
MATLAB / Octave, 20 bytes

```<code>@(a,b,c)max(c-b+a,0)
</code>```

Anonymous function that accepts the three inputs and returns the length of the fourth side. Can be called using ans(a,b,c).

Demo with all test cases

Body:
MATLAB / Octave, 20 bytes

@(a,b,c)max(c-b+a,0)

Anonymous function that accepts the three inputs and returns the length of the fourth side. Can be called using ans(a,b,c).

Demo with all test cases


答:
Python 3, <s>388</s> <s>398</s> <s>373</s> 371 bytes

Assumes 256 memory cells. Just a straightforward implementation, easily beatable, probably can be golfed more. Try it on repl.it.

Thanks to @EasterlyIrk for having me realize that Python 3 is much shorter that Python 2.

EDIT: Realized I only accounted for over/underflow while printing, not in actual value.

Thanks to @KevinLau-notKenney for saving 25 (!) bytes with list multiplication and inversion operator tricks

EDIT: -3 bytes by putting 256 into a variable, -4 messing with operators, +8 making sure it is lowercase

```<code>def p(s):
 b=256
 l,m=[w[-1]for w in s.lower().split()],[0]*b
 i=p=x=0
 while x<len(l):
  c=l[x]
  if'm'>c:
   if 1>i:m[p]=-~m[p]%b
   if 1==i:m[p]=~-m[p]%b
   if 2==i:p=-~p%b
   if 3==i:p=~-p%b
   if 4==i:m[p]=ord(input()[0])
   if 4<i:print(chr(m[p]),end="")
  if'r'==c:i=-~i%6
  if't'==c and m[p]<1:x+=l[:x].index('y')
  if'x'<c and m[p]>0:x-=l[x::-1].index('t')
  x+=1
</code>```

Title: Interpret DOGO!

Body:
Interpret DOGO

DOGO is a lesser known programming language. While the original DOGO (a joke language from a Usenet post) has never been implemented, a language resembling it has been created. The commands for the language are:

```<code>+===========+================================================================+
|  Command  |                          Description                           |
+===========+================================================================+
| SIT       | If the value of the current memory cell is 0, jump to STAY.    |
+-----------+----------------------------------------------------------------+
| STAY      | If the value of the current memory cell is not 0, jump to SIT. |
+-----------+----------------------------------------------------------------+
| ROLL-OVER | Select the next operation from the operation list.             |
+-----------+----------------------------------------------------------------+
| HEEL      | Execute the currently selected operation.                      |
+-----------+----------------------------------------------------------------+
</code>```

The operations are:

```<code>+========+=======================================================+====+
| Number |                      Description                      | BF |
+========+=======================================================+====+
|      0 | Increment current memory cell.                        | +  |
+--------+-------------------------------------------------------+----+
|      1 | Decrement current memory cell.                        | -  |
+--------+-------------------------------------------------------+----+
|      2 | Move to next memory cell.                             | >  |
+--------+-------------------------------------------------------+----+
|      3 | Move to previous memory cell.                         | <  |
+--------+-------------------------------------------------------+----+
|      4 | Input a byte and store it in the current memory cell. | ,  |
+--------+-------------------------------------------------------+----+
|      5 | Output the current memory cell as ASCII.              | .  |
+--------+-------------------------------------------------------+----+
</code>```

Examples

Hello World:

```<code>roll-over roll-over heel roll-over roll-over roll-over roll-over heel heel heel
heel heel heel heel heel heel sit roll-over roll-over roll-over heel roll-over
roll-over roll-over heel heel heel heel heel heel heel heel roll-over roll-over
heel roll-over roll-over roll-over roll-over roll-over heel roll-over roll-over
roll-over roll-over roll-over stay roll-over roll-over roll-over heel roll-over
roll-over heel roll-over roll-over roll-over heel roll-over roll-over roll-over
roll-over heel heel heel heel heel heel heel sit roll-over roll-over roll-over
heel roll-over roll-over roll-over heel heel heel heel roll-over roll-over heel
roll-over roll-over roll-over roll-over roll-over heel roll-over roll-over
roll-over roll-over roll-over stay roll-over roll-over roll-over heel roll-over
roll-over roll-over heel roll-over roll-over roll-over roll-over roll-over heel
roll-over heel heel heel heel heel heel heel roll-over roll-over roll-over
roll-over roll-over heel heel roll-over heel heel heel roll-over roll-over
roll-over roll-over roll-over heel roll-over roll-over roll-over heel heel heel
roll-over roll-over roll-over roll-over heel heel heel heel heel heel heel heel
sit roll-over roll-over roll-over heel roll-over roll-over roll-over heel heel
heel heel roll-over roll-over heel roll-over roll-over roll-over roll-over
roll-over heel roll-over roll-over roll-over roll-over roll-over stay roll-over
roll-over roll-over heel roll-over roll-over heel roll-over roll-over roll-over
heel heel heel roll-over roll-over roll-over roll-over heel heel heel heel heel
heel heel heel heel heel sit roll-over roll-over roll-over heel roll-over
roll-over roll-over heel heel heel heel heel heel heel heel heel roll-over
roll-over heel roll-over roll-over roll-over roll-over roll-over heel roll-over
roll-over roll-over roll-over roll-over stay roll-over roll-over roll-over heel
roll-over roll-over roll-over roll-over heel heel heel roll-over roll-over
roll-over roll-over heel roll-over roll-over roll-over roll-over heel heel heel
heel roll-over roll-over heel roll-over heel heel heel roll-over roll-over
roll-over roll-over roll-over heel roll-over roll-over heel heel heel heel heel
heel roll-over roll-over roll-over roll-over heel roll-over roll-over heel heel
heel heel heel heel heel heel roll-over roll-over roll-over roll-over heel
roll-over roll-over roll-over heel heel roll-over roll-over roll-over roll-over
heel roll-over roll-over roll-over roll-over roll-over heel
</code>```

99 bottles of beer

Rules

Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.

If it is possible, please provide a link to an online site where your code can be tested.

Your program cannot write anything to STDERR (or something similar).

You can take input from STDIN (or the closest alternative in your language), or as an argument.

Standard loopholes are forbidden.

Scoring

Programs are scored according to bytes. The default character set is UTF-8, if you are using a different one, please specify.

That aside, this is code-golf, and the lowest byte count will be deemed the winner!

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

var QUESTION_ID = 79350; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://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 "https://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,]*[^\s,]),.*?(\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,
      });

  });

  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;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) 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: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

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

```

Update:

Sorry for not clarifying the sit and stay commands very well. They are, as @user6245072 said, like [ and ] in BF.

Update 2:

To clarify @KennyLau's questions:

The default operation is 0.

Memory consists of 8-bit cells.

Cells wrap on overflow/underflow.

Input is required for operation 4.

Body:
Python 3, <s>388</s> <s>398</s> <s>373</s> 371 bytes

Assumes 256 memory cells. Just a straightforward implementation, easily beatable, probably can be golfed more. Try it on repl.it.

Thanks to @EasterlyIrk for having me realize that Python 3 is much shorter that Python 2.

EDIT: Realized I only accounted for over/underflow while printing, not in actual value.

Thanks to @KevinLau-notKenney for saving 25 (!) bytes with list multiplication and inversion operator tricks

EDIT: -3 bytes by putting 256 into a variable, -4 messing with operators, +8 making sure it is lowercase

def p(s):
 b=256
 l,m=[w[-1]for w in s.lower().split()],[0]*b
 i=p=x=0
 while x<len(l):
  c=l[x]
  if'm'>c:
   if 1>i:m[p]=-~m[p]%b
   if 1==i:m[p]=~-m[p]%b
   if 2==i:p=-~p%b
   if 3==i:p=~-p%b
   if 4==i:m[p]=ord(input()[0])
   if 4<i:print(chr(m[p]),end="")
  if'r'==c:i=-~i%6
  if't'==c and m[p]<1:x+=l[:x].index('y')
  if'x'<c and m[p]>0:x-=l[x::-1].index('t')
  x+=1