问:
Print a Lego piece
This challenge is a simple ascii-art one. Given two inputs, describing the height and width of a Lego piece, you have print an ASCII art representation of it.

Here is how the Lego pieces are supposed to look:

```<code>(4, 2)

___________
| o o o o |
| o o o o |
-----------

(8, 2)

___________________
| o o o o o o o o |
| o o o o o o o o |
-------------------

(4, 4)

___________
| o o o o |
| o o o o |
| o o o o |
| o o o o |
-----------

(3, 2)

_________
| o o o |
| o o o |
---------

(1, 1)

o
</code>```

If you can't tell from the test-cases, the top and bottom are width*2+3 underscores and dashes, and each row has pipes for the sides, o's for the little things, and everything is separated by spaces.

The only exception for this is (1, 1), which is just a single o.

You will never get 0 for any of the dimensions.

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
C#, 198 bytes

```<code>void f(int x,int y){int l=x*2+3;Console.Write(y==x&&x==1?"o":s("_",l)+"\n"+s("|"+s(" o",x)+" |\n",y)+s("-",l));}string s(string m,int u){return string.Join("",new string[u].Select(n=>m).ToArray());}
</code>```

quick and dirty

I had to write a function that multiplies strings

ungolfed (for suggestions)

```<code>public static void f(int x,int y)
{
    int l=x*2+3;
    Console.Write(y == x && x == 1 ? "o" : s("_",l)+"\n"+ s("|" + s(" o", x) + " |\n", y) + s("-",l));

}
public static string s(string m,int u)
{
    return string.Join("", new string[u].Select(n => m).ToArray());
}
</code>```

Title: Print a Lego piece

Body:
C#, 198 bytes

void f(int x,int y){int l=x*2+3;Console.Write(y==x&&x==1?"o":s("_",l)+"\n"+s("|"+s(" o",x)+" |\n",y)+s("-",l));}string s(string m,int u){return string.Join("",new string[u].Select(n=>m).ToArray());}

quick and dirty

I had to write a function that multiplies strings

ungolfed (for suggestions)

public static void f(int x,int y)
{
    int l=x*2+3;
    Console.Write(y == x && x == 1 ? "o" : s("_",l)+"\n"+ s("|" + s(" o", x) + " |\n", y) + s("-",l));

}
public static string s(string m,int u)
{
    return string.Join("", new string[u].Select(n => m).ToArray());
}


问:
Can Pac-Man Eat This String?
In the arcade version of the game, Pac-Man eats pac-dots. However, in this challenge, he's hungry for alphanumeric characters and punctuation in a string.

Your task is to create a function that feeds Pac-Man a string, evaluates if he can eat it or not, and returns the string with Pac-Man's location in it.

Pac-Man (<) eats characters from left to right, leaving an underscore or space for each character as he goes, and his goal is to get from the first position-1 to the last position+1:

```<code>1. <Pac
2. _<ac
3. __<c
4. ___<
</code>```

However, Pac-Man's natural enemy, the ghost, will stop him if he encounters one of the letters in the word "GHOST" (not case sensitive). Your function should return the string with Pac-Man's location as he encounters the ghost character:

```<code>1. <No!
2. _<o!
</code>```

The only thing that can defeat a ghost is a power pellet. If Pac-Man reaches a letter in the word "PELLET" (also not case sensitive) before coming to a ghost, he will eat the ghost and keep moving, and that pellet will be used up. Power pellets can stack (ie, in ppgg both ghosts would be eaten). The T character exists as both as a ghost and a pellet, so it can be ignored (treated as any other letter, like a).

```<code>1. <Pop
2. _<op
3. __<p
4. ___<
</code>```

To further clarify, in the string "Pac-Man loses here", the following operations occur:

```<code>P <P, +1 Pellet (1 pellet)
a <a
c <c
- <-
M <M
a <a
n <n
  <[space]
l <l, +1 Pellet (2 pellets)
o <o, -1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
e <e, +1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
  <[space]
h <h, ghost wins, returns
e
r
e
</code>```

Examples

```<code>Input: Pacman wins!
Output: ____________<

Input: Pacman loses wah-wah :(
Output: _______________<h-wah :(

Input: PELLET PELLET GHOST
Output: ___________________<

Input: Hello World!
Output: <Hello World!

Input: <_!@12<_<_<
Output: ___________<
</code>```

This is code-golf--lowest score in bytes wins.

答:
C#, <s>269</s> <s>256</s> <s>232</s> <s>212</s> 211 Bytes

First ever post on here, so this is probably a lot longer than it could be (and probably because it is in C#). Any tips on where I could shorten it would be great!

Thank you to everyone in the comments who helped me!

Golfed version

```<code>static void p(string x){int p=0,i=0;string t='<'+x;var s=t.ToCharArray();for(;++i<s.Length;){if("PELpel".Contains(s[i]))p++;if("GHOSghos".Contains(s[i])&&--p<0)break;s[i]='<';if(i>0)s[i-1]='_';}Console.Write(s);}
</code>```

Ungolfed version

```<code>static void p(string x) {
 int p = 0, i = 0;
 string t = '<' + x;
 var s = t.ToCharArray();
 for (; ++i < s.Length;) {
  if ("PELpel".Contains(s[i])) p++;
  if ("GHOSghos".Contains(s[i]) && --p < 0) break;
  s[i] = '<';
  if (i > 0) s[i - 1] = '_';
 }
 Console.Write(s);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Can Pac-Man Eat This String?

Body:
C#, <s>269</s> <s>256</s> <s>232</s> <s>212</s> 211 Bytes

First ever post on here, so this is probably a lot longer than it could be (and probably because it is in C#). Any tips on where I could shorten it would be great!

Thank you to everyone in the comments who helped me!

Golfed version

static void p(string x){int p=0,i=0;string t='<'+x;var s=t.ToCharArray();for(;++i<s.Length;){if("PELpel".Contains(s[i]))p++;if("GHOSghos".Contains(s[i])&&--p<0)break;s[i]='<';if(i>0)s[i-1]='_';}Console.Write(s);}

Ungolfed version

static void p(string x) {
 int p = 0, i = 0;
 string t = '<' + x;
 var s = t.ToCharArray();
 for (; ++i < s.Length;) {
  if ("PELpel".Contains(s[i])) p++;
  if ("GHOSghos".Contains(s[i]) && --p < 0) break;
  s[i] = '<';
  if (i > 0) s[i - 1] = '_';
 }
 Console.Write(s);
}


问:
Reverse and subtract

Challenge description

Let's take a positive integer n, reverse its digits to get rev(n) and get the absolute value of the difference of these two numbers: |n - rev(n)| (or abs(n - rev(n))).

Example:

```<code>n = 5067
rev(n) = 7605
|n - rev(n)| = |5067 - 7605| = |-2538| = 2538
</code>```

After repeating this operation sufficiently many times, most numbers will become 0 (thus terminating the loop)...

```<code>5067 -> 2538 -> 5814 -> 1629 -> 7632 -> 5265 -> 360 -> 297 -> 495 -> 99 -> 0
</code>```

...though some numbers (like 1584) get stuck in an infinite loop:

```<code>1584 -> 3267 -> 4356 -> 2178 -> 6534 -> 2178 -> 6534 -> 2178 -> 6534 -> ...
                        ^ infinite loop starts here
</code>```

Your job is to determine if a given integer gets stuck in an infinite loop.

Input description

A positive integer.

Output description

A truthy value (True, 1) if the number gets stuck in an infinite loop, a falsy value (False, 0) otherwise.

Notes

Trailing zeroes should be ommited. i.e. rev(5020) = 205.

Remember that this is code-golf, so make your code as short as possible!

Relevant sequence: A072140

答:
PowerShell v2+, 94 bytes

```<code>param($n)for($a=,0;){if(($n=[math]::Abs($n-(-join"$n"["$n".length..0])))-in$a){$n;exit}$a+=$n}
</code>```

Takes input $n, starts an infinite for loop, with $a=,0 as the initial condition (this uses the comma operator to set $a to an array of one element, 0). This $a is our array of already-seen values.

Each loop iteration we check an if. The condition first sets the next value of $n using string-reversing and the [math]::Abs .NET call, and checks whether that value is already -in $a. If so, we output $n and exit. Otherwise, we add that value to the array and continue the loop.

Outputs 0 for input values where it does not go into an infinite loop (which is falsey in PowerShell) and outputs the value where the loop was encountered otherwise (non-zero integers are truthy). For example, outputs 2178 for input 1584.

Title: Reverse and subtract

Body:
PowerShell v2+, 94 bytes

param($n)for($a=,0;){if(($n=[math]::Abs($n-(-join"$n"["$n".length..0])))-in$a){$n;exit}$a+=$n}

Takes input $n, starts an infinite for loop, with $a=,0 as the initial condition (this uses the comma operator to set $a to an array of one element, 0). This $a is our array of already-seen values.

Each loop iteration we check an if. The condition first sets the next value of $n using string-reversing and the [math]::Abs .NET call, and checks whether that value is already -in $a. If so, we output $n and exit. Otherwise, we add that value to the array and continue the loop.

Outputs 0 for input values where it does not go into an infinite loop (which is falsey in PowerShell) and outputs the value where the loop was encountered otherwise (non-zero integers are truthy). For example, outputs 2178 for input 1584.


问:
Calculate the sum of ILD

Input:

An integer

Output:

Sum of the input itself + the length of the input + each individual digit of the input.

```<code>nr + nr-length + {sum of digits} = output
</code>```

Examples:

Input: 99

Output: 99 (nr) + 2 (nr-length) + (9 + 9) (digits) → 119

Input: 123

Output: 123 + 3 + (1 + 2 + 3) → 132

Challenge rules:

The input can also contain negative input, which are resolved special. The -/minus-sign is also +1 for the length, and is part of the first digit.

For example:

Input: -123

Output: -123 + 4 + (-1 + 2 + 3) → -115

You can assume that the input nor output will ever be outside the range of an (32-bit) integer.

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases:

```<code>87901 → 87931
123 → 132
99 → 119
5 → 11
1 → 3
0 → 1
-3 → -4
-123 → -115
-900 → -905
-87901 → -87886
</code>```

Semi-related: Count Sum of all Digits

答:
XSLT 1.0 (without EXSLT), 673 bytes

```<code><transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0"><output method="text"/><param name="i"/><template match="/"><variable name="d"><variable name="s">0<if test="0>$i">1</if></variable><variable name="d"><call-template name="d"><with-param name="i" select="substring($i,$s+2)"/></call-template></variable><value-of select="substring($i,1,$s+1)+$d"/></variable><value-of select="$i+string-length($i)+$d"/></template><template name="d"><param name="i"/>0<if test="$i!=''"><variable name="d"><call-template name="d"><with-param name="i" select="substring($i,2)"/></call-template></variable><value-of select="substring($i,1,1)+$d"/></if></template></transform>
</code>```

Lightly inflated:

```<code><transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <output method="text"/>
    <param name="i"/>
    <template match="/">
        <variable name="d">
            <variable name="s">0<if test="0>$i">1</if></variable>
            <variable name="d">
                <call-template name="d">
                    <with-param name="i" select="substring($i,$s+2)"/>
                </call-template>
            </variable>
            <value-of select="substring($i,1,$s+1)+$d"/>
        </variable>
        <value-of select="$i+string-length($i)+$d"/>
    </template>
    <template name="d">
        <param name="i"/>0<if test="$i!=''">
            <variable name="d">
                <call-template name="d">
                    <with-param name="i" select="substring($i,2)"/>
                </call-template>
            </variable>
            <value-of select="substring($i,1,1)+$d"/>
        </if>
    </template>
</transform>
</code>```

Run using xsltproc:

```<code>xsltproc --param i -87901 ild.xsl ild.xsl
</code>```

Yes, ild.xsl is passed twice: Once as the XSLT document and then as the XML document to be transformed. An input document must be present because an XSLT processor generally requires one to begin running. (XSLT is designed to define a transformation from an input document to an output document; running a transform solely with command-line parameters as I've done here is atypical.) For this program, any well-formed XML document will suffice as input, and, XSLT being an application of XML, any well-formed XSLT transform is by definition a well-formed XML document.

Title: Calculate the sum of ILD

Body:
XSLT 1.0 (without EXSLT), 673 bytes

<transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0"><output method="text"/><param name="i"/><template match="/"><variable name="d"><variable name="s">0<if test="0>$i">1</if></variable><variable name="d"><call-template name="d"><with-param name="i" select="substring($i,$s+2)"/></call-template></variable><value-of select="substring($i,1,$s+1)+$d"/></variable><value-of select="$i+string-length($i)+$d"/></template><template name="d"><param name="i"/>0<if test="$i!=''"><variable name="d"><call-template name="d"><with-param name="i" select="substring($i,2)"/></call-template></variable><value-of select="substring($i,1,1)+$d"/></if></template></transform>

Lightly inflated:

<transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <output method="text"/>
    <param name="i"/>
    <template match="/">
        <variable name="d">
            <variable name="s">0<if test="0&gt;$i">1</if></variable>
            <variable name="d">
                <call-template name="d">
                    <with-param name="i" select="substring($i,$s+2)"/>
                </call-template>
            </variable>
            <value-of select="substring($i,1,$s+1)+$d"/>
        </variable>
        <value-of select="$i+string-length($i)+$d"/>
    </template>
    <template name="d">
        <param name="i"/>0<if test="$i!=''">
            <variable name="d">
                <call-template name="d">
                    <with-param name="i" select="substring($i,2)"/>
                </call-template>
            </variable>
            <value-of select="substring($i,1,1)+$d"/>
        </if>
    </template>
</transform>

Run using xsltproc:

xsltproc --param i -87901 ild.xsl ild.xsl

Yes, ild.xsl is passed twice: Once as the XSLT document and then as the XML document to be transformed. An input document must be present because an XSLT processor generally requires one to begin running. (XSLT is designed to define a transformation from an input document to an output document; running a transform solely with command-line parameters as I've done here is atypical.) For this program, any well-formed XML document will suffice as input, and, XSLT being an application of XML, any well-formed XSLT transform is by definition a well-formed XML document.


答:
Retina, 52 bytes

Byte count assumes ISO 8859-1 encoding. Note that the sixth line is supposed to contain a single space.

```<code>\G1?
$_¶
1*

.+
|$&|
\G.
_
r`.\G
-
s`^.{17}$|1
o
</code>```

Try it online!

Input is in unary, using 1 as the unary digit, space as a separator and height followed by width.

Explanation

All stages in this program are bare substitutions, occasionally with a regular regex modifier (no repetition or loops, no other types of stages). It doesn't even use Retina-specific substitution features, apart from the usual ¶ alias for linefeeds.

```<code>\G1?
$_¶
</code>```

The purpose of this is to "multiply" the two inputs. Our goal is to create h+2 rows with w 1s each (h+2 so that we can turn the top and bottom into _ and - later). The \G anchor requires the match to start where the last one left off. That is, if we ever fail to match a character in the string, further characters won't match either. We use this to match only the 1s in h, but not in w because the regex doesn't allow the space that separates them to be matched. However, we also make the 1 optional, so that we get an additional empty match at the end of h. That's h+1 matches. Each of those is replaced with the entire input ($_) followed by a linefeed. w itself remains untouched which gives us the h+2nd copy. Say the input was 11 1111, then we've now got:

```<code>11 1111
11 1111
11 1111
 1111
</code>```

That's pretty good. We've got some extra stuff, but the h+2 copies of w are there.

```<code>1*

</code>```

Note that there's a space at the end of the first line. This removes those prefixes from the lines so that we only have the ws afterwards.

```<code>

</code>```

Ah well, that doesn't really work with SE's formatting... the first line is empty and the second line is supposed to contain a single space. This inserts spaces into every possible position, i.e. at the beginning and end of each line and between every pair of 1s:

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

We will turn these into os later

```<code>.+
|$&|
</code>```

This simply wraps every line in a pair of |:

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

Now we take care of the top and bottom:

```<code>\G.
_
</code>```

Time for \G to shine again. This matches each character on the first line and turns it into a _.

```<code>r`.\G
-
</code>```

Same thing, but due to the r modifier (right-to-left mode), this matches the characters on the last line and turns them into -. So now we've got:

```<code>\G1?
$_¶
</code>```0

There's only two things left to do now: turn those 1 into os, and if the input was 1 1 then turn the entire thing into o instead. We can handle both of those with a single stage:

```<code>\G1?
$_¶
</code>```1

s is regular singleline mode (i.e. it makes . match linefeeds). If the input was 1 1 the result will have the minimum size of 17 characters so we can match it with ^.{17}$ and replace it with o. Otherwise, if that fails, we'll just match all the 1s and replace those with o instead.

Title: Print a Lego piece

Body:
This challenge is a simple ascii-art one. Given two inputs, describing the height and width of a Lego piece, you have print an ASCII art representation of it.

Here is how the Lego pieces are supposed to look:

```<code>(4, 2)

___________
| o o o o |
| o o o o |
-----------

(8, 2)

___________________
| o o o o o o o o |
| o o o o o o o o |
-------------------

(4, 4)

___________
| o o o o |
| o o o o |
| o o o o |
| o o o o |
-----------

(3, 2)

_________
| o o o |
| o o o |
---------

(1, 1)

o
</code>```

If you can't tell from the test-cases, the top and bottom are width*2+3 underscores and dashes, and each row has pipes for the sides, o's for the little things, and everything is separated by spaces.

The only exception for this is (1, 1), which is just a single o.

You will never get 0 for any of the dimensions.

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Retina, 52 bytes

Byte count assumes ISO 8859-1 encoding. Note that the sixth line is supposed to contain a single space.

\G1?
$_¶
1*

.+
|$&|
\G.
_
r`.\G
-
s`^.{17}$|1
o

Try it online!

Input is in unary, using 1 as the unary digit, space as a separator and height followed by width.

Explanation

All stages in this program are bare substitutions, occasionally with a regular regex modifier (no repetition or loops, no other types of stages). It doesn't even use Retina-specific substitution features, apart from the usual ¶ alias for linefeeds.

\G1?
$_¶

The purpose of this is to "multiply" the two inputs. Our goal is to create h+2 rows with w 1s each (h+2 so that we can turn the top and bottom into _ and - later). The \G anchor requires the match to start where the last one left off. That is, if we ever fail to match a character in the string, further characters won't match either. We use this to match only the 1s in h, but not in w because the regex doesn't allow the space that separates them to be matched. However, we also make the 1 optional, so that we get an additional empty match at the end of h. That's h+1 matches. Each of those is replaced with the entire input ($_) followed by a linefeed. w itself remains untouched which gives us the h+2nd copy. Say the input was 11 1111, then we've now got:

11 1111
11 1111
11 1111
 1111

That's pretty good. We've got some extra stuff, but the h+2 copies of w are there.

1*

Note that there's a space at the end of the first line. This removes those prefixes from the lines so that we only have the ws afterwards.

Ah well, that doesn't really work with SE's formatting... the first line is empty and the second line is supposed to contain a single space. This inserts spaces into every possible position, i.e. at the beginning and end of each line and between every pair of 1s:

 1 1 1 1
 1 1 1 1
 1 1 1 1
 1 1 1 1

We will turn these into os later

.+
|$&|

This simply wraps every line in a pair of |:

| 1 1 1 1 |
| 1 1 1 1 |
| 1 1 1 1 |
| 1 1 1 1 |

Now we take care of the top and bottom:

\G.
_

Time for \G to shine again. This matches each character on the first line and turns it into a _.

r`.\G
-

Same thing, but due to the r modifier (right-to-left mode), this matches the characters on the last line and turns them into -. So now we've got:

___________
| 1 1 1 1 |
| 1 1 1 1 |
-----------

There's only two things left to do now: turn those 1 into os, and if the input was 1 1 then turn the entire thing into o instead. We can handle both of those with a single stage:

s`^.{17}$|1
o

s is regular singleline mode (i.e. it makes . match linefeeds). If the input was 1 1 the result will have the minimum size of 17 characters so we can match it with ^.{17}$ and replace it with o. Otherwise, if that fails, we'll just match all the 1s and replace those with o instead.


答:
Haskell, 65 bytes

```<code>_#0=0
a#n|elem n a=1|1<2=(n:a)#abs(n-(read$reverse$show n))
([]#)
</code>```

Returns 0 for False and 1 for True. Usage example: ([]#) 1584 -> 1.

The obvious approach: keep a list with all results seen so far. Calculate the next number until 0 or it's in the list.

Title: Reverse and subtract

Body:
Challenge description

Let's take a positive integer n, reverse its digits to get rev(n) and get the absolute value of the difference of these two numbers: |n - rev(n)| (or abs(n - rev(n))).

Example:

```<code>n = 5067
rev(n) = 7605
|n - rev(n)| = |5067 - 7605| = |-2538| = 2538
</code>```

After repeating this operation sufficiently many times, most numbers will become 0 (thus terminating the loop)...

```<code>5067 -> 2538 -> 5814 -> 1629 -> 7632 -> 5265 -> 360 -> 297 -> 495 -> 99 -> 0
</code>```

...though some numbers (like 1584) get stuck in an infinite loop:

```<code>1584 -> 3267 -> 4356 -> 2178 -> 6534 -> 2178 -> 6534 -> 2178 -> 6534 -> ...
                        ^ infinite loop starts here
</code>```

Your job is to determine if a given integer gets stuck in an infinite loop.

Input description

A positive integer.

Output description

A truthy value (True, 1) if the number gets stuck in an infinite loop, a falsy value (False, 0) otherwise.

Notes

Trailing zeroes should be ommited. i.e. rev(5020) = 205.

Remember that this is code-golf, so make your code as short as possible!

Relevant sequence: A072140

Body:
Haskell, 65 bytes

_#0=0
a#n|elem n a=1|1<2=(n:a)#abs(n-(read$reverse$show n))
([]#)

Returns 0 for False and 1 for True. Usage example: ([]#) 1584 -> 1.

The obvious approach: keep a list with all results seen so far. Calculate the next number until 0 or it's in the list.


Title: Print a Lego piece

Body:
brainfuck, 391 bytes

I know this can be golfed down more, but at this point I'm just glad it works. I will continue to work to golf it down.

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

Input needs to be given as just two digits. As in, to do (8, 2) you would just enter 82.

<a href="http://brainfuck.tryitonline.net/#code=KysrKytbLTwrKytbLTwrKys8KysrKysrPCsrKysrKys8Kys8KysrKysrKys-Pj4-Pl08PCs8Kzw8KzwrKz4-Pj4-Pj5dPDw8PCs8Kys8LT4-Pj4-Piw8LD4-KysrKysrWzwtLS0tLS0tLTwtLS0tLS0tLT4-LV08PC0-Pis8PFs-Pi08PFs-Pj4rPDw8LV1dPj4-Wzw8PCs-Pj4tXTxbPC0-Pj4rPDw8Wz4-Pi08PDxbPj4-Pis8PDw8LV1dPj4-Pls8PDw8Kz4-Pj4tXTxbPDw8PDw8PC5bLV0uXTw8PCs-LV08PCs-Wy0-Kys-Kzw8XT4rKytbLTw8PDwuPj4-Pl0-Wy08PCs-Pl08PDw8PDw8PDwuPj4-Pj4-PjxbLT5bLT4rPis8PF08PDw8PDwuPj4-Pj4-Pls8PDw8PDwuPi4-Pj4-Pi1dPlstPDwrPj5dPDw8PDw8PC48LjwuPj4-Pj4-XT5bLT4rKz4rPDxdPisrK1stPDw8Lj4-Pl0-Wy08PCs-Pl08PA&input=NDI">Try it online!

Breakdown:

First put the necessary characters into the tape: (newline)| o_-

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

Then collect the input into two cells and subtract 48 from each (to get the numeric value and not the numeral character)

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

Next, check for the special case of (1, 1) (Note that just this check accounts for 109 bytes of the code). As if ifs weren't hard enough to do in brainfuck, we have a nested if:

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

The following is the structure to check if a cell x is zero or nonzero:

temp0[-]+
temp1[-]
x[
 code1
 temp0-
 x[temp1+x-]
]
temp1[x+temp1-]
temp0[
 code2
temp0-]

However in a nested if, we need to have 4 temporary cells.

Now we get to the actual printing of characters:

Print the top bar and a newline:

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

Print a |, a row of o's, another | and a newline a number of times equal to the height:

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

And print the bottom bar (no newline needed here):

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


答:
C#, 118 bytes

```<code>int k(int a){var s=a.ToString();for(int i=0;i<s.Length;a+=s[i]<46?-(s[++i]-48)+ ++i-i:(s[i++]-48));return a+s.Length;}
</code>```

Title: Calculate the sum of ILD

Body:
Input:

An integer

Output:

Sum of the input itself + the length of the input + each individual digit of the input.

```<code>nr + nr-length + {sum of digits} = output
</code>```

Examples:

Input: 99

Output: 99 (nr) + 2 (nr-length) + (9 + 9) (digits) → 119

Input: 123

Output: 123 + 3 + (1 + 2 + 3) → 132

Challenge rules:

The input can also contain negative input, which are resolved special. The -/minus-sign is also +1 for the length, and is part of the first digit.

For example:

Input: -123

Output: -123 + 4 + (-1 + 2 + 3) → -115

You can assume that the input nor output will ever be outside the range of an (32-bit) integer.

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases:

```<code>87901 → 87931
123 → 132
99 → 119
5 → 11
1 → 3
0 → 1
-3 → -4
-123 → -115
-900 → -905
-87901 → -87886
</code>```

Semi-related: Count Sum of all Digits

Body:
C#, 118 bytes

int k(int a){var s=a.ToString();for(int i=0;i<s.Length;a+=s[i]<46?-(s[++i]-48)+ ++i-i:(s[i++]-48));return a+s.Length;}


答:
C#, 106 bytes

I beat java my a byte, my life is complete

```<code>int r(int n){var s=n+"";return n+s.Length+s.Select((k,j)=>int.Parse(s[k==45?1:j]+"")*(k==45?-2:1)).Sum();}
</code>```

Ungolfed (kinda)

```<code>    public static int r(int n)
    {
            var s = n + "";
            return n + s.Length + s.Select((k, j) =>int.Parse(s[k==45?1:j]+"")*(k==45?-2:1)).Sum();
    }
</code>```

Title: Calculate the sum of ILD

Body:
C#, 106 bytes

I beat java my a byte, my life is complete

int r(int n){var s=n+"";return n+s.Length+s.Select((k,j)=>int.Parse(s[k==45?1:j]+"")*(k==45?-2:1)).Sum();}

Ungolfed (kinda)

    public static int r(int n)
    {
            var s = n + "";
            return n + s.Length + s.Select((k, j) =>int.Parse(s[k==45?1:j]+"")*(k==45?-2:1)).Sum();
    }


问:
Sum of integers in string, separated by non-numericals such as 'a' and 'Y'
Create a program which sums all integers found in a string which is set as a variable in the program (thus, the program doesn't have to handle any input). The integer numbers are separated by non-numericals (anything but 0, 1, 2, 3, ..., 9).

Examples:

e7rde f  ,fe 43 jfj 54f4sD = 7+43+54+4=108

5 = 5

64 545,5445-32JIFk0ddk = 64+545+5445+32+0=6086

0ab0 = 0+0 = 0

Extra notes:

Unicode support is not necessary, but allowed

-n (where n is an integer) is not counted as a negative n, but as a hyphen followed by n.

The answer may be printed on the screen (but not required).

Shortest answer (in characters) win.

答:
Swift 3, 78

```<code>s.characters.split{!("0"..."9"~=$0)}.flatMap{Int(String($0))}.reduce(0){$0+$1}
</code>```

where s is the string

ContentLicense: CC BY-SA 4.0

Body:
Swift 3, 78

s.characters.split{!("0"..."9"~=$0)}.flatMap{Int(String($0))}.reduce(0){$0+$1}

where s is the string


问:
Generate excel column name from index
This one comes from a real life problem. We solved it, of course, but it keeps feeling like it could have be done better, that it's too lengthy and roundabout solution. However none of my colleagues can think of a more succinct way of writing it. Hence I present it as code-golf.

The goal is to convert a nonnegative integer into a string the same way Excel presents its column headers. Thus:

```<code>0 -> A
1 -> B
...
25 -> Z
26 -> AA
27 -> AB
...
51 -> AZ
52 -> BA
...
16,383 -> XFD
</code>```

It has to work at least up to 16,383, but beyond is acceptable too (no bonus points though). I'm looking forward most to the C# solution, but, as per traditions of code-golf, any real programming language is welcome.

Title: Generate excel column name from index

Body:
Python 45 <s>51</s>

f=lambda i:i>=0and f(i/26-1)+chr(65+i%26)or''


答:
PowerShell v4, 48 bytes

```<code>param($n)$n,"$n".length+[char[]]"$n"-join'+'|iex
</code>```

This should work in v2+, but I only tested in v4.

Takes input $n. Creates a new array with the , operator consisting of $n and the .length when $n is converted to a string. Concatenates with that the string $n cast as a char-array. Then, that whole array is -joined together with + before being piped to iex (similar to eval). The result is left on the pipeline and output is implicit.

For example, for input -123, the array would look like (-123, 4, -, 1, 2, 3), and the string after the -join would look like -123+4+-+1+2+3. Then the Invoke-Expression happens, and the result is -115 as expected.

Title: Calculate the sum of ILD

Body:
PowerShell v4, 48 bytes

param($n)$n,"$n".length+[char[]]"$n"-join'+'|iex

This should work in v2+, but I only tested in v4.

Takes input $n. Creates a new array with the , operator consisting of $n and the .length when $n is converted to a string. Concatenates with that the string $n cast as a char-array. Then, that whole array is -joined together with + before being piped to iex (similar to eval). The result is left on the pipeline and output is implicit.

For example, for input -123, the array would look like (-123, 4, -, 1, 2, 3), and the string after the -join would look like -123+4+-+1+2+3. Then the Invoke-Expression happens, and the result is -115 as expected.


答:
JavaScript (ES6), 98 bytes

```<code>s=>s.replace(/./g,c=>p<0?c:(p+=/[elp]/i.test(c)-/[ghos]/i.test(c))<0?"<"+c:"_",p=0)+"<".slice(p<0)
</code>```

Explanation: p maintains the current number of pellets. If it's already negative, we just return the character and move on, so that the rest of the string is untouched. Otherwise, we examine the current character, and if that makes p become negative, we insert the < character, otherwise we replace the current character with _. Finally, if p never becomes negative, we suffix a < to the string.

Title: Can Pac-Man Eat This String?

Body:
In the arcade version of the game, Pac-Man eats pac-dots. However, in this challenge, he's hungry for alphanumeric characters and punctuation in a string.

Your task is to create a function that feeds Pac-Man a string, evaluates if he can eat it or not, and returns the string with Pac-Man's location in it.

Pac-Man (<) eats characters from left to right, leaving an underscore or space for each character as he goes, and his goal is to get from the first position-1 to the last position+1:

```<code>1. <Pac
2. _<ac
3. __<c
4. ___<
</code>```

However, Pac-Man's natural enemy, the ghost, will stop him if he encounters one of the letters in the word "GHOST" (not case sensitive). Your function should return the string with Pac-Man's location as he encounters the ghost character:

```<code>1. <No!
2. _<o!
</code>```

The only thing that can defeat a ghost is a power pellet. If Pac-Man reaches a letter in the word "PELLET" (also not case sensitive) before coming to a ghost, he will eat the ghost and keep moving, and that pellet will be used up. Power pellets can stack (ie, in ppgg both ghosts would be eaten). The T character exists as both as a ghost and a pellet, so it can be ignored (treated as any other letter, like a).

```<code>1. <Pop
2. _<op
3. __<p
4. ___<
</code>```

To further clarify, in the string "Pac-Man loses here", the following operations occur:

```<code>P <P, +1 Pellet (1 pellet)
a <a
c <c
- <-
M <M
a <a
n <n
  <[space]
l <l, +1 Pellet (2 pellets)
o <o, -1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
e <e, +1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
  <[space]
h <h, ghost wins, returns
e
r
e
</code>```

Examples

```<code>Input: Pacman wins!
Output: ____________<

Input: Pacman loses wah-wah :(
Output: _______________<h-wah :(

Input: PELLET PELLET GHOST
Output: ___________________<

Input: Hello World!
Output: <Hello World!

Input: <_!@12<_<_<
Output: ___________<
</code>```

This is code-golf--lowest score in bytes wins.

Body:
JavaScript (ES6), 98 bytes

s=>s.replace(/./g,c=>p<0?c:(p+=/[elp]/i.test(c)-/[ghos]/i.test(c))<0?"<"+c:"_",p=0)+"<".slice(p<0)

Explanation: p maintains the current number of pellets. If it's already negative, we just return the character and move on, so that the rest of the string is untouched. Otherwise, we examine the current character, and if that makes p become negative, we insert the < character, otherwise we replace the current character with _. Finally, if p never becomes negative, we suffix a < to the string.


问:
Golf bit weaving
Note: the first half of this challenge comes from Martin Ender's previous challenge, Visualize Bit Weaving.

The esoteric programming language evil has an interesting operation on byte values which it calls "weaving".

It is essentially a permutation of the eight bits of the byte (it doesn't matter which end we start counting from, as the pattern is symmetric):

Bit 0 is moved to bit 2

Bit 1 is moved to bit 0

Bit 2 is moved to bit 4

Bit 3 is moved to bit 1

Bit 4 is moved to bit 6

Bit 5 is moved to bit 3

Bit 6 is moved to bit 7

Bit 7 is moved to bit 5

For convenience, here are three other representations of the permutation. As a cycle:

```<code>(02467531)
</code>```

As a mapping:

```<code>57361402 -> 76543210 -> 64725031
</code>```

And as a list of pairs of the mapping:

```<code>[[0,2], [1,0], [2,4], [3,1], [4,6], [5,3], [6,7], [7,5]]
</code>```

After 8 weavings, the byte is essentially reset.

For example, weaving the number 10011101 (which is 157 in base 10) will produce 01110110 (which is 118 in base 10).

Input

There are only 256 valid inputs, namely all the integers between 0 and 255 inclusive. That may be taken in any base, but it must be consistent and you must specify it if the base you choose is not base ten.

You may not zero-pad your inputs.

Output

You should output the result of the bit weaving, in any base, which must also be consistent and specified if not base ten.

You may zero-pad your outputs.

Related: Visualize Bit Weaving

答:
vi, 27 bytes

```<code>8I0<ESC>$7hc0lxp<ESC>l"qd0xp3@q03@q
</code>```

Where <ESC> represents the Escape character. I/O is in binary, output is padded. 24 bytes in vim:

```<code>8I0<ESC>$7hd0xpqqlxpq2@q03@q
</code>```

Title: Golf bit weaving

Body:
vi, 27 bytes

8I0<ESC>$7hc0lxp<ESC>l"qd0xp3@q03@q

Where <ESC> represents the Escape character. I/O is in binary, output is padded. 24 bytes in vim:

8I0<ESC>$7hd0xpqqlxpq2@q03@q


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

```

答:
ELF 32-bit LSB executable (Linux), 59 bytes

```<code>0000000: 7f 45 4c 46 01 00 00 00 00 00 00 00 00 90 43 0d  .ELF..........C.
0000010: 02 00 03 00 19 90 43 0d 19 90 43 0d 04 00 00 00  ......C...C.....
0000020: b9 2e 90 43 0d b2 0d cd 80 cc 20 00 01 00 48 65  ...C...... ...He
0000030: 6c 6c 6f 2c 20 57 6f 72 6c 64 21                 llo, World!
</code>```

This exits with INT 3 (breakpoint), so your shell may display a message to indicate this. However, the program itself prints nothing to STDERR.

Try it online!

Verification

```<code>$ cksum hw32
3205536342 59 hw32
$ ./hw32
Hello, World!Trace/breakpoint trap
$ ./hw32 | cat; echo
Hello, World!
$ ./hw32 | xxd -g 1
0000000: 48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 21           Hello, World!
</code>```

Title: "Hello, World!"

Body:
ELF 32-bit LSB executable (Linux), 59 bytes

0000000: 7f 45 4c 46 01 00 00 00 00 00 00 00 00 90 43 0d  .ELF..........C.
0000010: 02 00 03 00 19 90 43 0d 19 90 43 0d 04 00 00 00  ......C...C.....
0000020: b9 2e 90 43 0d b2 0d cd 80 cc 20 00 01 00 48 65  ...C...... ...He
0000030: 6c 6c 6f 2c 20 57 6f 72 6c 64 21                 llo, World!

This exits with INT 3 (breakpoint), so your shell may display a message to indicate this. However, the program itself prints nothing to STDERR.

Try it online!

Verification

$ cksum hw32
3205536342 59 hw32
$ ./hw32
Hello, World!Trace/breakpoint trap
$ ./hw32 | cat; echo
Hello, World!
$ ./hw32 | xxd -g 1
0000000: 48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 21           Hello, World!


问:
Starbucks to English
In the classic days of Starbucks before these newfangled sticker-printers and wireless drivethrough headset palmtop scanner dealies, in the heady days of 2000-ish, Starbucks had a concise system for describing beverages with a strict syntax and accompanying encoded form.

Vertically on the cup there are a series of labelled boxes which may contain certain values.:

```<code>Decaf
[   ]     -blank-  X  1/2  1/3  2/3
Shots
[   ]     -blank-  0 1 2 3 ... 20    followed by    S T G V
Syrup
[   ]     -blank-  V M C H
Milk
[   ]     -blank-  Wh % N B
Custom
[    ]    -blank- ((-|x)?(F|WC|M|CR) )+
Drink
[   ]     E EM ECP A L C CM
</code>```

But we will use a horizontal form for easier manipulation. These are the names of the 6 fields of the input which may be any convenient form. Examples here are simple CSV. The Custom field and Syrup fields each may be a concatenation of several values. You may use any convenient subdelimiter. Examples here use space. The Shots field is also a concatenation of a (possible) number and a designation of the cup size (which is implicit in the physical cup but naturally fits in this place in the encoding).

The Decaf field values are translated into words like this

```<code>-blank-   -nothing-
X         "decaf"
1/2       "half-caf"
1/3       "one-third-caf"
2/3       "two-thirds-caf"
</code>```

Logically, the fractional values are only permissible when the number of shots is divisible by the denominator; but for this challenge it is not necessary to detect or diagnose this error.

The Shots field should be broken into its numerical component (if present) and the size identifier. The number should be displayed in latin tuple form: single, double, triple, quadruple, quintuple, beyond 5 just print the number and the suffix "-tuple" ie. 7-tuple, 16-tuple. The size designations are:

```<code>S  short
T  tall
G  grande
V  venti
</code>```

Eg.

```<code>2T  double tall
3G  triple grande
</code>```

The Syrup field may contain one or more of several optional-number/lettercode tokens. The maximum number of a syrup is 20. Even that is too much. LOL.

```<code>V  vanilla
C  caramel
M  mocha
H  hazelnut
</code>```

Eg.

```<code>2V 2C     two vanilla two caramel
H         hazelnut
M H 1V    mocha hazelnut one vanilla
</code>```

The Milk field may contain one of the following.

```<code>Wh  whole-milk
%   two-percent
N   skim
B   breve
</code>```

The Custom field may contain one or more of several modifiers with optional x or - sign.

```<code>x  extra     F   foam
-  no        WC  whip
             M   mocha drizzle
             CR  caramel drizzle
</code>```

The Drink field contains one drink id.

```<code>E    espresso
EM   espresso macchiato
ECP  espresso con panna
A    americano
L    latte
C    cappuccino
CM   caramel macchiato
</code>```

Any field may be blank except for the size designation and the drink id.

Examples.

```<code>,3G,V,Wh,,L    =>   triple grande vanilla whole-milk latte
X,2T,,N,,L     =>   decaf double tall skim latte
1/2,V,,,,CM    =>   half-caf venti caramel macchiato
2/3,3V,3V,B,WC,L  => two-thirds-caf triple venti three vanilla breve whip latte
,G,,,xCR,CM    =>   grande extra caramel drizzle caramel macchiato
X,4T,2M 2C,B,xWC -F xM,C  =>
  decaf quadruple tall two mocha two caramel breve extra whip no foam extra mocha drizzle cappuccino
</code>```

There is no need to diagnose erroneous or illogical concoctions such as a "no foam ... cappuccino*.

Additional Complication

For only the drinks with the word espresso, the number single should be replaced by solo and double should be replaced by doppio. And the size may be unspecified and omitted. Also, just for the bare espresso drink itself, if the only other specification is one of these two specially-replaced numbers-of-shots, then the word espresso itself should be omitted.

```<code>-blank-   -nothing-
X         "decaf"
1/2       "half-caf"
1/3       "one-third-caf"
2/3       "two-thirds-caf"
</code>```0

Additional observations on 'reading a cup'

This part is not a requirement for this challenge but may be a useful refinement in applying this sort of verbalized system in other domains.

I mentioned syntax at the very beginning, and by applying the schema to incoming streams of words, orders could be transmitted verbally by several order takers to the barista making beverages. The rough framework SIZE .... DRINK provides demarcation between several orders spoken at once. There is thus a tendency to make all the interior attributes as adjectival phrases so the order also has a valid English noun-phrase structure. So whip is often spoken with whip or whipped and foam is often spoken foamy or with foam.

Thus, for some old-time baristas, they're not "correcting you" when they repeat the order in the proper format (well,... sometimes). They're simply organizing the information for the purpose of remembering all the details exactly. By schematizing the information, an entire beverage order becomes a single unit for the purpose of applying the magic number 7 plus or minus 2. So a barista with this skill can hold 5-9 orders in their head provided other distractions do not consume too much head room. :)

答:
Javascript ES6, <s>902</s> 900 bytes

```<code>s=>(R=(l,r)=>(l.split`.`.map((e,i,l)=>!(i%2)&&(r=r.split(e).join(l[i+1]+" "))),r),R("-.no.!.-tuple.1/2.half-caf.1/3.one-third-caf.2/3.two-thirds-caf.ECP.Econ panna.CM.RY.CR.RZ.EM.EY.WC.whip.Wh.whole-milk.A.americano.B.breve.C.cappuccino.D.extra.E.espresso.F.foam.G.grande.H.hazelnut.I.venti.L.latte.M.OZ.N.skim.O.mocha.R.caramel.S.short.T.tall.V.vanilla.X.decaf.Y.macchiato.Z.drizzle.%.two-percent",R(",1,,,,E.solo.,2,,,,E.doppio",s).split`,`.map((e,i)=>(`1VI.2MO.2CR.4xD`.split`.`.map(k=>k[0]==i&&(e=e.split(k[1]).join(k[2]))),i==1?(e=R("1!.single.2!.double.3!.triple.4!.quadruple.5!.quintuple",e.replace(/(\d+)/,"$1!"))):i==2?(e=R("10.ten.20.twenty.11.eleven.12.twelve.13.thir0.14.four0.15.fif0.16.six0.17.seven0.18.eigh0.19.nine0.0.teen.1.one.2.two.3.three.4.four.5.five.6.six.7.seven.8.eight.9.nine",e)):s.includes`E`&&(e=R("single.solo.double.doppio",e)),e)).join` `).replace(/\s+/g," ").trim())
</code>```

"Ungolfed":

```<code>s=>(
  R=(l,r)=>(l.split`.`.map((e,i,l)=>!(i%2)&&(r=r.split(e).join(l[i+1]+" "))),r),                                   // consecutive string replacement function
  R("-.no.!.-tuple.1/2.half-caf.1/3.one-third-caf.2/3.two-thirds-caf.ECP.Econ panna.CM.RY.CR.RZ.EM.EY.WC.whip.     // replace all symbols with appropriate values
     Wh.whole-milk.A.americano.B.breve.C.cappuccino.D.extra.E.espresso.F.foam.G.grande.H.hazelnut.I.venti.L.latte.
     M.OZ.N.skim.O.mocha.R.caramel.S.short.T.tall.V.vanilla.X.decaf.Y.macchiato.Z.drizzle.%.two-percent",
    R(",1,,,,E.solo.,2,,,,E.doppio",s)                                                                             // if special espresso cases, directly replace entire string
    .split`,`.map((e,i)=>(                                                                                // split input at commas
      `1VI.2MO.2CR.4xD`.split`.`.map(k=>k[0]==i&&(e=e.split(k[1]).join(k[2]))),                                    // substitute duplicate symbols with unique symbols
      i==1?(e=R("1!.single.2!.double.3!.triple.4!.quadruple.5!.quintuple",e.replace(/(\d+)/,"$1!"))):              // if in shots section, expand all numbers
      i==2?(e=R("10.ten.20.twenty.11.eleven.12.twelve.13.thir0.14.four0.15.fif0.16.six0.17.seven0.18.eigh0.        // if in syrup section, expand all numbers
                  19.nine0.0.teen.1.one.2.two.3.three.4.four.5.five.6.six.7.seven.8.eight.9.nine",e)):
      s.includes`E`&&(e=R("single.solo.double.doppio",e)),                                                         // replace single,double with solo,doppio if espresso is in the string
    e)).join` `).replace(/\s+/g," ").trim())                                                                       // join sections, cleanup whitespaces
</code>```

Example runs:

```<code>f(",3G,V,Wh,,L")              -> triple grande vanilla whole-milk latte
f("X,2T,,N,,L")               -> decaf double tall skim latte
f("1/2,V,,,,CM")              -> half-caf venti caramel macchiato
f("2/3,3V,3V,B,WC,L")         -> two-thirds-caf triple venti three vanilla breve whip latte
f(",G,,,xCR,CM")              -> grande extra caramel drizzle caramel macchiato
f("X,4T,2M 2C,B,xWC -F xM,C") -> decaf quadruple tall two mocha two caramel breve extra whip no foam extra mocha drizzle cappuccino
f(",2,1V,B,,EM")              -> doppio one vanilla breve espresso macchiato
f(",1,,,,E")                  -> solo
f(",2,,,,E")                  -> doppio
f(",3,,,,E")                  -> triple espresso
</code>```

Title: Starbucks to English

Body:
Javascript ES6, <s>902</s> 900 bytes

s=>(R=(l,r)=>(l.split`.`.map((e,i,l)=>!(i%2)&&(r=r.split(e).join(l[i+1]+" "))),r),R("-.no.!.-tuple.1/2.half-caf.1/3.one-third-caf.2/3.two-thirds-caf.ECP.Econ panna.CM.RY.CR.RZ.EM.EY.WC.whip.Wh.whole-milk.A.americano.B.breve.C.cappuccino.D.extra.E.espresso.F.foam.G.grande.H.hazelnut.I.venti.L.latte.M.OZ.N.skim.O.mocha.R.caramel.S.short.T.tall.V.vanilla.X.decaf.Y.macchiato.Z.drizzle.%.two-percent",R(",1,,,,E.solo.,2,,,,E.doppio",s).split`,`.map((e,i)=>(`1VI.2MO.2CR.4xD`.split`.`.map(k=>k[0]==i&&(e=e.split(k[1]).join(k[2]))),i==1?(e=R("1!.single.2!.double.3!.triple.4!.quadruple.5!.quintuple",e.replace(/(\d+)/,"$1!"))):i==2?(e=R("10.ten.20.twenty.11.eleven.12.twelve.13.thir0.14.four0.15.fif0.16.six0.17.seven0.18.eigh0.19.nine0.0.teen.1.one.2.two.3.three.4.four.5.five.6.six.7.seven.8.eight.9.nine",e)):s.includes`E`&&(e=R("single.solo.double.doppio",e)),e)).join` `).replace(/\s+/g," ").trim())

"Ungolfed":

s=>(
  R=(l,r)=>(l.split`.`.map((e,i,l)=>!(i%2)&&(r=r.split(e).join(l[i+1]+" "))),r),                                   // consecutive string replacement function
  R("-.no.!.-tuple.1/2.half-caf.1/3.one-third-caf.2/3.two-thirds-caf.ECP.Econ panna.CM.RY.CR.RZ.EM.EY.WC.whip.     // replace all symbols with appropriate values
     Wh.whole-milk.A.americano.B.breve.C.cappuccino.D.extra.E.espresso.F.foam.G.grande.H.hazelnut.I.venti.L.latte.
     M.OZ.N.skim.O.mocha.R.caramel.S.short.T.tall.V.vanilla.X.decaf.Y.macchiato.Z.drizzle.%.two-percent",
    R(",1,,,,E.solo.,2,,,,E.doppio",s)                                                                             // if special espresso cases, directly replace entire string
    .split`,`.map((e,i)=>(                                                                                // split input at commas
      `1VI.2MO.2CR.4xD`.split`.`.map(k=>k[0]==i&&(e=e.split(k[1]).join(k[2]))),                                    // substitute duplicate symbols with unique symbols
      i==1?(e=R("1!.single.2!.double.3!.triple.4!.quadruple.5!.quintuple",e.replace(/(\d+)/,"$1!"))):              // if in shots section, expand all numbers
      i==2?(e=R("10.ten.20.twenty.11.eleven.12.twelve.13.thir0.14.four0.15.fif0.16.six0.17.seven0.18.eigh0.        // if in syrup section, expand all numbers
                  19.nine0.0.teen.1.one.2.two.3.three.4.four.5.five.6.six.7.seven.8.eight.9.nine",e)):
      s.includes`E`&&(e=R("single.solo.double.doppio",e)),                                                         // replace single,double with solo,doppio if espresso is in the string
    e)).join` `).replace(/\s+/g," ").trim())                                                                       // join sections, cleanup whitespaces

Example runs:

f(",3G,V,Wh,,L")              -> triple grande vanilla whole-milk latte
f("X,2T,,N,,L")               -> decaf double tall skim latte
f("1/2,V,,,,CM")              -> half-caf venti caramel macchiato
f("2/3,3V,3V,B,WC,L")         -> two-thirds-caf triple venti three vanilla breve whip latte
f(",G,,,xCR,CM")              -> grande extra caramel drizzle caramel macchiato
f("X,4T,2M 2C,B,xWC -F xM,C") -> decaf quadruple tall two mocha two caramel breve extra whip no foam extra mocha drizzle cappuccino
f(",2,1V,B,,EM")              -> doppio one vanilla breve espresso macchiato
f(",1,,,,E")                  -> solo
f(",2,,,,E")                  -> doppio
f(",3,,,,E")                  -> triple espresso


Title: "Hello, World!"

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

```

Body:
ELF 64-bit LSB executable (Linux), 104 bytes

0000000: 7f 45 4c 46 02 01 01 03 b0 04 b3 01 b2 0e eb 18  .ELF............
0000010: 02 00 3e 00 01 00 00 00 08 00 40 00 00 00 00 00  ..>.......@.....
0000020: 30 00 00 00 00 00 00 00 b9 48 00 40 00 90 eb 30  0........H.@...0
0000030: 01 00 00 00 01 00 38 00 01 00 00 00 00 00 00 00  ......8.........
0000040: 01 00 40 00 00 00 00 00 48 65 6c 6c 6f 2c 20 57  ..@.....Hello, W
0000050: 6f 72 6c 64 21 0a 00 00 6f 72 6c 64 21 0a 00 00  orld!...orld!...
0000060: cd 80 b0 01 b3 00 cd 80                          ........

This sets as many proper headers as possible without affecting the byte count, prints a trailing linefeed and exits cleanly with exit code 0.

Try it online!

Verification

$ cksum hw64
3288151474 104 hw64
$ file hw64
hw64: ELF 64-bit LSB executable, x86-64, version 1, statically linked, corrupted section header size
$ ./hw64
Hello, World!
$ echo $?
0


答:
JavaScript (ES6), 75 bytes

```<code>f=(n,...a)=>a.includes(n=n<0?-n:n)?n:f([...n+``].reverse().join``-n,n,...a)
</code>```

n<0?n=-n:n and n*=n>0||-1 also work. Algorithm somewhat resembles the PowerShell answer, although this is a recursive formulation.

Title: Reverse and subtract

Body:
JavaScript (ES6), 75 bytes

f=(n,...a)=>a.includes(n=n<0?-n:n)?n:f([...n+``].reverse().join``-n,n,...a)

n<0?n=-n:n and n*=n>0||-1 also work. Algorithm somewhat resembles the PowerShell answer, although this is a recursive formulation.


答:
Haskell, 119 113 Bytes

Thanks to Daniel Wagner for 6 bytes less.

```<code>p=(0!)
n!(c:s)|elem c"ghosGHOS"=if n<1then '<':c:s else(n-1)&s|elem c"elpELP"=(n+1)&s|0<1=n&s
_!_="<"
n&s='_':n!s
</code>```

Call it as p "Hello World!".

The 1then is an edge case that is interpreted correctly in my GHC (7.10), but it throws of most syntax highlighters. So it might be interpreted differently in your compiler as well.

Ungolfed:

pacman string = go 0 string

-- | In the golfed version: (!)
go _   []                   = "<"                            -- won
go pellets (char:string)
 | char `elem` "ghosGHOS"
 = if pellets < 1        then '<':char:string                -- lost
                         else nextStep (pellets - 1) string  -- ghost
 | char `elem` "elpELP"
 =                            nextStep (pellets + 1) string  -- pellet
 | otherwise
 =                            nextStep  pellets      string  -- anything else

-- | In the golfed version: (&)
nextStep pellets string = '_':(go pellets string)
```

Title: Can Pac-Man Eat This String?

Body:
Haskell, 119 113 Bytes

Thanks to Daniel Wagner for 6 bytes less.

p=(0!)
n!(c:s)|elem c"ghosGHOS"=if n<1then '<':c:s else(n-1)&s|elem c"elpELP"=(n+1)&s|0<1=n&s
_!_="<"
n&s='_':n!s

Call it as p "Hello World!".

The 1then is an edge case that is interpreted correctly in my GHC (7.10), but it throws of most syntax highlighters. So it might be interpreted differently in your compiler as well.

Ungolfed:

pacman string = go 0 string

-- | In the golfed version: (!)
go _   []                   = "<"                            -- won
go pellets (char:string)
 | char `elem` "ghosGHOS"
 = if pellets < 1        then '<':char:string                -- lost
                         else nextStep (pellets - 1) string  -- ghost
 | char `elem` "elpELP"
 =                            nextStep (pellets + 1) string  -- pellet
 | otherwise
 =                            nextStep  pellets      string  -- anything else

-- | In the golfed version: (&)
nextStep pellets string = '_':(go pellets string)


答:
Ruby, 57 bytes

```<code>->n,*h{h[n]=n=(n-"#{n}".reverse.to_i).abs until h[n];n>0}
</code>```

The initially empty array h tracks previously hit values. We iterate the number until we hit a previous value, then check the value on the last iteration. Since 0 is a cycle of 1, it'll be 0 if and only if there's no larger cycle. I take an extra 2 bytes to convert this to a Boolean because 0 is truthy in Ruby.

Title: Reverse and subtract

Body:
Challenge description

Let's take a positive integer n, reverse its digits to get rev(n) and get the absolute value of the difference of these two numbers: |n - rev(n)| (or abs(n - rev(n))).

Example:

```<code>n = 5067
rev(n) = 7605
|n - rev(n)| = |5067 - 7605| = |-2538| = 2538
</code>```

After repeating this operation sufficiently many times, most numbers will become 0 (thus terminating the loop)...

```<code>5067 -> 2538 -> 5814 -> 1629 -> 7632 -> 5265 -> 360 -> 297 -> 495 -> 99 -> 0
</code>```

...though some numbers (like 1584) get stuck in an infinite loop:

```<code>1584 -> 3267 -> 4356 -> 2178 -> 6534 -> 2178 -> 6534 -> 2178 -> 6534 -> ...
                        ^ infinite loop starts here
</code>```

Your job is to determine if a given integer gets stuck in an infinite loop.

Input description

A positive integer.

Output description

A truthy value (True, 1) if the number gets stuck in an infinite loop, a falsy value (False, 0) otherwise.

Notes

Trailing zeroes should be ommited. i.e. rev(5020) = 205.

Remember that this is code-golf, so make your code as short as possible!

Relevant sequence: A072140

Body:
Ruby, 57 bytes

->n,*h{h[n]=n=(n-"#{n}".reverse.to_i).abs until h[n];n>0}

The initially empty array h tracks previously hit values. We iterate the number until we hit a previous value, then check the value on the last iteration. Since 0 is a cycle of 1, it'll be 0 if and only if there's no larger cycle. I take an extra 2 bytes to convert this to a Boolean because 0 is truthy in Ruby.


答:
Python 2, 50 bytes

n=input()
exec'n=abs(n-int(`n`[::-1]));'*n
print n
```

Test it on Ideone.

Background

This uses @MartinEnder's upper bound of 10n iterations and the following observations.

There are 9 × 10k - 1 positive integers n with k digits.

The difference of a number and its reverse is always a multiple of 9, so only 10k - 1 of them can occur after the first iteration.

Of the multiples, more than 1 / 10 will lose a digit in the next iteration (for starters, all that start and end with the same digits, and roughly twice as many if the first digit is neither a 1 nor a 9), so it takes at most 9 × 10k - 2 to either enter a loop or lose a digit.

Applying the same reasoning to the eventual resulting integer of k - 1 digits and so on, it takes at most 9 × 10k - 2 + 9 × 10k - 2 + … ≤ 10k - 1 ≤ n iterations to enter a loop or reach 0.

Title: Reverse and subtract

Body:
Python 2, 50 bytes

n=input()
exec'n=abs(n-int(`n`[::-1]));'*n
print n

Test it on Ideone.

Background

This uses @MartinEnder's upper bound of 10n iterations and the following observations.

There are 9 × 10k - 1 positive integers n with k digits.

The difference of a number and its reverse is always a multiple of 9, so only 10k - 1 of them can occur after the first iteration.

Of the multiples, more than 1 / 10 will lose a digit in the next iteration (for starters, all that start and end with the same digits, and roughly twice as many if the first digit is neither a 1 nor a 9), so it takes at most 9 × 10k - 2 to either enter a loop or lose a digit.

Applying the same reasoning to the eventual resulting integer of k - 1 digits and so on, it takes at most 9 × 10k - 2 + 9 × 10k - 2 + … ≤ 10k - 1 ≤ n iterations to enter a loop or reach 0.


问:
Tips for golfing in Factor
What general tips do you have for golfing in Factor? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Factor (e.g. "remove comments" is not an answer).</p>

答:
The following are equivalent

```<code>[ 1 2 3 ] [ 1 + ] map V{ } clone-like
[ 1 2 3 ] [ 1 + ] V{ } map-as
</code>```

It's just map-as and the other -as words (zip-as, map-as, accumulate-as, etc) are usually shorter than an obj clone-like if you're going to use them anyways.

Title: Tips for golfing in Factor

Body:
The following are equivalent

[ 1 2 3 ] [ 1 + ] map V{ } clone-like
[ 1 2 3 ] [ 1 + ] V{ } map-as

It's just map-as and the other -as words (zip-as, map-as, accumulate-as, etc) are usually shorter than an obj clone-like if you're going to use them anyways.


问:
Expand a bash brace expansion
For mostly historical reasons, bash is quite a hodge-podge of syntax and programming paradigms - this can make it awkward and sometimes frustrating to golf in.  However it does have a few tricks up its sleeve that can often make it competitive with other mainstream script languages.  One of these is brace expansion.

There are two basic types of brace expansion:

List braces may contain comma-separated lists of arbitrary strings (including duplicates and the empty string).  For example {a,b,c,,pp,cg,pp,} will expand to a b c  pp cg pp (note the spaces around the empty strings).

Sequence braces may contain sequence endpoints separated by ... Optionally another .. may follow, followed by a step size.  Sequence endpoints may be either integers or characters.  The sequence will automatically ascend or descend according to which endpoint is greater.  For example:

{0..15} will expand to 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

{-10..-5} will expand to -10 -9 -8 -7 -6 -5

{3..-6..2} will expand to 3 1 -1 -3 -5

{a..f} will expand to a b c d e f

{Z..P..3} will expand to Z W T Q

Beyond this, sequence and list braces may exist with list braces:

{a,b,{f..k},p} will expand to a b f g h i j k p

{a,{b,c}} will expand to a b c

Braces expand with non-whitespace strings either side of them.  For example:

c{a,o,ha,}t will expand to cat cot chat ct

This also works for multiple braces concatenated together:

{ab,fg}{1..3} will expand to ab1 ab2 ab3 fg1 fg2 fg3

This can get quite complex.  For example:

{A..C}{x,{ab,fg}{1..3},y,} will expand to Ax Aab1 Aab2 Aab3 Afg1 Afg2 Afg3 Ay A Bx Bab1 Bab2 Bab3 Bfg1 Bfg2 Bfg3 By B Cx Cab1 Cab2 Cab3 Cfg1 Cfg2 Cfg3 Cy C

However, if there is whitespace between expansions, then they simply expand as separate expansions.  For example:

{a..c} {1..5} will expand to a b c 1 2 3 4 5

Note how order is always preserved.

Entries for this challenge will expand bash brace expansions as described above.  In particular:

eval by bash (or other shells that perform similar expansion) is not allowed

sequence braces will always be number-to-number, lowercase-to-lowercase or uppercase-to-uppercase with no mixing.  Numbers will be integers in the 32-bit signed range.  If given, the optional step size will always be a positive integer.  (Note that bash will also expand {A..z} as well, but this may be ignored for this challenge)

individual items in list braces will always be composed only of upper- and lower-case alphanumeric characters (empty string included)

list braces may contain arbitrary nestings of other brace expansions

braces may be concatenated arbitrary numbers of times.  This will be limited by your language's memory, so the expectation is that you can theoretically do arbitrary numbers of concatenations but if/when you run out of memory that won't count against you.

The examples in the text above serve as testcases.  Summarised, with each line of input corresponding to the same line of output, they are:

Input

```<code>{0..15}
{-10..-5}
{3..-6..2}
{a..f}
{Z..P..3}
{a,b,{f..k},p}
{a,{b,c}}
c{a,o,ha,}t
{ab,fg}{1..3}
{A..C}{x,{ab,fg}{1..3},y,}
{a..c} {1..5}
{a{0..100..10},200}r
</code>```

Output

```<code>0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
-10 -9 -8 -7 -6 -5
3 1 -1 -3 -5
a b c d e f
Z W T Q
a b f g h i j k p
a b c
cat cot chat ct
ab1 ab2 ab3 fg1 fg2 fg3
Ax Aab1 Aab2 Aab3 Afg1 Afg2 Afg3 Ay A Bx Bab1 Bab2 Bab3 Bfg1 Bfg2 Bfg3 By B Cx Cab1 Cab2 Cab3 Cfg1 Cfg2 Cfg3 Cy C
a b c 1 2 3 4 5
a0r a10r a20r a30r a40r a50r a60r a70r a80r a90r a100r 200r
</code>```

答:
Python 2.7, <s>752</s> 728 bytes

Wow, this is like a bunch of code golfs in one challenge!

Thanks to @Neil for shortening a lambda

```<code>def b(s,o,p):
 t,f=s>':'and(ord,chr)or(int,str);s,o=t(s),t(o);d=cmp(o,s)
 return list(map(f,range(s,o+d,int(p)*d)))
def e(s):
 c=1;i=d=0
 while c:d+=-~'{}}'.count(s[i])%3-1;i+=1;c=i<len(s)and 0<d
 return i
def m(s):
 if len(s)<1:return[]
 if','==s[-1]:return m(s[:-1])+['']
 i=0
 while i<len(s)and','!=s[i]:i+=e(s[i:])
 return[s[:i]]+m(s[i+1:])
n=lambda a,b:[c+d for c in a for d in b]or a or b
def p(s):
 h=s.count
 if h('{')<1:return[s]
 f,l=s.index('{'),e(s)
 if h('{')<2and h('..')>0and f<1:s=s[1:-1].split('..');return b(s[0],s[1],s[2])if len(s)>2 else b(s[0],s[1],1)
 if f>0 or l<len(s):return n(p(s[:f]),n(p(s[f:l]),p(s[l:])))
 return sum(map(list,map(p,m(s[1:-1]))),[])
o=lambda s:' '.join(p('{'+s.replace(' ',',')+'}'))
</code>```

Explanation

b: calculates range according to specs.

e: returns position of first outermost close brace. Iterative.

m: splits outermost elements on commas. Recursive.

n: combines arrays while checking for empties. <s>I couldn't get and/or to work.</s>

p: Where most of the work is done. Checks all the cases (Range, just list, needs to combine). Recursive.

o: What should take input. Formats input/output to p.

I feel I can improve in some places, so I will try to golf more. Also I should put in more detail in the explanation.

Title: Expand a bash brace expansion

Body:
Python 2.7, <s>752</s> 728 bytes

Wow, this is like a bunch of code golfs in one challenge!

Thanks to @Neil for shortening a lambda

def b(s,o,p):
 t,f=s>':'and(ord,chr)or(int,str);s,o=t(s),t(o);d=cmp(o,s)
 return list(map(f,range(s,o+d,int(p)*d)))
def e(s):
 c=1;i=d=0
 while c:d+=-~'{}}'.count(s[i])%3-1;i+=1;c=i<len(s)and 0<d
 return i
def m(s):
 if len(s)<1:return[]
 if','==s[-1]:return m(s[:-1])+['']
 i=0
 while i<len(s)and','!=s[i]:i+=e(s[i:])
 return[s[:i]]+m(s[i+1:])
n=lambda a,b:[c+d for c in a for d in b]or a or b
def p(s):
 h=s.count
 if h('{')<1:return[s]
 f,l=s.index('{'),e(s)
 if h('{')<2and h('..')>0and f<1:s=s[1:-1].split('..');return b(s[0],s[1],s[2])if len(s)>2 else b(s[0],s[1],1)
 if f>0 or l<len(s):return n(p(s[:f]),n(p(s[f:l]),p(s[l:])))
 return sum(map(list,map(p,m(s[1:-1]))),[])
o=lambda s:' '.join(p('{'+s.replace(' ',',')+'}'))

Explanation

b: calculates range according to specs.

e: returns position of first outermost close brace. Iterative.

m: splits outermost elements on commas. Recursive.

n: combines arrays while checking for empties. <s>I couldn't get and/or to work.</s>

p: Where most of the work is done. Checks all the cases (Range, just list, needs to combine). Recursive.

o: What should take input. Formats input/output to p.

I feel I can improve in some places, so I will try to golf more. Also I should put in more detail in the explanation.


问:
It's Life, Jim, but not as we know it
You probably know Conway's Game of Life, the famous cellular automaton invented by mathematician John Conway. Life is a set of rules that, together, allow you to simulate a two-dimensional board of cells. The rules decide which cells on the board live and  which ones die. With some imagination, you could say that Life is a zero-player game: a game with the objective to find patterns with interesting behavior, like the famous glider.

A zero-player game... Until today. You are to write a program that plays the Game of Life - and plays it to win, King of the Hill-style. Your opponent (singular) of course tries to do the same. The winner is either the last bot with any live cells, or the player with the most live cells after 10000 generations.

Game rules

The rules are almost the same as normal (B3/S23) Life:

A live cell with fewer than two friendly neighbors dies from starvation.

A live cell with two or three friendly neighbors survives.

A live cell with more than three friendly neighbors dies from overpopulation.

A dead cell with exactly three neighbors of the same player comes alive to fight for that player provided there are no enemy neighbors.

...but after each generation, both you and your opponent get the opportunity to intervene. You can awake up to a maximum of 30 cells to fight for you. (Who goes first is decided by the server.)

The board is a (x,y) cells square. All squares are initially dead. The borders do not wrap around (this is not a torus-shaped world) and are permanently dead.

This is is a contest in the spirit of Battlebots and Core Wars. There is a central server that will run bots and it can be found here

Protocol

The arena server speaks a simple JSON protocol communicated through argv

Where Values is a JSON encoded string

y_size: the maximum y coords of tiles before they vanish

x_size: the maximum x coords of tiles before they vanish

tick_id: the current tick number

board: a dictionary with keys in the form '(y,x)' and values in the form bot_id (int)

bot_id: tiles in the board with this id are yours

Example:

```<code> {"y_size":2000,"x_size":2000,"board":{},"bot_id":1,"tick_id":1}

</code>```

Telling the server your choice:

Send the server a list of tiles to turn to your colour.

Only those that are empty will be changed

Nested coords list format

[[0,0], [0,1], [100,22]...]

NOTE: Your bot doesn't have to update the tiles at all - the server does the updating itself

Competition rules

If your implementation fails to follow the protocol, the turn it does will be forfeited; The server will assume no change in state

You are not allowed to willfully take advantage of a fault in the arena server.

Have your AI decide on moves in a sane time. Please send your next move as  fast as reasonably possible.

Finally, please be nice to the server. It's there for your enjoyment.

Not following these rules can lead to disqualification.

In the event of a tie, both players have 1 win added to their total

Running the controller yourself

The source for the controller can be found here. There are 2 ways of running the controller:

Competition mode (terminal)

Setup with python3 get_answers.py

Run an all v all competition with each bot pitting it against every other.

Testing mode (GUI)

Run python3 nice_gui.py

Click Pull Answers

If you want to add your own answer to try it before posting, click File -> Add manual answer and find the file and choose the language it's written in.

If your language isn't present ping me and I'll try to get it installed on the server I will run it on (installation and running instructions would be nice too!)

Choose 2 bots to pit against each other

Click Run

Watch the game...

Installation

Requires python3

get_answers requires bs4 and html5lib

controller requires a way of running .sh files (MinGW on windows)

Scoring

The bot with the most wins starting from <s>12/07/2016 (12th July)</s>   14/07/2016 (14th July, couldn't work out how to run a bot) wins.

Help with the controller/gui can be asked in this chat room

This question has been in development since 2014 and was the most upvoted question in the sandbox. Special Thanks goes to Wander Nauta (original author and concept), PPCG Chat (comments and help) and anyone who commented in the sandbox post (more comments).

答:
Python 3, RandomBot

This bot has trouble making intelligent decisions, but it at least knows not to try to place things on top of other things.  It'll randomly create gliders, boats, C/2 Orthagonals, and 2x2 blocks with various orientations, ensuring that when they're placed they're not overlapping with something else, ally or enemy.

This bot wasn't tested, seeing as I'm receiving all sorts of errors when I try to run the GUI.  Also, I used the TrainingBot as the base and just edit, so any similarities in code is probably because of that.

```<code>import random, copy
import sys, json
args = json.loads(sys.argv[1])
bot_id = args["bot_id"]
x_size = args["x_size"]
y_size = args["y_size"]
board = args["board"]
occupied = [tuple(key) for key,value in iter(board.items())]
cellsleft=30
move=[]
choices = [[[1,2],[2,1],[0,0],[0,1],[0,2]],
           [[0,0],[0,1],[1,1],[1,0]],
           [[0,1],[1,0],[0,2],[0,3],[1,3],[2,3],[3,3],[4,3],[5,2],[5,0]],
           [[0,0],[1,0],[0,1],[2,1],[2,2]]]
while cellsleft>0:
    x_add = random.randrange(x_size)
    y_add = random.randrange(y_size)
    new_glider = copy.deepcopy(random.choice(choices))
    randomdirection = random.choice([[1,1],[1,-1],[-1,1],[-1,-1]])
    maxy=max([y[0] for y in new_glider])
    maxx=max([x[1] for x in new_glider])
    for coord in new_glider:
        coord[0]=coord[0]*randomdirection[0]+y_add
        coord[1]=coord[1]*randomdirection[1]+x_add
        cellsleft-=1
    set([tuple(x) for x in new_glider])
    if not set([tuple(x) for x in new_glider]) & (set(occupied)|set([tuple(x) for x in move])) and cellsleft>0:
        if min(y[0] for y in new_glider)<0: new_glider = [[y[0]+maxy,y[1]] for y in new_glider]
        if min(y[1] for y in new_glider)<0: new_glider = [[y[0],y[1]+maxx] for y in new_glider]
        move += new_glider
    elif set([tuple(x) for x in new_glider]) & (set(occupied)|set([tuple(x) for x in move])):
        cellsleft+=len(new_glider)

print(json.dumps(move))
</code>```

Title: It's Life, Jim, but not as we know it

Body:
Python 3, RandomBot

This bot has trouble making intelligent decisions, but it at least knows not to try to place things on top of other things.  It'll randomly create gliders, boats, C/2 Orthagonals, and 2x2 blocks with various orientations, ensuring that when they're placed they're not overlapping with something else, ally or enemy.

This bot wasn't tested, seeing as I'm receiving all sorts of errors when I try to run the GUI.  Also, I used the TrainingBot as the base and just edit, so any similarities in code is probably because of that.

import random, copy
import sys, json
args = json.loads(sys.argv[1])
bot_id = args["bot_id"]
x_size = args["x_size"]
y_size = args["y_size"]
board = args["board"]
occupied = [tuple(key) for key,value in iter(board.items())]
cellsleft=30
move=[]
choices = [[[1,2],[2,1],[0,0],[0,1],[0,2]],
           [[0,0],[0,1],[1,1],[1,0]],
           [[0,1],[1,0],[0,2],[0,3],[1,3],[2,3],[3,3],[4,3],[5,2],[5,0]],
           [[0,0],[1,0],[0,1],[2,1],[2,2]]]
while cellsleft>0:
    x_add = random.randrange(x_size)
    y_add = random.randrange(y_size)
    new_glider = copy.deepcopy(random.choice(choices))
    randomdirection = random.choice([[1,1],[1,-1],[-1,1],[-1,-1]])
    maxy=max([y[0] for y in new_glider])
    maxx=max([x[1] for x in new_glider])
    for coord in new_glider:
        coord[0]=coord[0]*randomdirection[0]+y_add
        coord[1]=coord[1]*randomdirection[1]+x_add
        cellsleft-=1
    set([tuple(x) for x in new_glider])
    if not set([tuple(x) for x in new_glider]) & (set(occupied)|set([tuple(x) for x in move])) and cellsleft>0:
        if min(y[0] for y in new_glider)<0: new_glider = [[y[0]+maxy,y[1]] for y in new_glider]
        if min(y[1] for y in new_glider)<0: new_glider = [[y[0],y[1]+maxx] for y in new_glider]
        move += new_glider
    elif set([tuple(x) for x in new_glider]) & (set(occupied)|set([tuple(x) for x in move])):
        cellsleft+=len(new_glider)

print(json.dumps(move))


问:
Count sum of all digits
This challenge is to write a program or script which counts the sum of all digits within the integers from 1 up to and including a given number.

Input, one positive integer.
Output, the sum of digits in that number and all smaller numbers.

Examples:

```<code>Input: 5
Integer Sequence: 1, 2, 3, 4, 5
Sum of Digits: 1 + 2 + 3 + 4 + 5 = 15

Input: 12
Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
Sum of Digits: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 + 1 + 1 + 1 + 2 = 51
</code>```

To be clear, this is to count a sum of the digits - not the integers. For single-digit inputs, this will be the same. However, inputs larger than 10 will have different responses. This would be an incorrect response:

```<code>Input: 12
Output: 78
</code>```

Another example, to show the difference:

```<code>Input: 10

Integer Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Sum of Integers (INCORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Digit Sequence: 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0
Sum of Digits (CORRECT RESPONSE): 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 + 0 = 46
</code>```

A larger test case (CORRECT RESPONSE):

```<code>Input: 1000000
Output: 27000001
</code>```

Rules & Guidelines:

Submitted code must be a complete program or script - not just a function. If the code requires includes, imports, etc., they must be included in the posted code.

The number must be input by the user - not hard-coded. Input may be received as a command-line argument, file, stdin, or any other means by which your language can take user input.

The code must be able to properly handle inputs at least up to (2^64)-1.

The code should only output the sum.

Submitted programs & scripts should be user-friendly and not wasteful of computer resources (e.g.: they should not declare insanely-large arrays to hold every character). There is no strict bonus or penalty for this, but please be good programmers.

Scoring:

Primary scoring mechanism is by code length. Lower scores are better. The following bonuses and penalties also apply:

-25 Bonus if your code can handle all positive numbers, for example: 1234567891234567891234564789087414984894900000000

-50 Bonus if your code can handle simple expressions, for example 55*96-12. To qualify for this bonus, the code should handle + - / * (addition, subtraction, division, multiplication) operators and enforce order of operations. Division is regular integer division.

The given example (55*96-12) evaluates to 5268. Your code should return the same for either of those inputs - correct answer is 81393.

-10 Bonus if your code qualifies for the -50 bonus and can handle the ^ (exponent) operator.

-100 Bonus if your code qualifies for the -50 bonus and does not use eval or similar to handle expressions.

+300 Penalty if your code relies upon any web resources.

答:
Factor, 44

```<code>[ iota [ 1 + 10 >base ] map ""join >array [ 48 - ] [ + ] map-reduce ]
</code>```

Title: Count sum of all digits

Body:
Factor, 44

[ iota [ 1 + 10 >base ] map ""join >array [ 48 - ] [ + ] map-reduce ]