问:
Electrons bouncing in a wire
Imagine a "wire" that has n spaces. Imagine further that there are "electrons" in that wire. These electrons only live for one unit of time. Any spaces in the wire that are adjacent to exactly one electron become an electron. In Game of Life terminology, this is B1/S.

For example, this is a wire of length 10, with period 62.

Rules

Input, n, is a single, positive integer.

Output must be a single integer denoting the period of a wire of length n.

The starting state is a single electron at one end of the wire.

The period does not necessarily include the starting state. Some lengths never return to the starting state, but all of them are periodic.

A static wire (i.e., one without electrons) has period 1.

Boundary conditions are not periodic. That is, the wire is not toroidal in any way.

Test cases

Special thanks to orlp for producing this list. (I have verified it up to n=27.)

```<code>1 1
2 2
3 1
4 6
5 4
6 14
7 1
8 14
9 12
10 62
11 8
12 126
13 28
14 30
15 1
16 30
17 28
18 1022
19 24
20 126
21 124
22 4094
23 16
24 2046
25 252
26 1022
27 56
28 32766
29 60
30 62
31 1
32 62
33 60
34 8190
35 56
36 174762
37 2044
38 8190
39 48
40 2046
41 252
42 254
43 248
44 8190
45 8188
</code>```

You can see test cases for n=2 through 21 here with my Game-of-Life-esque simulator: Variations of Life.

EDIT: the sequence here has been published as A268754!

答:
Pyth, 29 bytes

```<code>J^2QL%x/b2*b2JK.uyN1;-lKxKyeK
</code>```

Try it online!

Test suite

Uses the algorithm a(n+1) = ((a(n) << 1)^(a(n) >> 1)) % (2 ** N).

Title: Electrons bouncing in a wire

Body:
Pyth, 29 bytes

J^2QL%x/b2*b2JK.uyN1;-lKxKyeK

Try it online!

Test suite

Uses the algorithm a(n+1) = ((a(n) << 1)^(a(n) >> 1)) % (2 ** N).


答:
Ruby, 72 bytes

Anonymous function.

```<code>->n{s=[w=1];c=p
(j=s.index w=w*2%2**n^w/2
j ?c=s.size-j:s<<w)while !c
c}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Electrons bouncing in a wire

Body:
Imagine a "wire" that has n spaces. Imagine further that there are "electrons" in that wire. These electrons only live for one unit of time. Any spaces in the wire that are adjacent to exactly one electron become an electron. In Game of Life terminology, this is B1/S.

For example, this is a wire of length 10, with period 62.

Rules

Input, n, is a single, positive integer.

Output must be a single integer denoting the period of a wire of length n.

The starting state is a single electron at one end of the wire.

The period does not necessarily include the starting state. Some lengths never return to the starting state, but all of them are periodic.

A static wire (i.e., one without electrons) has period 1.

Boundary conditions are not periodic. That is, the wire is not toroidal in any way.

Test cases

Special thanks to orlp for producing this list. (I have verified it up to n=27.)

```<code>1 1
2 2
3 1
4 6
5 4
6 14
7 1
8 14
9 12
10 62
11 8
12 126
13 28
14 30
15 1
16 30
17 28
18 1022
19 24
20 126
21 124
22 4094
23 16
24 2046
25 252
26 1022
27 56
28 32766
29 60
30 62
31 1
32 62
33 60
34 8190
35 56
36 174762
37 2044
38 8190
39 48
40 2046
41 252
42 254
43 248
44 8190
45 8188
</code>```

You can see test cases for n=2 through 21 here with my Game-of-Life-esque simulator: Variations of Life.

EDIT: the sequence here has been published as A268754!

Body:
Ruby, 72 bytes

Anonymous function.

->n{s=[w=1];c=p
(j=s.index w=w*2%2**n^w/2
j ?c=s.size-j:s<<w)while !c
c}


问:
Average an image
Here is an image:

```<code>%%%%%%%%%%%%%
% Hello,    %
%    world! %
%%%%%%%%%%%%%
</code>```

But it is too confusing for our undersized brains to compute. So we average it like this:

Split it into 2 x 2 sections. If the picture ends before a section is complete, imagine that there are spaces there.

Average the values of the ASCII characters in each section.

Round this average and convert it to an ASCII character.

Finally, replace all characters in the section to the average character.

Repeat this for all sections.

So the average of the image above looks like this:

```<code>$$>>II99######
$$>>II99######
$$##88KKGG####
$$##88KKGG####
</code>```

Your task: Write  a program that takes an ASCII image as input and outputs its average.

Note Integers are rounded by function floor(x+0.5) or similar function - in other words, round halves upwards.

答:
MATL, <s>32</s> 30 bytes

```<code>2thZCO32XEoYmYocGZy2/Xke2t3$Y"
</code>```

Input is a 2D char array, with rows separated by ;.

Try it online!

Explanation

```<code>2th     % push array [2 2]
ZC      % take input implicitly. Arrange distinct 2x2 blocks as columns, padding with 0
O32XE   % replace 0 by 32 (space)
oYm     % convert to number. Take mean of each column
Yoc     % round. Convert to char
GZy     % size of input in the 2 dimensions
2/Xk    % divide each dimension by 2, and round up to account for the padding
e       % reshape into image with half original size in each dimension
2t3$Y"  % replicate by a factor of 2 in each dimension. Display implicitly
</code>```

Title: Average an image

Body:
MATL, <s>32</s> 30 bytes

2thZCO32XEoYmYocGZy2/Xke2t3$Y"

Input is a 2D char array, with rows separated by ;.

Try it online!

Explanation

2th     % push array [2 2]
ZC      % take input implicitly. Arrange distinct 2x2 blocks as columns, padding with 0
O32XE   % replace 0 by 32 (space)
oYm     % convert to number. Take mean of each column
Yoc     % round. Convert to char
GZy     % size of input in the 2 dimensions
2/Xk    % divide each dimension by 2, and round up to account for the padding
e       % reshape into image with half original size in each dimension
2t3$Y"  % replicate by a factor of 2 in each dimension. Display implicitly


答:
Pyth, 58 bytes

```<code>J2A,lQlhQV:0GJ
Ksm*C+csmsm?&<kG<bHC@@Qkb32hBdhBN4 .5J:0HJK
</code>```

Try it online!

Title: Average an image

Body:
Here is an image:

```<code>%%%%%%%%%%%%%
% Hello,    %
%    world! %
%%%%%%%%%%%%%
</code>```

But it is too confusing for our undersized brains to compute. So we average it like this:

Split it into 2 x 2 sections. If the picture ends before a section is complete, imagine that there are spaces there.

Average the values of the ASCII characters in each section.

Round this average and convert it to an ASCII character.

Finally, replace all characters in the section to the average character.

Repeat this for all sections.

So the average of the image above looks like this:

```<code>$$>>II99######
$$>>II99######
$$##88KKGG####
$$##88KKGG####
</code>```

Your task: Write  a program that takes an ASCII image as input and outputs its average.

Note Integers are rounded by function floor(x+0.5) or similar function - in other words, round halves upwards.

Body:
Pyth, 58 bytes

J2A,lQlhQV:0GJ
Ksm*C+csmsm?&<kG<bHC@@Qkb32hBdhBN4 .5J:0HJK

Try it online!


Title: Average an image

Body:
JavaScript (ES6), 159 bytes

document.write("<pre>"+(

// --- Solution ---
s=>s.replace(/./g,(c,i)=>(a=String.fromCharCode([t=0,1,l=s.search`
`+1,l+1].map(o=>t+=(n=s.charCodeAt(p=i+o-i%l%2-(i/l|0)%2*l))>32?n:32)|t/4+.5))+(++p%l?"":a))
// ----------------

)(`%%%%%%%%%%%%%
% Hello,    %
%    world! %
%%%%%%%%%%%%%`))

Takes a multiline string as input.


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

Sample

Using Ferulas flourish in gorgeous gardens. as input:

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

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

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

Challenge

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

Program or function allowed.

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

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

Another samples:

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

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

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

答:
Javascript ES6, <s>108</s> 107 chars

107 chars, result string is trimmed

```<code>r=s=>s.split``.reverse().join``
f=s=>r(r(s).replace(/\b\w*(\w)\b(?=.*\1\b)/gi,'')).replace(/\W+/g,' ').trim()
</code>```

Test:

```<code>["Take all first words for each letter... this is a test",
"Look ^_^ .... There are 3 little dogs :)",
"...maybe some day 1 plus 2 plus 20 could result in 3"
].map(f) + '' == [
"Take all first words each letter is",
"Look _ There are 3 dogs",
"maybe some day 1 plus 2 could result in 3"
]
</code>```

Body:
Javascript ES6, <s>108</s> 107 chars

107 chars, result string is trimmed

r=s=>s.split``.reverse().join``
f=s=>r(r(s).replace(/\b\w*(\w)\b(?=.*\1\b)/gi,'')).replace(/\W+/g,' ').trim()

Test:

["Take all first words for each letter... this is a test",
"Look ^_^ .... There are 3 little dogs :)",
"...maybe some day 1 plus 2 plus 20 could result in 3"
].map(f) + '' == [
"Take all first words each letter is",
"Look _ There are 3 dogs",
"maybe some day 1 plus 2 could result in 3"
]


问:
Greatest Common Divisor
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

答:
ARM machine code, 12 bytes:

assembly:

```<code>gcd: cmp r0, r1
     sublt r0, r0, r1
     bne gcd
</code>```

Currently can't compile this, but each instruction in ARM takes 4 bytes. Probably it could be golfed down using THUMB-2 mode.

Title: Greatest Common Divisor

Body:
ARM machine code, 12 bytes:

assembly:

gcd: cmp r0, r1
     sublt r0, r0, r1
     bne gcd

Currently can't compile this, but each instruction in ARM takes 4 bytes. Probably it could be golfed down using THUMB-2 mode.


答:
C++, 211 bytes

Golfed

#include <bitset>
#include <cstdio>
#define B std::bitset<1<<10>
B m,t(1),h(2);int main() {int p,l;for(scanf("%d",&p);p--;m.set(p));
for(p=l=1;t!=h;h=(h>>1^h<<1)&m,l++)p==l?t=h,p*=2,l=0:0;return !printf("%d",l);}
```
<p>With added whitespace for readability</p>
<pre class="lang-cpp prettyprint-override"><code>#include <bitset>
#include <cstdio>
#define B std::bitset<1<<10>
B m,t(1),h(2);
int main() {
    int p,l;
    for(scanf("%d",&p);p--;m.set(p));
    for(p=l=1;t!=h;h=(h>>1^h<<1)&m,l++)p==l?t=h,p*=2,l=0:0;
    return !printf("%d",l);
}
</code>```

Good practice for C++'s bitset; and a great education learning about Brent's cycle detection algorithm (as used by @orlp)

Title: Electrons bouncing in a wire

Body:
C++, 211 bytes

Golfed

#include <bitset>
#include <cstdio>
#define B std::bitset<1<<10>
B m,t(1),h(2);int main() {int p,l;for(scanf("%d",&p);p--;m.set(p));
for(p=l=1;t!=h;h=(h>>1^h<<1)&m,l++)p==l?t=h,p*=2,l=0:0;return !printf("%d",l);}

With added whitespace for readability

#include <bitset>
#include <cstdio>
#define B std::bitset<1<<10>
B m,t(1),h(2);
int main() {
    int p,l;
    for(scanf("%d",&p);p--;m.set(p));
    for(p=l=1;t!=h;h=(h>>1^h<<1)&m,l++)p==l?t=h,p*=2,l=0:0;
    return !printf("%d",l);
}

Good practice for C++'s bitset; and a great education learning about Brent's cycle detection algorithm (as used by @orlp)


答:
><>, 32 bytes

```<code>::{::}@(?\=?v{:}-
.!09}}${{/;n/>
</code>```

Accepts two values from the stack and apply the euclidian algorithm to produce their GCD.

You can try it here!

For a much better answer in ><>, check out Sok's !

Title: Greatest Common Divisor

Body:
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

Body:
><>, 32 bytes

::{::}@(?\=?v{:}-
.!09}}${{/;n/>

Accepts two values from the stack and apply the euclidian algorithm to produce their GCD.

You can try it here!

For a much better answer in ><>, check out Sok's !


问:
Evolution of OEIS
In this challenge, the goal is to recreate the On-Line Encyclopedia of Integer Sequences one sequence at a time.  Similar to the Evolution of Hello World, each answer depends on a previous answer.

Over time, this challenge will create a "family tree" of the OEIS sequences.  It is simple to add on to this tree.

Find a previous answer, which can be at any depth N of the tree.

Determine the first N numbers generated by that answer's sequence.

Find a sequence in OEIS which starts with those same numbers and which hasn't been used before.

Write a program to generate this new sequence you just found.

Submit your answer as depth N+1

Since the level of your answer influences scoring, you should always add your answer onto the tree at the deepest level possible.  If you cannot fit your answer anywhere on the tree, you can start a new branch of the tree and put your answer as depth 1.

Answer Requirements

There are a few ways to output a sequence.

The first option is to write a program or function that inputs a number (from STDIN or as an argument) and returns the Nth number in your chosen sequence.  You can assume that the sequence will be defined for N and that N and S_N are "reasonably sized" (so it won't cause overflows).  You can also use any reasonable indexing, such as 0 indexing, 1 indexing, or the indexing listed under "offset" on the sequence's OEIS page, that doesn't matter.  The term produced by the first index must match the first term of the OEIS entry.

The second option is to write a program or function that inputs a number and returns the first N terms of the sequence.  The first terms of the output must be the first terms of the OEIS entry (you can't leave off the first few terms).  Consecutive terms must be delimited by arbitrary strings of non-digit characters, so 0,1  1.2/3,5;8,11 works but 011235811 does not count.

The third option is to create a program that outputs a continuous stream of numbers.  Similarly to the second option, there must be delimiters between consecutive terms.

Your answer should contain a header like this to aid Stack Snippet parsing:

```<code> # [language], [number] bytes, depth [number], A[new sequence] from A[old sequence]
</code>```

Your answer should contain the code to generate the sequence, along with the first few terms that any descendants will need to contain.  These few terms should be preceded by the exact word terms: so that the controller can use them as part of the tree diagram.  It is also recommended to write a description of the sequence you chose.

If your post is a depth 1 answer and thus has no ancestor, you should simply omit the from A[number] in your header.

Here is an example answer:

```<code># Perl, 26 bytes, depth 3, A026305 from A084912

    various code here
    and here

The next answer should match the following terms:

    1, 4, 20

This sequence is .... and does ....
</code>```

Chaining Requirements

In order to make this challenge more fair, there are restrictions on which answers you can chain yours to. These rules are mostly to prevent a single person from creating a whole branch of the tree by themselves or owning a lot of "root" nodes.

You cannot chain to yourself.

You cannot directly chain two of your answers to the same ancestor.

You cannot make more than one "Level 1" answer.

Also, if the ancestor was of depth N, your post must have depth N+1, even if more than the required number of terms agree.

Scoring

Your score as a user is the sum of the scores of all of your answers.  The score of a single answer is determined by the following formula:

```<code>Answer Score = Sqrt(Depth) * 1024 / (Length + 256)
</code>```

This scoring system should encourage users to submit a large number of deeper answers.  Shorter answers are preferred over longer answers, but depth has a much larger influence.

Below is a stack snippet that generates a leaderboard as well as a tree diagram of all of the answers.  I would like to thank Martin Büttner and d3noob as the sources for a lot of this code.  You should click "Full screen" to see the complete results.

function answersUrl(t){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+t+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(t){answers.push.apply(answers,t.items),t.has_more?getAnswers():process()}})}function shouldHaveHeading(t){var e=!1,r=t.body_markdown.split("\n");try{e|=/^#/.test(t.body_markdown),e|=["-","="].indexOf(r[1][0])>-1,e&=LANGUAGE_REG.test(t.body_markdown)}catch(a){}return e}function shouldHaveScore(t){var e=!1;try{e|=SIZE_REG.test(t.body_markdown.split("\n")[0])}catch(r){}return e}function getAuthorName(t){return t.owner.display_name}function decodeEntities(t){return $("<textarea>").html(t).text()}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.reverse();var t={},e=[],r=1,a=null,n=1,s=[];answers.forEach(function(t){var r=t.body_markdown.split("\n")[0],a=getAuthorName(t),n=r.match(SEQUENCE_REG)[0];n=n.trim();var o="from A000000";PARENT_REG.test(r)&&(o=r.match(PARENT_REG)[0]),o=o.substring(5).trim(),"A000000"==o&&(o="OEIS");var i="";SEQDATA_REG.test(t.body_markdown)&&(i=t.body_markdown.match(SEQDATA_REG)[1]);for(var u=!0,c=0;c<e.length;++c)u=u&&!(e[c]===n);for(var l=!0,c=0;c<e.length;++c)l=!(!l||e[c]===n||e[c]===n+a||e[c]===o+a);e.push(n),e.push(n+a),e.push(o+a),u&&data.push({name:n,parent:o,term:i+" : ",author:decodeEntities(a),URL:t.share_link}),l&&s.push(t)}),answers.sort(function(t,e){var r=t.body_markdown.split("\n")[0].match(SEQUENCE_REG),a=e.body_markdown.split("\n")[0].match(SEQUENCE_REG);return a>r?-1:r>a?1:void 0}),answers.forEach(function(e){var o=e.body_markdown.split("\n")[0],i=(o.match(NUMBER_REG)[0],(o.match(SIZE_REG)||[0])[0]),u=parseInt((o.match(DEPTH_REG)||[0])[0]).toString(),c=o.match(SEQUENCE_REG)[0],l="from A000000";PARENT_REG.test(o)&&(l=o.match(PARENT_REG)[0]),l=l.substring(5);var d=o.match(LANGUAGE_REG)[1];d.indexOf("]")>0&&(d=d.substring(1,d.indexOf("]")));for(var p=getAuthorName(e),E=!1,h=0;h<s.length;++h)E=E||s[h]===e;if(E){var f=jQuery("#answer-template").html();i!=a&&(n=r),a=i,++r;var m=1024*Math.pow(parseInt(u),.5)/(parseInt(i)+256);f=f.replace("{{SEQUENCE}}",c).replace("{{SEQUENCE}}",c).replace("{{NAME}}",p).replace("{{LANGUAGE}}",d).replace("{{SIZE}}",i).replace("{{DEPTH}}",u).replace("{{LINK}}",e.share_link),f=jQuery(f),jQuery("#answers").append(f),t[p]=t[p]||{lang:d,user:p,size:"0",numanswers:"0",link:e.share_link},t[p].size=(parseFloat(t[p].size)+m).toString(),t[p].numanswers=(parseInt(t[p].numanswers)+1).toString()}});var o=[];for(var i in t)t.hasOwnProperty(i)&&o.push(t[i]);o.sort(function(t,e){return parseFloat(t.size)>parseFloat(e.size)?-1:parseFloat(t.size)<parseFloat(e.size)?1:0});for(var u=0;u<o.length;++u){var c=jQuery("#language-template").html(),i=o[u];c=c.replace("{{RANK}}",u+1+".").replace("{{NAME}}",i.user).replace("{{NUMANSWERS}}",i.numanswers).replace("{{SIZE}}",i.size),c=jQuery(c),jQuery("#languages").append(c)}createTree()}function createTree(){function t(){var t=i.nodes(root).reverse(),e=i.links(t);t.forEach(function(t){t.y=180*t.depth});var r=c.selectAll("g.node").data(t,function(t){return t.id||(t.id=++o)}),a=r.enter().append("g").attr("class","node").attr("transform",function(t){return"translate("+t.y+","+t.x+")"});a.append("a").attr("xlink:href",function(t){return t.URL}).append("circle").attr("r",10).style("fill","#fff"),a.append("text").attr("x",function(){return 0}).attr("y",function(){return 20}).attr("dy",".35em").attr("text-anchor",function(){return"middle"}).text(function(t){return t.term+t.name}).style("fill-opacity",1),a.append("text").attr("x",function(){return 0}).attr("y",function(){return 35}).attr("dy",".35em").attr("text-anchor",function(){return"middle"}).text(function(t){return t.author}).style("fill-opacity",1);var n=c.selectAll("path.link").data(e,function(t){return t.target.id});n.enter().insert("path","g").attr("class","link").attr("d",u)}var e=data.reduce(function(t,e){return t[e.name]=e,t},{}),r=[];data.forEach(function(t){var a=e[t.parent];a?(a.children||(a.children=[])).push(t):r.push(t)});var a={top:20,right:120,bottom:20,left:120},n=3203-a.right-a.left,s=4003-a.top-a.bottom,o=0,i=d3.layout.tree().size([s,n]),u=d3.svg.diagonal().projection(function(t){return[t.y,t.x]}),c=d3.select("body").append("svg").attr("width",n+a.right+a.left).attr("height",s+a.top+a.bottom).append("g").attr("transform","translate("+a.left+","+a.top+")");root=r[0],t(root)}var QUESTION_ID=49223,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",data=[{name:"OEIS",parent:"null",term:"",author:"",URL:"https://oeis.org/"}],answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*,)/,DEPTH_REG=/\d+, A/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/,SEQUENCE_REG=/A\d+/,PARENT_REG=/from\s*A\d+/,SEQDATA_REG=/terms:\s*(?:(?:-)?\d+,\s*)*((?:-)?\d+)/;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align: left !important}#answer-list{padding: 10px; width: 550px; float: left;}#language-list{padding: 10px; width: 290px; float: left;}table thead{font-weight: bold;}table td{padding: 5px;}.node circle{fill: #fff; stroke: steelblue; stroke-width: 3px;}.node text{font: 12px sans-serif;}.link{fill: none; stroke: #ccc; stroke-width: 2px;}</code>```

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

Sequence List

 Sequence	Author	Language	Size	Depth

Leaderboard

 Rank	User	Answers	Score

 {{SEQUENCE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	{{DEPTH}}	Link

 {{RANK}}	{{NAME}}	{{NUMANSWERS}}	{{SIZE}}

```

答:
Mathematica, 20 bytes, depth 10, A225545 from A098388

```<code>Floor@*Exp@*LambertW
</code>```

Does what it says on the tin (takes ⌊eW(n)⌋). LambertW appears to be an alias for ProductLog. The next answer should start with the terms:

```<code>1, 1, 2, 2, 3, 3, 4, 4, 4, 5
</code>```

Title: Evolution of OEIS

Body:
Mathematica, 20 bytes, depth 10, A225545 from A098388

Floor@*Exp@*LambertW

Does what it says on the tin (takes ⌊eW(n)⌋). LambertW appears to be an alias for ProductLog. The next answer should start with the terms:

1, 1, 2, 2, 3, 3, 4, 4, 4, 5


答:
PHP

Inspired by the use of regex in most of the answers, I originally tried to do this without using regex at all just to show off a neat variation, but the sticking point of not having clean strings as input ruined that idea. Sad.

With function wrapper, 89 bytes

```<code>function f($s){foreach(preg_split('/\W/',$s)as$w)$c[lcfirst($w)[0]]++?:$v.=" $w";echo$v;}
</code>```

Without function wrapper (needing $s pre-declared), 73 bytes

```<code>foreach(preg_split('/\W/',$s)as$w)$c[lcfirst($w)[0]]++?:$v.=" $w";echo$v;
</code>```

Explanation:

```<code>foreach(preg_split('/\W/',$s)as$w)$c[lcfirst($w)[0]]++?:$v.=" $w";echo$v;
        preg_split('/\w/',$s)                                             Break input on all non-word characters
foreach(                     as$w)                                        Loop through each 'word'
                                     lcfirst($w)[0]                       Take the first letter of the lowercase version of the word
                                  $c[              ]++?:                  Increment an array element with a key of that letter after checking if it's false-y (0)
                                                        $v.=" $w";        Add the word if the letter wasn't found (if the previous condition evaluated to false)
                                                                  echo$v; Print the new string to screen.
</code>```

My only regret is that I couldn't find a faster way of checking/converting letter case.

Title: Find the first word starting with each letter

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

Sample

Using Ferulas flourish in gorgeous gardens. as input:

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

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

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

Challenge

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

Program or function allowed.

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

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

Another samples:

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

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

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

Body:
PHP

Inspired by the use of regex in most of the answers, I originally tried to do this without using regex at all just to show off a neat variation, but the sticking point of not having clean strings as input ruined that idea. Sad.

With function wrapper, 89 bytes

function f($s){foreach(preg_split('/\W/',$s)as$w)$c[lcfirst($w)[0]]++?:$v.=" $w";echo$v;}

Without function wrapper (needing $s pre-declared), 73 bytes

foreach(preg_split('/\W/',$s)as$w)$c[lcfirst($w)[0]]++?:$v.=" $w";echo$v;

Explanation:

foreach(preg_split('/\W/',$s)as$w)$c[lcfirst($w)[0]]++?:$v.=" $w";echo$v;
        preg_split('/\w/',$s)                                             Break input on all non-word characters
foreach(                     as$w)                                        Loop through each 'word'
                                     lcfirst($w)[0]                       Take the first letter of the lowercase version of the word
                                  $c[              ]++?:                  Increment an array element with a key of that letter after checking if it's false-y (0)
                                                        $v.=" $w";        Add the word if the letter wasn't found (if the previous condition evaluated to false)
                                                                  echo$v; Print the new string to screen.

My only regret is that I couldn't find a faster way of checking/converting letter case.


问:
"Hello, World!"
So... uh... this is a bit embarrassing. But we don't have a plain "Hello, World!" challenge yet (despite having 35 variants tagged with hello-world, and counting). While this is not the most interesting code golf in the common languages, finding the shortest solution in certain esolangs can be a serious challenge. For instance, to my knowledge it is not known whether the shortest possible Brainfuck solution has been found yet.

Furthermore, while all of <s>Wikipedia</s> (the Wikipedia entry has been deleted but there is a copy at archive.org
), esolangs and Rosetta Code have lists of "Hello, World!" programs, none of these are interested in having the shortest for each language (there is also this GitHub repository). If we want to be a significant site in the code golf community, I think we should try and create the ultimate catalogue of shortest "Hello, World!" programs (similar to how our basic quine challenge contains some of the shortest known quines in various languages). So let's do this!

The Rules

Each submission must be a full program.

The program must take no input, and print Hello, World! to STDOUT (this exact byte stream, including capitalization and punctuation) plus an optional trailing newline, and nothing else.

The program must not write anything to STDERR.

If anyone wants to abuse this by creating a language where the empty program prints Hello, World!, then congrats, they just paved the way for a very boring answer.

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

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

This is not about finding the language with the shortest "Hello, World!" program. This is about finding the shortest "Hello, World!" program in every language. Therefore, I will not mark any answer as "accepted".

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

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

For inspiration, check the Hello World Collection.

The Catalogue

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

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

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

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

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

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

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

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

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

/* Configuration */

var QUESTION_ID = 55422; // 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 = 8478; // 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,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  text-align: left !important;
  display: block !important;
}

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

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

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
.kill();, 39 bytes

Try it here! Github.

```<code>SFTp^B2lA=ZkW`j\9@+*+@9\j`WkZ=Al2B^pTGT
</code>```

Alright, so I made another monster! This is how this works. First, the code is iterated through, and a resulting string is made. First, let's look at the first character and some related information:

```<code>char: S
opposite char: T
average char floored: (@S + @T) / 2 = (83 + 84) / 2 = 83.5 => 83 = S
index: 0
result: S
</code>```

Each character in the new string is calculated by averaging the values of the current char and the char that lies the same distance from the end of the string; this value is incremented by the index (starting at zero) then floored. The resulting character is appended to the result.

Once this result is made, we look for a valid base64 string in it. This is what that result looks like:

```<code>SGVsbG8sIFdvcmxkIQ==?UOs#yq'vZ_,Rc!4xky
</code>```

This will result in the string SGVsbG8sIFdvcmxkIQ== being found as the base 64 string for "Hello, World!", and is thus outputted.

(When no such string is found, then a more complicated algorithm ensues that transpiles this to JavaScript, so this is most definitely turing-complete and thus a valid language.)

ContentLicense: CC BY-SA 4.0

Title: "Hello, World!"

Body:
.kill();, 39 bytes

Try it here! Github.

SFTp^B2lA=ZkW`j\9@+*+@9\j`WkZ=Al2B^pTGT

Alright, so I made another monster! This is how this works. First, the code is iterated through, and a resulting string is made. First, let's look at the first character and some related information:

char: S
opposite char: T
average char floored: (@S + @T) / 2 = (83 + 84) / 2 = 83.5 => 83 = S
index: 0
result: S

Each character in the new string is calculated by averaging the values of the current char and the char that lies the same distance from the end of the string; this value is incremented by the index (starting at zero) then floored. The resulting character is appended to the result.

Once this result is made, we look for a valid base64 string in it. This is what that result looks like:

SGVsbG8sIFdvcmxkIQ==?UOs#yq'vZ_,Rc!4xky

This will result in the string SGVsbG8sIFdvcmxkIQ== being found as the base 64 string for "Hello, World!", and is thus outputted.

(When no such string is found, then a more complicated algorithm ensues that transpiles this to JavaScript, so this is most definitely turing-complete and thus a valid language.)


答:
Oracle SQL 11.2, <s>104</s> 118 bytes

```<code>SELECT MAX(:1+:2-LEVEL+1)FROM DUAL WHERE(MOD(:1,:1+:2-LEVEL+1)+MOD(:2,:1+:2-LEVEL+1))*:1*:2=0 CONNECT BY LEVEL<=:1+:2;
</code>```

Fixed for input of 0

Title: Greatest Common Divisor

Body:
Oracle SQL 11.2, <s>104</s> 118 bytes

SELECT MAX(:1+:2-LEVEL+1)FROM DUAL WHERE(MOD(:1,:1+:2-LEVEL+1)+MOD(:2,:1+:2-LEVEL+1))*:1*:2=0 CONNECT BY LEVEL<=:1+:2;

Fixed for input of 0


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

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

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

If that number is 1, print out 1 forever.

Challenge

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

take input from STDIN or an acceptable alternative

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

must output to STDOUT or an acceptable alternative

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

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

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

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

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of code-golf must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Oration, 101 bytes

```<code>start a function t with x
inhale
to iterate, 1
literally, print x
if not x:break#
invoke t with input
</code>```

Very long.  Starts a function called t with arguments x.

Inhale is a command used to keep the program running, you need oxygen to execute. :P

to iterate,  starts a while $1 loop, so this becomes while 1:.

literally, print x just prints x, the function input.

if not x:break# is a simple if statement.  The # is there because the compiler appends a : to it, so that becomes if not x:break#:.  It happens to be golfier than the following good code with normal syntax.

if not x
goodbye
```
<p><code>invoke t with input</code> calls the function.</p>
<p>Transpiles to:</p>
<pre class="lang-python prettyprint-override"><code>#!/usr/bin/env python3
def t(x):
    while 1:
        print x
        if not x:break#:
t(input("~> "))
</code>```

Title: Implement a Truth-Machine

Body:
Oration, 101 bytes

start a function t with x
inhale
to iterate, 1
literally, print x
if not x:break#
invoke t with input

Very long.  Starts a function called t with arguments x.

Inhale is a command used to keep the program running, you need oxygen to execute. :P

to iterate,  starts a while $1 loop, so this becomes while 1:.

literally, print x just prints x, the function input.

if not x:break# is a simple if statement.  The # is there because the compiler appends a : to it, so that becomes if not x:break#:.  It happens to be golfier than the following good code with normal syntax.

if not x
goodbye

invoke t with input calls the function.

Transpiles to:

#!/usr/bin/env python3
def t(x):
    while 1:
        print x
        if not x:break#:
t(input("~> "))


答:
Reng v.3.3, 6 bytes

```<code>i:n?~!
</code>```

Try it here!

This takes input I, duplicates, outputs as number, ? skips if true. If false, ~ is met and the program ends. Otherwise, we skip ~ then skip i with !, and it repeats.

Title: Implement a Truth-Machine

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

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

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

If that number is 1, print out 1 forever.

Challenge

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

take input from STDIN or an acceptable alternative

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

must output to STDOUT or an acceptable alternative

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

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

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

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

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of code-golf must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
Reng v.3.3, 6 bytes

i:n?~!

Try it here!

This takes input I, duplicates, outputs as number, ? skips if true. If false, ~ is met and the program ends. Otherwise, we skip ~ then skip i with !, and it repeats.


问:
De-Snakify a String
A regular string looks like this:

```<code>Hello,IAmAStringSnake!
</code>```

And a string snake looks something like this:

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan
</code>```

Your Task

String snakes are dangerous, so you must make a program that takes a string snake as input and outputs it as a regular string.

Specifications

Input can be a multiline string or an array of strings.

Each line of the input will be padded with spaces to form a rectangular grid.

Characters in the snake can only connect to adjacent characters above, below, left or right of them (just like in the game Snake). They cannot go diagonal.

The snake characters will never be adjacent to another part of the snake, only the connected characters.

The first character of the string is the end character with the shortest Manhattan distance from the top-left corner of the input grid (i.e. the minimum number of moves it would take for a snake to go directly from the end character to the top-left corner). Both ends will never have the same distance.

The string can contain any ASCII character between code points 33 and 126 inclusive (no spaces or newlines).

The string will be between 2 and 100 characters long.

Shortest code in bytes wins.

Test Cases

(Input grid, followed by the output string)

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan

Hello,IAmAStringSnake!

----------

Python

Python

----------

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

ProgrammingPuzzlesAndCodeGolf

----------

   ~ zyx tsr XWVUTSR
   }|{ wvu q Y     Q
!          p Z `ab P
"#$ 6789:; o [ _ c O
  % 5    < n \]^ d N
('& 432  = m     e M
)     1  > lkjihgf L
*+,-./0  ?         K
         @ABCDEFGHIJ

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

----------

  tSyrep
  r    p
  in Sli
   g    Sile
   Snakes  n
Ser      ylt
a eh   ilS
fe w   t
   emo h
     Sre

SlipperyStringSnakesSilentlySlitherSomewhereSafe
</code>```

答:
APL, 55 bytes

```<code>{⍵[1↓(⊂0 0){1<⍴⍵:⍺,∆[⊃⍋+/¨|⍺-∆]∇∆←⍵~⍺⋄⍺}(,⍵≠' ')/,⍳⍴⍵]}
</code>```

This function takes a character matrix with the string snake in it.

Example:

```<code>      s1 s2 s3
┌────────────┬──────────────┬────────────────────┐
│Hel         │P  ngPu  Code │   ~ zyx tsr XWVUTSR│
│  l      rin│r  i  z  d  G │   }|{ wvu q Y     Q│
│  o,IAmAst g│o  m  z  n  o │!          p Z `ab P│
│           S│gram  lesA  lf│"#$ 6789;: o [ _ c O│
│       !ekan│              │  % 5    < n \]^ d N│
│            │              │('& 432  = m     e M│
│            │              │)     1  > lkjighf L│
│            │              │*+,-./0  ?         K│
│            │              │         @ABCDEFGHIJ│
└────────────┴──────────────┴────────────────────┘
      ↑ {⍵[1↓(⊂0 0){1<⍴⍵:⍺,∆[⊃⍋+/¨|⍺-∆]∇∆←⍵~⍺⋄⍺}(,⍵≠' ')/,⍳⍴⍵]} ¨ s1 s2 s3
Hello,IAmAstringSnake!
ProgrammingPuzzlesAndCodeGolf
!"#$%&'()*+,-./0123456789;:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefhgijklmnopqrstuvwxyz{|}~
</code>```

Explanation:

(,⍵≠' ')/,⍳⍴⍵: get the coordinates of all non-spaces

(⊂0 0): begin at (0,0) (which is an invalid coordinate)

{...}: follow the snake, given position and snake:

1<⍴⍵:: if there is more than 1 element left:

∆←⍵~⍺: remove the current position from the snake and store it in ∆.

+/¨|⍺-∆: find the distance between the current position and each point in the rest of the snake

∆[⊃⍋...]`: get the closest point on the snake

∇: run the function again, with the closest point as the new current point and the shortened snake as the new snake.

⍺,: add the current position to the result of that

⋄⍺: otherwise, just return the current position

1↓: drop the first item from the result (which is the (0,0) position)

⍵[...]: get those elements from ⍵, in that order

Title: De-Snakify a String

Body:
APL, 55 bytes

{⍵[1↓(⊂0 0){1<⍴⍵:⍺,∆[⊃⍋+/¨|⍺-∆]∇∆←⍵~⍺⋄⍺}(,⍵≠' ')/,⍳⍴⍵]}

This function takes a character matrix with the string snake in it.

Example:

      s1 s2 s3
┌────────────┬──────────────┬────────────────────┐
│Hel         │P  ngPu  Code │   ~ zyx tsr XWVUTSR│
│  l      rin│r  i  z  d  G │   }|{ wvu q Y     Q│
│  o,IAmAst g│o  m  z  n  o │!          p Z `ab P│
│           S│gram  lesA  lf│"#$ 6789;: o [ _ c O│
│       !ekan│              │  % 5    < n \]^ d N│
│            │              │('& 432  = m     e M│
│            │              │)     1  > lkjighf L│
│            │              │*+,-./0  ?         K│
│            │              │         @ABCDEFGHIJ│
└────────────┴──────────────┴────────────────────┘
      ↑ {⍵[1↓(⊂0 0){1<⍴⍵:⍺,∆[⊃⍋+/¨|⍺-∆]∇∆←⍵~⍺⋄⍺}(,⍵≠' ')/,⍳⍴⍵]} ¨ s1 s2 s3
Hello,IAmAstringSnake!
ProgrammingPuzzlesAndCodeGolf
!"#$%&'()*+,-./0123456789;:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefhgijklmnopqrstuvwxyz{|}~

Explanation:

(,⍵≠' ')/,⍳⍴⍵: get the coordinates of all non-spaces

(⊂0 0): begin at (0,0) (which is an invalid coordinate)

{...}: follow the snake, given position and snake:

1<⍴⍵:: if there is more than 1 element left:

∆←⍵~⍺: remove the current position from the snake and store it in ∆.

+/¨|⍺-∆: find the distance between the current position and each point in the rest of the snake

∆[⊃⍋...]`: get the closest point on the snake

∇: run the function again, with the closest point as the new current point and the shortened snake as the new snake.

⍺,: add the current position to the result of that

⋄⍺: otherwise, just return the current position

1↓: drop the first item from the result (which is the (0,0) position)

⍵[...]: get those elements from ⍵, in that order


问:
Insert semi-sorted into unsorted array
Welcome to your first day at PPCG Inc. As our newest junior assistant document sorter, you are responsible for making sure all documents we sent down to you are archived in alphabetical order. It's so easy a monkey can do it. Well, metaphorically speaking, as we did hire a monkey to do it. Guess what? Turns out monkeys lack an understanding of our alphabet. Anyway, there's no time to fix the mess there is right now, so just try to not make the situation any worse, ok? Then get to it! If you get hungry, there's bananas over by the water cooler. Good luck!

Job Description

Input

You will receive a list of strings (the archive) and a string that needs to be added to that list (the document)

All strings will contain only uppercase letters, lowercase letters and spaces

Strings will always start and end with a letter

Task

Determine the target position of the document: the position it should receive in the archive. The target position can be determined as follows:

For each position:

Count the amount of strings in the archive before that position that are alphabetically before the document

Count the amount of strings in the archive after that position that are alphabetically after the document

Define the score of the position as the sum of the above two counts

The target position of the document is the position with the highest score

In case of a tie, all positions with the highest score are equally valid as target position. Only one needs to be selected.

When sorting:

Uppercase and lowercase letters are equivalent

Spaces come before letters

Output

The archive with the document added to it in any form

OR

The target position of the document, in either a 0-based or 1-based index

Job evaluation

Fewest bytes wins!

Example I/O

```<code>Archive:
    Applebuck Season
    Friendship is Magic
    The Ticket Master
    Griffon the BrushOff
    Boast Busters
    Bridle Gossip

Document: Dragonshy

Position scores (0-based index):
0: 0 + 3 = 3
1: 1 + 3 = 4
2: 1 + 2 = 3
3: 1 + 1 = 2
4: 1 + 0 = 1
5: 2 + 0 = 2
6: 3 + 0 = 3

Target position: 1
</code>```

答:
MATL, 32 bytes

```<code>hk4#S4#S%2#0)>t0whYsw~0hPYsP+K#X>
</code>```

Input is a cell array of strings (several strings separated by spaces and enclosed in curly braces) for the archive, and a string for the document. Output is 1-based. In case of a tie the first position is returned.

Try it online!

Explanation

```<code>h      % Concatenate archive and document as a cell array of strings
k      % Convert all strings to lowercase
4#S    % Sort and output the indices of the sorting
4#S    % Again. This gives the indices that applied to the concatenated
       % array would make it sorted
2#0)   % Separate last index (document) from the others (archive)
>      % Is it greater? Gives zero/one array the size of the archive
t      % Duplicate that array
0wh    % Prepend a 0
Ys     % Cumulative sum. This is first part of the score
w~     % Swap. Negate zero/one array
0h     % Postpend a 0
PYsP   % Reverse, cumulative sum, reverse. Second part of the score
+      % Add. This is the score of each position
K#X>   % Arg max
</code>```

Title: Insert semi-sorted into unsorted array

Body:
MATL, 32 bytes

hk4#S4#S%2#0)>t0whYsw~0hPYsP+K#X>

Input is a cell array of strings (several strings separated by spaces and enclosed in curly braces) for the archive, and a string for the document. Output is 1-based. In case of a tie the first position is returned.

Try it online!

Explanation

h      % Concatenate archive and document as a cell array of strings
k      % Convert all strings to lowercase
4#S    % Sort and output the indices of the sorting
4#S    % Again. This gives the indices that applied to the concatenated
       % array would make it sorted
2#0)   % Separate last index (document) from the others (archive)
>      % Is it greater? Gives zero/one array the size of the archive
t      % Duplicate that array
0wh    % Prepend a 0
Ys     % Cumulative sum. This is first part of the score
w~     % Swap. Negate zero/one array
0h     % Postpend a 0
PYsP   % Reverse, cumulative sum, reverse. Second part of the score
+      % Add. This is the score of each position
K#X>   % Arg max


答:
Lua, <s>382</s> <s>376</s> <s>367</s> <s>353</s> 348 bytes

```<code>r="\n"o=... n=o:find(r)-1
l=n+n%2
a=o:gsub(r,(n~=l and" "or"")..r).." "..(#o//(l+1)%2<1 and r..(" "):rep(l)or"")print(a:gsub("()([^\n])(.)",function(p,m,c)t=p//(l+1)%2==0return string.char(math.floor((m:byte()+c:byte()+(t and a:sub(p+l+1,p+l+1)or a:sub(p-l,p-l)):byte()+(t and a:sub(p+l+2,p+l+2)or a:sub(p-l-1,p-l-1)):byte())/4+.5)):rep(2)end).."")
</code>```

Works on the command line; accepts a string like the test case.

Title: Average an image

Body:
Here is an image:

```<code>%%%%%%%%%%%%%
% Hello,    %
%    world! %
%%%%%%%%%%%%%
</code>```

But it is too confusing for our undersized brains to compute. So we average it like this:

Split it into 2 x 2 sections. If the picture ends before a section is complete, imagine that there are spaces there.

Average the values of the ASCII characters in each section.

Round this average and convert it to an ASCII character.

Finally, replace all characters in the section to the average character.

Repeat this for all sections.

So the average of the image above looks like this:

```<code>$$>>II99######
$$>>II99######
$$##88KKGG####
$$##88KKGG####
</code>```

Your task: Write  a program that takes an ASCII image as input and outputs its average.

Note Integers are rounded by function floor(x+0.5) or similar function - in other words, round halves upwards.

Body:
Lua, <s>382</s> <s>376</s> <s>367</s> <s>353</s> 348 bytes

r="\n"o=... n=o:find(r)-1
l=n+n%2
a=o:gsub(r,(n~=l and" "or"")..r).." "..(#o//(l+1)%2<1 and r..(" "):rep(l)or"")print(a:gsub("()([^\n])(.)",function(p,m,c)t=p//(l+1)%2==0return string.char(math.floor((m:byte()+c:byte()+(t and a:sub(p+l+1,p+l+1)or a:sub(p-l,p-l)):byte()+(t and a:sub(p+l+2,p+l+2)or a:sub(p-l-1,p-l-1)):byte())/4+.5)):rep(2)end).."")

Works on the command line; accepts a string like the test case.


问:
Interpret Befunge-93
The program will be provided as the first argument, stdin should be used for all
read requests by the program and stdout for all write requests.  It can be
assumed that the program is less than 80 characters wide and less than 25 lines
high.

~ should push -1 if there is nothing to read.

Any pop off the bottom of the list should simply return 0, including for any calculations.

For p and g, x and y are 0 based indices.

Input should be fully buffered, i.e. & and ~ block the program until EOF is encountered on stdin then any remaining input is kept to serve future requests.

The following commands must be available:

0-9

    Push this number on the stack

+

    Addition: Pop a then b, push a+b

-

    Subtraction: Pop a then b, push b-a

*

    Multiplication: Pop a then b, push a*b

/

    Integer division: Pop a then b, push b/a, rounded down. If a is 0, result is undefined

%

    Modulo: Pop a then b, push the remainder of the integer division of b/a. If a is 0, result is undefined

!

    Logical NOT: Pop a value. If the value is 0, push 1; otherwise, push 0.

`

    Greater than: Pop a then b, push 1 if b>a, otherwise 0.

>

    Start moving right

<

    Start moving left

^

    Start moving up

v

    Start moving down

?

    Start moving in a random cardinal direction

_

    Pop a value; move right if value=0, left otherwise

|

    Pop a value; move down if value=0, up otherwise

"

    Start string mode: push each character's ASCII value all the way up to the next "

:

    Duplicate value on top of the stack

\

    Swap two values on top of the stack

$

    Pop value from the stack

.

    Pop value and output as an integer

,

    Pop value and output as ASCII character

#

    Trampoline: Skip next cell

p

    A "put" call (a way to store a value for later use). Pop y then x then v, change the character at the position (x,y) in the program to the character with ASCII value v

g

    A "get" call (a way to retrieve data in storage). Pop y then x, push ASCII value of the character at that position in the program

&

    Input an integer (may be multiple characters and may be negative) and push it

~

    Input a single character from stdin and push its ASCII value

@

    End program

This is a code golf, shortest answer wins.  If there is a tie then the first answer wins.

You may use any language feature not specifically designed for Befunge to implement this, if you want to try and translate Befunge to native code and eval it good luck.

For test cases look at my recent answers.  The reference interpreter I have been using is http://www.quirkster.com/js/befunge.html.

One quick test case of some features from "egnufeB">:#,_@

```<code>1-0g:"Z"-#v_$91+"sparw tup/teG">:#,_$               v                          Z
          >:" "-#v_$91+"ecaps snruter teg BOO">:#,_$v
v                >0" snruter teg BOO">:#,_$.91+,    >
>8:+:*11p11g#v_91+"tib 8 dengis"01-11p11g!#v_"nu">" era slleC">:#,_v
vv           >91+"tib 8>"                  >     ^                 >91+"krow " #
 >        >"spmuj egdE">:#,_   91+"krow "04-3%1+#v_        >"sredniamer evitag"v
>"ton od "^                                      >"ton od "^
"eN">:#,_  91+"skrow edomgnirts ni @">:#,_@                                    >
</code>```

答:
16bit MSDOS .COM File - 1104 bytes

This is Base64 encoded (decoder here), save decoded file as a .com and execute from command line with name of program file to run as the only argument. Tested in WinXP command prompt.

```<code>yEAAADP/jNiAxBCJRv6JRvKAxBCJfuqJRuyJfvqJfviJfvSAxBCJRvbHRuiMAo7AM8C5AIDzq7Qs
zSGJVvC6RgWKHoAAMv+A6wF9Cei3ALQJzSHJw8aHggAAuAA9uoIAzSG6SAVy5YvYjkb+uQCAM8Dz
q7kBALpQBbQ/zSG6SgVyygvAdCWgUAU8CnQHPCBy4qrr34vHOkb5cgOIRvn+RviB5wD/gccAAevI
tD7NIQv/ukwFdJa4AwDNEDPb6FQAtAfNITxxdDk8cnQhPDF0DTwydBE8c3Xo6I8A6+CLRvaJRvLr
2ItG/olG8uvQi0b2iUby6B4A6HEAgH76AHTu67zoAgDJw7gAuI7AuCAHuQCA86vDYB6OXvK4ALiO
wLUZM/8z9rQHsVCsq/7JdfqBxrAA/s118FOLRvI7Rv6yz3QFi170svCA+1BzG4D/GXMWise0oPbk
ANiA1AAA2IDUAIv4R4rCqlsfYcOORv4migc8MHJVPDl3UbQALDDoKwD/ZugK23UDil75/svD/sM6
Xvl1+DLbwwr/dQOKfvj+z8P+xzp++HX4Mv/DBsR+6quJfuoHwwbEfuozwAv/dAmD7wImiwWJfuoH
w77uBIPGA4A8/3QOOAR19ItEAQvAdAP/4MO6TgXpZP7olP8migc8InSNtADos//r7+i4/4nB67To
9v8Dwel0/+ju/yvB6Wz/6Ob/9+npZP/o3v+Z9/npW//o1f+Z9/mLwulQ/+iF/wvAuAEAdAFI6UL/
6Lz/O8G4AQB/AUjpNP/HRuiMAukv/+hh/wvAdPHHRuiCAukg/+hS/wvAdAjHRuiWAukR/8dG6KAC
6Qn/i0bwuk189+IFGTaJRvAkBgWSA4vwrYlG6Ont/pYCoAKCAowC6Bf/6Ar/6dn+6FP/kegA/4nI
6c3+6AL/6cr+6Pz+C8B5CffYULAt6CYAWFO7UAUz0rkKAPfxgMIwiBdDC8B170uKB+gKAIH7UAV1
9Fvplf48CnQUBsR+9KqLxzxQdQSBx7AAiX70B8PGRvQA/kb1w+in/uja/+ls/uhp/ulm/ugOAOiV
/gaORv4miAQH6VX+6If+ik74C8B5BwLBgNQA6/X28YjhtQDocP5Rik75C8B5BwLBgNQA6/X28Yjg
WYjMi/DD6Mr/Bo5G/iaKBAe0AOkP/v928otG9olG8jP2Msnol/20B80hPC11CwrJdfH+wehc/+vq
PA11Do9G8ovGCsl0AvfY6dr9iMUsMDwJd9C0AFCwCvfmC9JadcT2xIB1vwHC9saAdbiJ1ojo6CH/
66//dvKLRvaJRvLoPf20B80hPCBy+FDoB/9YtACPRvLpkP3GRvoBwysAAy0IAyoQAy8YAyUhAyEs
A2A6Az5IAzxXA15mA3ZuAz92A19QA3xfAyLoAjqaA1yjAySvAy61AywKBCMTBHAZBGddBCZtBH7L
BEDsBCB/AgB/Av8xJDIkMyQ0JDUk
</code>```

On startup, the display shows the program. Commands are:

r - runs the program (switches to output screen)

s - single steps the program

q - quits the interpreter

1 - shows output screen (white cursor is current output position)

2 - shows program screen (red cursors is current program position)

When an input command is executed, the display switches to the output screen. Input is echoed to the output screen. For ascii input, only characters in the range 32-255 are accepted. For numeric input, only values in the range -32768 to 32767 are allowed, press enter to complete input (sorry, no backspace).

I really should add a stack screen as well.

Update

Here's the original assembly source code, assembled using A86. It's quite long:

```<code>  enter 64,0
  xor di,di
  mov ax,ds
  add ah,10h
  mov [bp-2],ax   ; program
  mov [bp-14],ax  ; current display
  add ah,10h
  mov w[bp-22],di ; stack off
  mov [bp-20],ax  ; stack seg
  mov w[bp-6],di  ; exit status
  mov w[bp-8],di  ; size of field -8=lines,-7=columns
  mov w[bp-12],di ; output window position
  add ah,10h
  mov w[bp-10],ax; output segment
  mov w[bp-24],MoveRight

  ; clear output
  mov es,ax
  xor ax,ax
  mov cx,8000h
  rep stosw

  ; random seed
  mov ah,2ch
  int 21h
  mov w[bp-16],dx

  ; get filename
  mov dx,StrNoFile
  mov bl,[80h]
  xor bh,bh
  sub bl,1
  jge NoError

Error:
  call ClearScreen
  mov ah,9
  int 21h
  leave
  ret

NoError:
  ; open file
  mov b[82h+bx],0
  mov ax,3d00h
  mov dx,82h
  int 21h
  mov dx,StrBadFile
  jc Error
  mov bx,ax
  ; clear program
  mov es,[bp-2]
  mov cx,8000h
  xor ax,ax
  rep stosw
  ; read file
ReadLoop:
  mov cx,1
  mov dx,EOP
  mov ah,3fh
  int 21h
  mov dx,StrBadRead
  jc Error
  or ax,ax
  jz EOF
  mov al,b[EOP]
  cmp al,10
  je EOL
  cmp al,32
  jb ReadLoop
  stosb
  jmp ReadLoop
EOL:
  mov ax,di
  cmp al,[bp-7]
  jb l9
  mov [bp-7],al
l9:
  inc b[bp-8]
  and di,0ff00h
  add di,100h
  jmp ReadLoop
EOF:
  mov ah,3eh
  int 21h
  or di,di
  mov dx,StrEmptyFile
  jz Error
  ; initialise
  mov ax,3
  int 10h
  xor bx,bx ; PC
  ; execute
Redraw:
  call DisplayProgram
WaitForInput:
  mov ah,7
  int 21h
  cmp al,'q'
  je Quit
  cmp al,'r'
  je DoRun
  cmp al,'1'
  je ShowIO
  cmp al,'2'
  je ShowProgram
  cmp al,'s'
  jne WaitForInput
  ; single step
  call Execute
  jmp Redraw

ShowIO:
  mov ax,[bp-10]
  mov [bp-14],ax
  jmp Redraw

ShowProgram:
  mov ax,[bp-2]
  mov [bp-14],ax
  jmp Redraw

DoRun:
  mov ax,[bp-10]
  mov [bp-14],ax
  call DisplayProgram
  call Execute
  cmp b[bp-6],0
  je DoRun
  jmp Redraw

Quit:
  call ClearScreen
  leave
  ret

ClearScreen:
  mov ax,0b800h
  mov es,ax
  mov ax,720h
  mov cx,8000h
  rep stosw
  ret

DisplayProgram:
  pusha
  push ds
  mov ds,[bp-14]
  mov ax,0b800h
  mov es,ax
  mov ch,25
  xor di,di
  xor si,si
  mov ah,7
l1:
  mov cl,80
l2:
  lodsb
  stosw
  dec cl
  jnz l2
  add si,256-80
  dec ch
  jnz l1
  push bx
  mov ax,[bp-14]
  cmp ax,[bp-2]
  mov dl,0cfh
  je l33
  mov bx,[bp-12]
  mov dl,0f0h
l33:
  cmp bl,80
  jae l3
  cmp bh,25
  jae l3
  mov al,bh
  mov ah,160
  mul ah
  add al,bl
  adc ah,0
  add al,bl
  adc ah,0
  mov di,ax
  inc di
  mov al,dl
  stosb
l3:
  pop bx
  pop ds
  popa
  ret

Execute:
  mov es,[bp-2]
  mov al,es:[bx]

  cmp al,'0'
  jb NotPush
  cmp al,'9'
  ja NotPush

  ; push number
  mov ah,0
  sub al,'0'
PushValueUpdatePC:
  call PushValue
UpdatePC:
  jmp [bp-24]

MoveLeft:
  or bl,bl
  jnz MoveLeftNoWrap
  mov bl,[bp-7]
MoveLeftNoWrap:
  dec bl
  ret

MoveRight:
  inc bl
  cmp bl,[bp-7]
  jne ret
  xor bl,bl
  ret

MoveUp:
  or bh,bh
  jnz MoveUpNoWrap
  mov bh,[bp-8]
MoveUpNoWrap:
  dec bh
  ret

MoveDown:
  inc bh
  cmp bh,[bp-8]
  jne ret
  xor bh,bh
  ret

PushValue:
  push es
  les di,[bp-22]
  stosw
  mov [bp-22],di
  pop es
  ret

PopValue:
  push es
  les di,[bp-22]
  xor ax,ax
  or di,di
  jz PopValueZero
  sub di,2
  mov ax,es:[di]
  mov [bp-22],di
PopValueZero:
  pop es
  ret

NotPush:
  mov si,Functions-3
NextFunction:
  add si,3
FindFunction:
  cmp b[si],255
  je Endsearch
  cmp b[si],al
  jne NextFunction
  mov ax,[si+1]
  or ax,ax
  je EndSearch
  jmp ax
  ret

EndSearch:
  mov dx,StrEndSearch
  jmp Error

DoStringMode:
  call UpdatePC
  mov al,es:[bx]
  cmp al,'"'
  je UpdatePC
  mov ah,0
  call PushValue
  jmp DoStringMode

PopTwoValues:
  call PopValue
  mov cx,ax
  jmp PopValue

DoAdd:
  call PopTwoValues
  add ax,cx
  jmp PushValueUpdatePC

DoSub:
  call PopTwoValues
  sub ax,cx
  jmp PushValueUpdatePC

DoMultiply:
  call PopTwoValues
  imul cx
  jmp PushValueUpdatePC

DoDivide:
  call PopTwoValues
  cwd
  idiv cx
  jmp PushValueUpdatePC

DoModulo:
  call PopTwoValues
  cwd
  idiv cx
  mov ax,dx
  jmp PushValueUpdatePC

DoNot:
  call PopValue
  or ax,ax
  mov ax,1
  jz DoNotZero
  dec ax
DoNotZero:
  jmp PushValueUpdatePC

DoGreaterThan:
  call PopTwoValues
  cmp ax,cx
  mov ax,1
  jg DoGreaterThanIs1
  dec ax
DoGreaterThanIs1:
  jmp PushValueUpdatePC

DoMoveRight:
  mov [bp-24],MoveRight
  jmp UpdatePC

DoLeftRight:
  call PopValue
  or ax,ax
  jz DoMoveRight

DoMoveLeft:
  mov [bp-24],MoveLeft
  jmp UpdatePC

DoMoveUpDown:
  call PopValue
  or ax,ax
  jz DoMoveDown

DoMoveUp:
  mov [bp-24],MoveUp
  jmp UpdatePC

DoMoveDown:
  mov [bp-24],MoveDown
  jmp UpdatePC

DoRandomDirection:
  mov ax,[bp-16]
  mov dx,31821
  mul dx
  add ax,13849
  mov [bp-16],ax
  and al,6
  add ax,Movements
  mov si,ax
  lodsw
  mov [bp-24],ax
  jmp UpdatePC

Movements:
  dw MoveUp, MoveDown, MoveLeft, MoveRight

DoDuplicate:
  call PopValue
  call PushValue
  jmp PushValueUpdatePC

DoSwap:
  call PopTwoValues
  xchg ax,cx
  call PushValue
  mov ax,cx
  jmp PushValueUpdatePC

DoPop:
  call PopValue
  jmp UpdatePC

DoPopPrint:
  call PopValue
  or ax,ax
  jns Positive
  neg ax
  push ax
  mov al,'-'
  call PrintChar
  pop ax
Positive:
  push bx
  mov bx,EOP
DivLoop:
  xor dx,dx
  mov cx,10
  div cx
  add dl,'0'
  mov [bx],dl
  inc bx
  or ax,ax
  jnz DivLoop
PrintLoop:
  dec bx
  mov al,[bx]
  call PrintChar
  cmp bx,EOP
  jne PrintLoop
  pop bx
  jmp UpdatePC

PrintChar:
  cmp al,10
  je AsciiCR
  push es
  les di,[bp-12]
  stosb
  mov ax,di
  cmp al,80
  jne NoLF
  add di,256-80
NoLF:
  mov [bp-12],di
  pop es
  ret
AsciiCR:
  mov b[bp-12],0
  inc b[bp-11]
  ret

DoPopAsciiPrint:
  call PopValue
  call PrintChar
  jmp UpdatePC

DoTrampoline:
  call UpdatePC
  jmp UpdatePC

DoPut:
  call GetCoord
  call PopValue
  push es
  mov es,[bp-2]
  mov es:[si],al
  pop es
  jmp UpdatePC

GetCoord:
  call PopValue
  mov cl,[bp-8]
DoGet1:
  or ax,ax
  jns DecrementY
  add al,cl
  adc ah,0
  jmp DoGet1
DecrementY:
  div cl
  mov cl,ah
  mov ch,0
  call PopValue ; x
  push cx
  mov cl,[bp-7]
DoGet2:
  or ax,ax
  jns DecrementX
  add al,cl
  adc ah,0
  jmp DoGet2
DecrementX:
  div cl
  mov al,ah
  pop cx ; ax=x, cx=y
  mov ah,cl
  mov si,ax
  ret

DoGet:
  call GetCoord
  push es
  mov es,[bp-2]
  mov al,es:[si]
  pop es
  mov ah,0
  jmp PushValueUpdatePC

DoInput:
  push [bp-14]
  mov ax,[bp-10]
  mov [bp-14],ax
  xor si,si
  xor cl,cl
DoInput1:
  call DisplayProgram
  mov ah,7
  int 21h
  cmp al,'-'
  jne DoInputEnter
  or cl,cl
  jnz DoInput1
  inc cl
  call PrintChar
  jmp DoInput1

DoInputEnter:
  cmp al,13
  jnz DoInputDigit

  pop [bp-14]
  mov ax,si
  or cl,cl
  jz DoInput3
  neg ax
DoInput3:
  jmp PushValueUpdatePC

DoInputDigit:
  mov ch,al
  sub al,'0'
  cmp al,9
  ja DoInput1
  mov ah,0
  push ax
  mov al,10
  mul si
  or dx,dx
  pop dx
  jnz DoInput1
  test ah,80h
  jnz DoInput1
  add dx,ax
  test dh,80h
  jnz DoInput1
  mov si,dx
  mov al,ch
  call PrintChar
  jmp DoInput1

DoInputAscii:
  push [bp-14]
  mov ax,[bp-10]
  mov [bp-14],ax
  call DisplayProgram
DoInputAscii1:
  mov ah,7
  int 21h
  cmp al,32
  jb DoInputAscii1
  push ax
  call PrintChar
  pop ax
  mov ah,0
  pop [bp-14]
  jmp PushValueUpdatePC

DoExit:
  mov b[bp-6],1
  ret

Functions:
  db '+' ; Addition: Pop a then b, push a+b
  dw DoAdd
  db '-' ; Subtraction: Pop a then b, push b-a
  dw DoSub
  db '*' ; Multiplication: Pop a then b, push a*b
  dw DoMultiply
  db '/' ; Integer division: Pop a then b, push b/a, rounded down. If a is 0, result is undefined
  dw DoDivide
  db '%' ; Modulo: Pop a then b, push the remainder of the integer division of b/a. If a is 0, result is undefined
  dw DoModulo
  db '!' ; Logical NOT: Pop a value. If the value is 0, push 1; otherwise, push 0.
  dw DoNot
  db '`' ; Greater than: Pop a then b, push 1 if b>a, otherwise 0.
  dw DoGreaterThan
  db '>' ; Start moving right
  dw DoMoveRight
  db '<' ; Start moving left
  dw DoMoveLeft
  db '^' ; Start moving up
  dw DoMoveUp
  db 'v' ; Start moving down
  dw DoMoveDown
  db '?' ; Start moving in a random cardinal direction
  dw DoRandomDirection
  db '_' ; Pop a value; move right if value=0, left otherwise
  dw DoLeftRight
  db '|' ; Pop a value; move down if value=0, up otherwise
  dw DoMoveUpDown
  db '"' ; Start string mode: push each character's ASCII value all the way up to the next "
  dw DoStringMode
  db ':' ; Duplicate value on top of the stack
  dw DoDuplicate
  db '\' ; Swap two values on top of the stack
  dw DoSwap
  db '$' ; Pop value from the stack
  dw DoPop
  db '.' ; Pop value and output as an integer
  dw DoPopPrint
  db ',' ; Pop value and output as ASCII character
  dw DoPopAsciiPrint
  db '#' ; Trampoline: Skip next cell
  dw DoTrampoline
  db 'p' ; A "put" call (a way to store a value for later use). Pop y then x then v, change the character at the position (x,y) in the program to the character with ASCII value v
  dw DoPut
  db 'g' ; A "get" call (a way to retrieve data in storage). Pop y then x, push ASCII value of the character at that position in the program
  dw DoGet
  db '&' ; Input an integer (may be multiple characters and may be negative) and push it
  dw DoInput
  db '~' ; Input a single character from stdin and push its ASCII value
  dw DoInputAscii
  db '@' ; End program
  dw DoExit
  db ' ' ; NOP
  dw UpdatePC
  db 0 ; NOP
  dw UpdatePC
  db 255

StrNoFile:
  db "1$";"No File$"
StrBadFile:
  db "2$";"Bad File$"
StrBadRead:
  db "3$";"Bad Read$"
StrEmptyFile:
  db "4$";"Empty File$"
StrEndSearch:
  db "5$";"Bad Instruction$"
EOP:
</code>```

ContentLicense: CC BY-SA 2.5

Title: Interpret Befunge-93

Body:
16bit MSDOS .COM File - 1104 bytes

This is Base64 encoded (decoder here), save decoded file as a .com and execute from command line with name of program file to run as the only argument. Tested in WinXP command prompt.

yEAAADP/jNiAxBCJRv6JRvKAxBCJfuqJRuyJfvqJfviJfvSAxBCJRvbHRuiMAo7AM8C5AIDzq7Qs
zSGJVvC6RgWKHoAAMv+A6wF9Cei3ALQJzSHJw8aHggAAuAA9uoIAzSG6SAVy5YvYjkb+uQCAM8Dz
q7kBALpQBbQ/zSG6SgVyygvAdCWgUAU8CnQHPCBy4qrr34vHOkb5cgOIRvn+RviB5wD/gccAAevI
tD7NIQv/ukwFdJa4AwDNEDPb6FQAtAfNITxxdDk8cnQhPDF0DTwydBE8c3Xo6I8A6+CLRvaJRvLr
2ItG/olG8uvQi0b2iUby6B4A6HEAgH76AHTu67zoAgDJw7gAuI7AuCAHuQCA86vDYB6OXvK4ALiO
wLUZM/8z9rQHsVCsq/7JdfqBxrAA/s118FOLRvI7Rv6yz3QFi170svCA+1BzG4D/GXMWise0oPbk
ANiA1AAA2IDUAIv4R4rCqlsfYcOORv4migc8MHJVPDl3UbQALDDoKwD/ZugK23UDil75/svD/sM6
Xvl1+DLbwwr/dQOKfvj+z8P+xzp++HX4Mv/DBsR+6quJfuoHwwbEfuozwAv/dAmD7wImiwWJfuoH
w77uBIPGA4A8/3QOOAR19ItEAQvAdAP/4MO6TgXpZP7olP8migc8InSNtADos//r7+i4/4nB67To
9v8Dwel0/+ju/yvB6Wz/6Ob/9+npZP/o3v+Z9/npW//o1f+Z9/mLwulQ/+iF/wvAuAEAdAFI6UL/
6Lz/O8G4AQB/AUjpNP/HRuiMAukv/+hh/wvAdPHHRuiCAukg/+hS/wvAdAjHRuiWAukR/8dG6KAC
6Qn/i0bwuk189+IFGTaJRvAkBgWSA4vwrYlG6Ont/pYCoAKCAowC6Bf/6Ar/6dn+6FP/kegA/4nI
6c3+6AL/6cr+6Pz+C8B5CffYULAt6CYAWFO7UAUz0rkKAPfxgMIwiBdDC8B170uKB+gKAIH7UAV1
9Fvplf48CnQUBsR+9KqLxzxQdQSBx7AAiX70B8PGRvQA/kb1w+in/uja/+ls/uhp/ulm/ugOAOiV
/gaORv4miAQH6VX+6If+ik74C8B5BwLBgNQA6/X28YjhtQDocP5Rik75C8B5BwLBgNQA6/X28Yjg
WYjMi/DD6Mr/Bo5G/iaKBAe0AOkP/v928otG9olG8jP2Msnol/20B80hPC11CwrJdfH+wehc/+vq
PA11Do9G8ovGCsl0AvfY6dr9iMUsMDwJd9C0AFCwCvfmC9JadcT2xIB1vwHC9saAdbiJ1ojo6CH/
66//dvKLRvaJRvLoPf20B80hPCBy+FDoB/9YtACPRvLpkP3GRvoBwysAAy0IAyoQAy8YAyUhAyEs
A2A6Az5IAzxXA15mA3ZuAz92A19QA3xfAyLoAjqaA1yjAySvAy61AywKBCMTBHAZBGddBCZtBH7L
BEDsBCB/AgB/Av8xJDIkMyQ0JDUk

On startup, the display shows the program. Commands are:

r - runs the program (switches to output screen)

s - single steps the program

q - quits the interpreter

1 - shows output screen (white cursor is current output position)

2 - shows program screen (red cursors is current program position)

When an input command is executed, the display switches to the output screen. Input is echoed to the output screen. For ascii input, only characters in the range 32-255 are accepted. For numeric input, only values in the range -32768 to 32767 are allowed, press enter to complete input (sorry, no backspace).

I really should add a stack screen as well.

Update

Here's the original assembly source code, assembled using A86. It's quite long:

  enter 64,0
  xor di,di
  mov ax,ds
  add ah,10h
  mov [bp-2],ax   ; program
  mov [bp-14],ax  ; current display
  add ah,10h
  mov w[bp-22],di ; stack off
  mov [bp-20],ax  ; stack seg
  mov w[bp-6],di  ; exit status
  mov w[bp-8],di  ; size of field -8=lines,-7=columns
  mov w[bp-12],di ; output window position
  add ah,10h
  mov w[bp-10],ax; output segment
  mov w[bp-24],MoveRight

  ; clear output
  mov es,ax
  xor ax,ax
  mov cx,8000h
  rep stosw

  ; random seed
  mov ah,2ch
  int 21h
  mov w[bp-16],dx

  ; get filename
  mov dx,StrNoFile
  mov bl,[80h]
  xor bh,bh
  sub bl,1
  jge NoError

Error:
  call ClearScreen
  mov ah,9
  int 21h
  leave
  ret

NoError:
  ; open file
  mov b[82h+bx],0
  mov ax,3d00h
  mov dx,82h
  int 21h
  mov dx,StrBadFile
  jc Error
  mov bx,ax
  ; clear program
  mov es,[bp-2]
  mov cx,8000h
  xor ax,ax
  rep stosw
  ; read file
ReadLoop:
  mov cx,1
  mov dx,EOP
  mov ah,3fh
  int 21h
  mov dx,StrBadRead
  jc Error
  or ax,ax
  jz EOF
  mov al,b[EOP]
  cmp al,10
  je EOL
  cmp al,32
  jb ReadLoop
  stosb
  jmp ReadLoop
EOL:
  mov ax,di
  cmp al,[bp-7]
  jb l9
  mov [bp-7],al
l9:
  inc b[bp-8]
  and di,0ff00h
  add di,100h
  jmp ReadLoop
EOF:
  mov ah,3eh
  int 21h
  or di,di
  mov dx,StrEmptyFile
  jz Error
  ; initialise
  mov ax,3
  int 10h
  xor bx,bx ; PC
  ; execute
Redraw:
  call DisplayProgram
WaitForInput:
  mov ah,7
  int 21h
  cmp al,'q'
  je Quit
  cmp al,'r'
  je DoRun
  cmp al,'1'
  je ShowIO
  cmp al,'2'
  je ShowProgram
  cmp al,'s'
  jne WaitForInput
  ; single step
  call Execute
  jmp Redraw

ShowIO:
  mov ax,[bp-10]
  mov [bp-14],ax
  jmp Redraw

ShowProgram:
  mov ax,[bp-2]
  mov [bp-14],ax
  jmp Redraw

DoRun:
  mov ax,[bp-10]
  mov [bp-14],ax
  call DisplayProgram
  call Execute
  cmp b[bp-6],0
  je DoRun
  jmp Redraw

Quit:
  call ClearScreen
  leave
  ret

ClearScreen:
  mov ax,0b800h
  mov es,ax
  mov ax,720h
  mov cx,8000h
  rep stosw
  ret

DisplayProgram:
  pusha
  push ds
  mov ds,[bp-14]
  mov ax,0b800h
  mov es,ax
  mov ch,25
  xor di,di
  xor si,si
  mov ah,7
l1:
  mov cl,80
l2:
  lodsb
  stosw
  dec cl
  jnz l2
  add si,256-80
  dec ch
  jnz l1
  push bx
  mov ax,[bp-14]
  cmp ax,[bp-2]
  mov dl,0cfh
  je l33
  mov bx,[bp-12]
  mov dl,0f0h
l33:
  cmp bl,80
  jae l3
  cmp bh,25
  jae l3
  mov al,bh
  mov ah,160
  mul ah
  add al,bl
  adc ah,0
  add al,bl
  adc ah,0
  mov di,ax
  inc di
  mov al,dl
  stosb
l3:
  pop bx
  pop ds
  popa
  ret

Execute:
  mov es,[bp-2]
  mov al,es:[bx]

  cmp al,'0'
  jb NotPush
  cmp al,'9'
  ja NotPush

  ; push number
  mov ah,0
  sub al,'0'
PushValueUpdatePC:
  call PushValue
UpdatePC:
  jmp [bp-24]

MoveLeft:
  or bl,bl
  jnz MoveLeftNoWrap
  mov bl,[bp-7]
MoveLeftNoWrap:
  dec bl
  ret

MoveRight:
  inc bl
  cmp bl,[bp-7]
  jne ret
  xor bl,bl
  ret

MoveUp:
  or bh,bh
  jnz MoveUpNoWrap
  mov bh,[bp-8]
MoveUpNoWrap:
  dec bh
  ret

MoveDown:
  inc bh
  cmp bh,[bp-8]
  jne ret
  xor bh,bh
  ret

PushValue:
  push es
  les di,[bp-22]
  stosw
  mov [bp-22],di
  pop es
  ret

PopValue:
  push es
  les di,[bp-22]
  xor ax,ax
  or di,di
  jz PopValueZero
  sub di,2
  mov ax,es:[di]
  mov [bp-22],di
PopValueZero:
  pop es
  ret

NotPush:
  mov si,Functions-3
NextFunction:
  add si,3
FindFunction:
  cmp b[si],255
  je Endsearch
  cmp b[si],al
  jne NextFunction
  mov ax,[si+1]
  or ax,ax
  je EndSearch
  jmp ax
  ret

EndSearch:
  mov dx,StrEndSearch
  jmp Error

DoStringMode:
  call UpdatePC
  mov al,es:[bx]
  cmp al,'"'
  je UpdatePC
  mov ah,0
  call PushValue
  jmp DoStringMode

PopTwoValues:
  call PopValue
  mov cx,ax
  jmp PopValue

DoAdd:
  call PopTwoValues
  add ax,cx
  jmp PushValueUpdatePC

DoSub:
  call PopTwoValues
  sub ax,cx
  jmp PushValueUpdatePC

DoMultiply:
  call PopTwoValues
  imul cx
  jmp PushValueUpdatePC

DoDivide:
  call PopTwoValues
  cwd
  idiv cx
  jmp PushValueUpdatePC

DoModulo:
  call PopTwoValues
  cwd
  idiv cx
  mov ax,dx
  jmp PushValueUpdatePC

DoNot:
  call PopValue
  or ax,ax
  mov ax,1
  jz DoNotZero
  dec ax
DoNotZero:
  jmp PushValueUpdatePC

DoGreaterThan:
  call PopTwoValues
  cmp ax,cx
  mov ax,1
  jg DoGreaterThanIs1
  dec ax
DoGreaterThanIs1:
  jmp PushValueUpdatePC

DoMoveRight:
  mov [bp-24],MoveRight
  jmp UpdatePC

DoLeftRight:
  call PopValue
  or ax,ax
  jz DoMoveRight

DoMoveLeft:
  mov [bp-24],MoveLeft
  jmp UpdatePC

DoMoveUpDown:
  call PopValue
  or ax,ax
  jz DoMoveDown

DoMoveUp:
  mov [bp-24],MoveUp
  jmp UpdatePC

DoMoveDown:
  mov [bp-24],MoveDown
  jmp UpdatePC

DoRandomDirection:
  mov ax,[bp-16]
  mov dx,31821
  mul dx
  add ax,13849
  mov [bp-16],ax
  and al,6
  add ax,Movements
  mov si,ax
  lodsw
  mov [bp-24],ax
  jmp UpdatePC

Movements:
  dw MoveUp, MoveDown, MoveLeft, MoveRight

DoDuplicate:
  call PopValue
  call PushValue
  jmp PushValueUpdatePC

DoSwap:
  call PopTwoValues
  xchg ax,cx
  call PushValue
  mov ax,cx
  jmp PushValueUpdatePC

DoPop:
  call PopValue
  jmp UpdatePC

DoPopPrint:
  call PopValue
  or ax,ax
  jns Positive
  neg ax
  push ax
  mov al,'-'
  call PrintChar
  pop ax
Positive:
  push bx
  mov bx,EOP
DivLoop:
  xor dx,dx
  mov cx,10
  div cx
  add dl,'0'
  mov [bx],dl
  inc bx
  or ax,ax
  jnz DivLoop
PrintLoop:
  dec bx
  mov al,[bx]
  call PrintChar
  cmp bx,EOP
  jne PrintLoop
  pop bx
  jmp UpdatePC

PrintChar:
  cmp al,10
  je AsciiCR
  push es
  les di,[bp-12]
  stosb
  mov ax,di
  cmp al,80
  jne NoLF
  add di,256-80
NoLF:
  mov [bp-12],di
  pop es
  ret
AsciiCR:
  mov b[bp-12],0
  inc b[bp-11]
  ret

DoPopAsciiPrint:
  call PopValue
  call PrintChar
  jmp UpdatePC

DoTrampoline:
  call UpdatePC
  jmp UpdatePC

DoPut:
  call GetCoord
  call PopValue
  push es
  mov es,[bp-2]
  mov es:[si],al
  pop es
  jmp UpdatePC

GetCoord:
  call PopValue
  mov cl,[bp-8]
DoGet1:
  or ax,ax
  jns DecrementY
  add al,cl
  adc ah,0
  jmp DoGet1
DecrementY:
  div cl
  mov cl,ah
  mov ch,0
  call PopValue ; x
  push cx
  mov cl,[bp-7]
DoGet2:
  or ax,ax
  jns DecrementX
  add al,cl
  adc ah,0
  jmp DoGet2
DecrementX:
  div cl
  mov al,ah
  pop cx ; ax=x, cx=y
  mov ah,cl
  mov si,ax
  ret

DoGet:
  call GetCoord
  push es
  mov es,[bp-2]
  mov al,es:[si]
  pop es
  mov ah,0
  jmp PushValueUpdatePC

DoInput:
  push [bp-14]
  mov ax,[bp-10]
  mov [bp-14],ax
  xor si,si
  xor cl,cl
DoInput1:
  call DisplayProgram
  mov ah,7
  int 21h
  cmp al,'-'
  jne DoInputEnter
  or cl,cl
  jnz DoInput1
  inc cl
  call PrintChar
  jmp DoInput1

DoInputEnter:
  cmp al,13
  jnz DoInputDigit

  pop [bp-14]
  mov ax,si
  or cl,cl
  jz DoInput3
  neg ax
DoInput3:
  jmp PushValueUpdatePC

DoInputDigit:
  mov ch,al
  sub al,'0'
  cmp al,9
  ja DoInput1
  mov ah,0
  push ax
  mov al,10
  mul si
  or dx,dx
  pop dx
  jnz DoInput1
  test ah,80h
  jnz DoInput1
  add dx,ax
  test dh,80h
  jnz DoInput1
  mov si,dx
  mov al,ch
  call PrintChar
  jmp DoInput1

DoInputAscii:
  push [bp-14]
  mov ax,[bp-10]
  mov [bp-14],ax
  call DisplayProgram
DoInputAscii1:
  mov ah,7
  int 21h
  cmp al,32
  jb DoInputAscii1
  push ax
  call PrintChar
  pop ax
  mov ah,0
  pop [bp-14]
  jmp PushValueUpdatePC

DoExit:
  mov b[bp-6],1
  ret

Functions:
  db '+' ; Addition: Pop a then b, push a+b
  dw DoAdd
  db '-' ; Subtraction: Pop a then b, push b-a
  dw DoSub
  db '*' ; Multiplication: Pop a then b, push a*b
  dw DoMultiply
  db '/' ; Integer division: Pop a then b, push b/a, rounded down. If a is 0, result is undefined
  dw DoDivide
  db '%' ; Modulo: Pop a then b, push the remainder of the integer division of b/a. If a is 0, result is undefined
  dw DoModulo
  db '!' ; Logical NOT: Pop a value. If the value is 0, push 1; otherwise, push 0.
  dw DoNot
  db '`' ; Greater than: Pop a then b, push 1 if b>a, otherwise 0.
  dw DoGreaterThan
  db '>' ; Start moving right
  dw DoMoveRight
  db '<' ; Start moving left
  dw DoMoveLeft
  db '^' ; Start moving up
  dw DoMoveUp
  db 'v' ; Start moving down
  dw DoMoveDown
  db '?' ; Start moving in a random cardinal direction
  dw DoRandomDirection
  db '_' ; Pop a value; move right if value=0, left otherwise
  dw DoLeftRight
  db '|' ; Pop a value; move down if value=0, up otherwise
  dw DoMoveUpDown
  db '"' ; Start string mode: push each character's ASCII value all the way up to the next "
  dw DoStringMode
  db ':' ; Duplicate value on top of the stack
  dw DoDuplicate
  db '\' ; Swap two values on top of the stack
  dw DoSwap
  db '$' ; Pop value from the stack
  dw DoPop
  db '.' ; Pop value and output as an integer
  dw DoPopPrint
  db ',' ; Pop value and output as ASCII character
  dw DoPopAsciiPrint
  db '#' ; Trampoline: Skip next cell
  dw DoTrampoline
  db 'p' ; A "put" call (a way to store a value for later use). Pop y then x then v, change the character at the position (x,y) in the program to the character with ASCII value v
  dw DoPut
  db 'g' ; A "get" call (a way to retrieve data in storage). Pop y then x, push ASCII value of the character at that position in the program
  dw DoGet
  db '&' ; Input an integer (may be multiple characters and may be negative) and push it
  dw DoInput
  db '~' ; Input a single character from stdin and push its ASCII value
  dw DoInputAscii
  db '@' ; End program
  dw DoExit
  db ' ' ; NOP
  dw UpdatePC
  db 0 ; NOP
  dw UpdatePC
  db 255

StrNoFile:
  db "1$";"No File$"
StrBadFile:
  db "2$";"Bad File$"
StrBadRead:
  db "3$";"Bad Read$"
StrEmptyFile:
  db "4$";"Empty File$"
StrEndSearch:
  db "5$";"Bad Instruction$"
EOP:


答:
MATL, <s>11</s> 9 bytes

No one seems to have used brute force up to now, so here it is.

```<code>ts:\a~f0)
</code>```

Input is a column array with the two numbers (using ; as separator).

Try it online! or verify all test cases.

Explanation

```<code>t     % Take input [a;b] implicitly. Duplicate
s     % Sum. Gives a+b
:     % Array [1,2,...,a+b]
\     % Modulo operation with broadcast. Gives a 2×(a+b) array
a~    % 1×(a+b) array that contains true if the two modulo operations gave 0
f0)   % Index of last true value. Implicitly display
</code>```

Title: Greatest Common Divisor

Body:
MATL, <s>11</s> 9 bytes

No one seems to have used brute force up to now, so here it is.

ts:\a~f0)

Input is a column array with the two numbers (using ; as separator).

Try it online! or verify all test cases.

Explanation

t     % Take input [a;b] implicitly. Duplicate
s     % Sum. Gives a+b
:     % Array [1,2,...,a+b]
\     % Modulo operation with broadcast. Gives a 2×(a+b) array
a~    % 1×(a+b) array that contains true if the two modulo operations gave 0
f0)   % Index of last true value. Implicitly display


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

```<code>?v%uII/;O@
</code>```

Try it here

This wraps onto the cube as follows:

```<code>    ? v
    % u
I I / ; O @ . .
. . . . . . . .
    . .
    . .
</code>```

Uses the Euclidean Method.

II Two numbers are grabbed from STDIN and put on the stack

/ Flow reflected up

% Mod the Top of Stack.  Remainder left on top of stack

? If TOS 0 then carry on, otherwise turn right

v If not 0 then redirect down and u turn right twice back onto the mod

/ If 0 go around the cube to the reflector

; drop TOS, O output TOS and @ end

Title: Greatest Common Divisor

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

?v%uII/;O@

Try it here

This wraps onto the cube as follows:

    ? v
    % u
I I / ; O @ . .
. . . . . . . .
    . .
    . .

Uses the Euclidean Method.

II Two numbers are grabbed from STDIN and put on the stack

/ Flow reflected up

% Mod the Top of Stack.  Remainder left on top of stack

? If TOS 0 then carry on, otherwise turn right

v If not 0 then redirect down and u turn right twice back onto the mod

/ If 0 go around the cube to the reflector

; drop TOS, O output TOS and @ end


问:
Simulate Cookie Clicker

Intro

Cookie Clicker is a popular browser game in which the player has to click a cookie to gain... Cookies!

The player can buy upgrades which will automatically farm cookies for you. Sometimes a golden cookie will enter the screen, which will provide a bonus upon clicking it.

Challenge

This challenge will not be about clicking a cookie. It will be about automating the cookie.

The player starts off with 0 cookies, and will gain cookies on every game tick. The goal of the challenge is to calculate the amount of ticks it takes to reach a certain amount of cookies.

Input

Your program or function will have 2 input parameters.

The first parameter is the goal, which is simply the amount of cookies you need to finish.

The second parameter is a list of upgrades the player can buy. The format of the list will be explained in further detail in the paragraph Upgrades - List format.

For sake of convenience, you may assume that the input is always in the correct format. You don't have to deal with bad input.

Output

Your program or function should print or return the amount of ticks it takes before the player has reached the goal amount of cookies.

Upgrades

Every game-tick will earn the player some cookies. These are based on the upgrades of the player. If a player has no upgrades, the cookie production will be 1 cookie per tick. Once the player reaches enough cookies to buy an upgrade, he will automatically purchase it (before the next tick happens).

When the player has enough cookies after a tick to buy multiple upgrades, he will attempt to buy all possible upgrades, starting with the cheapest.

List format

[[100, '+', 1],[1000, '*', 2],[10000, '*', 10]

This is an unordered list which contains 3 upgrades. The first parameter of an upgrade is the price of the upgrade. The second parameter is the effect of the upgrade and the third parameter is the effect amount.

The input list will contain no upgrades with the same price.

The only possible effects are + (addition) and * (multiplication).

[100, '+', 1] means that the cookie production will increase by 1 at a cost of 100 cookies.

Golden cookies

Every 1000 ticks, the player will find a golden cookie. When this happens, the player will receive a bonus of 10% (rounded down) of his cookie amount. If the player has 1000 cookies at tick 1000, he will have 1100 cookies before tick 1001 happens.

Order of events

After every tick a couple of actions can occur.

If the player has enough cookies, end the game

If the player has enough cookies, purchase upgrades

If the amount of ticks is a multiple of 1000; Golden cookie

Example input + output

```<code>(0    , [])                              -> 0
(100  , [])                              -> 100
(1    , [[10, '+', 1]])                  -> 1
(10   , [[10, '+', 1]])                  -> 10
(1000 , [[100, '*', 2], [10, '+', 1]])   -> 310
(10000, [[10, '+', 1], [100, '*', 2]])   -> 2263
</code>```

Detailed example

```<code>(1000 , [[100, '*', 2], [10, '+', 1]])   -> 310

ticks: 8, cookies: 8, production: 1
ticks: 9, cookies: 9, production: 1
ticks: 10, cookies: 0, production: 2
ticks: 11, cookies: 2, production: 2
ticks: 58, cookies: 96, production: 2
ticks: 59, cookies: 98, production: 2
ticks: 60, cookies: 0, production: 4
ticks: 61, cookies: 4, production: 4
ticks: 70, cookies: 40, production: 4
ticks: 80, cookies: 80, production: 4
ticks: 260, cookies: 800, production: 4
ticks: 280, cookies: 880, production: 4
ticks: 300, cookies: 960, production: 4
ticks: 309, cookies: 996, production: 4
ticks: 310, cookies: 1000, production: 4 -- done
</code>```

Disclaimer

I will not be held responsible for any addictions caused by this challenge.

Happy golfing!

答:
CJam, 66

```<code>q~1$aa+$0{_W$<{{_2$0=0=<!}{\(~X@~:X;@\-}wT):T1e3%{_A/+}|X+}0?}h];T
</code>```

Try it online

Explanation:

```<code>q~            read and evaluate the input (the goal and the array of upgrades)
1$aa+         append a dummy upgrade with the cost equal to the goal
               (to avoid the array becoming empty)
$             sort the upgrades lexicographically (so first by cost)
0             push 0, the initial number of cookies
{…}h          do-while loop, checking the last value as the condition
  _W$<        duplicate the number of cookies and check if it's smaller
               than the goal (at the bottom of the stack)
  {…}         if true… ("<condition><then part><else part>?" is an if statement)
    {…}       while… ("{condition}{block}w" is a while loop)
      _2$     duplicate the number of cookies and the array of upgrades
      0=0=    get the cost (first item) of the first upgrade
      <!      check if the number of cookies is not smaller than it
    {…}       do…
      \(      bring the array of upgrades to the top and take out the first upgrade
      ~       dump the price, effect (operator) and amount onto the stack
      X@      push X (cookie production) and bring the operator to the top
      ~:X;    evaluate the operator and store the result back in X
      @\-     subtract the price from the number of cookies
    w         (end) while
    T):T      increment T (the number of ticks, initially 0)
    1e3%      calculate T % 1000
    {…}|      if false (0) then…
      _A/+    add cookies/10 to the number of cookies (A=10)
    X+        add X (cookie production, initially 1) to the number of cookies
               to go to the next step
               since the result is not 0, the do-while loop continues
  0           else (if we reached the goal) push 0 to exit the loop
  ?           (end) if
];            pop everything left on the stack after the do-while loop
T             push T, the final number of ticks
</code>```

Title: Simulate Cookie Clicker

Body:
CJam, 66

q~1$aa+$0{_W$<{{_2$0=0=<!}{\(~X@~:X;@\-}wT):T1e3%{_A/+}|X+}0?}h];T

Try it online

Explanation:

q~            read and evaluate the input (the goal and the array of upgrades)
1$aa+         append a dummy upgrade with the cost equal to the goal
               (to avoid the array becoming empty)
$             sort the upgrades lexicographically (so first by cost)
0             push 0, the initial number of cookies
{…}h          do-while loop, checking the last value as the condition
  _W$<        duplicate the number of cookies and check if it's smaller
               than the goal (at the bottom of the stack)
  {…}         if true… ("<condition><then part><else part>?" is an if statement)
    {…}       while… ("{condition}{block}w" is a while loop)
      _2$     duplicate the number of cookies and the array of upgrades
      0=0=    get the cost (first item) of the first upgrade
      <!      check if the number of cookies is not smaller than it
    {…}       do…
      \(      bring the array of upgrades to the top and take out the first upgrade
      ~       dump the price, effect (operator) and amount onto the stack
      X@      push X (cookie production) and bring the operator to the top
      ~:X;    evaluate the operator and store the result back in X
      @\-     subtract the price from the number of cookies
    w         (end) while
    T):T      increment T (the number of ticks, initially 0)
    1e3%      calculate T % 1000
    {…}|      if false (0) then…
      _A/+    add cookies/10 to the number of cookies (A=10)
    X+        add X (cookie production, initially 1) to the number of cookies
               to go to the next step
               since the result is not 0, the do-while loop continues
  0           else (if we reached the goal) push 0 to exit the loop
  ?           (end) if
];            pop everything left on the stack after the do-while loop
T             push T, the final number of ticks


答:
Javascript, 42 bytes

```<code>n=(x,y)=>{for(k=x;x%k+y%k>0;k--);alert(k)}
</code>```

I could get it down to ~32 with Grond, but whatever

Title: Greatest Common Divisor

Body:
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

Body:
Javascript, 42 bytes

n=(x,y)=>{for(k=x;x%k+y%k>0;k--);alert(k)}

I could get it down to ~32 with Grond, but whatever