答:
Lua, Ruby - 31 bytes

```<code>s="trick"
--0;s="treat"
print s
</code>```

The explanation is the same as my Python/Lua answer.
Prints treat in Ruby, trick in Lua.

Title: Trick or Treat polyglot

Body:
Since Halloween is coming up I thought I might start a fun little code golf challenge!

The challenge is quite simple. You have to write a program that outputs either trick or treat.

"The twist?" you may ask. Well let me explain:

Your program has to do the following:

Be compilable/runnable in two different languages. Different versions of the same language don't count.

When you run the program in one language it should output trick and the other should output treat. The case is irrelevant and padding the string with whitespace characters are allowed (see examples).

This is code-golf,  so the solution with the fewest bytes wins.

A few explanations:

Valid outputs (Just for the words not for running the code in the two languages. Also adding quotes to signalize the beginning or end of the output. Do not include them in your solution!):

```<code>"trick"

"Treat"

"    TReAt"

"
     tRICk          "
</code>```

Invalid outputs:

```<code>"tri ck"

"tr
eat"

"trck"
</code>```

I'm interested to see what you can come up with! Happy Golfing!

I'd like to note that this is my first challenge so if you have suggestions on this question please leave them in the form of a comment.

Leaderboards

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

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

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

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

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

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

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

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

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

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

s="trick"
--0;s="treat"
print s

The explanation is the same as my Python/Lua answer.
Prints treat in Ruby, trick in Lua.


答:
Python 2, <s>89</s> <s>82</s> <s>77</s> <s>76</s> 75 bytes

n=0
for c in input():n=n<<8|ord(c)
while 1:print n;n^=2**n.bit_length()-n/n
```

<p>Test it on Ideone.</p>

<h3>How it works</h3>

<p>After initializing <strong>n</strong> to <strong>0</strong>, the second line performs the string-to-integer conversion specified in the challenges as follows.</p>

<p>In each step, <strong>n</strong> is shifted <strong>8</strong> units to the left, then bitwise <strong>OR</strong>-ed with the the code point of the next character <strong>c</strong>. For input <strong>Inf</strong>, this goes as follows.</p>

```n                                  0
a = n<<8                           0
b = 'I'                      1001001
n = a ^ b                    1001001
a = n<<8             100100100000000
b = 'n'                      1101110
n = a ^ b            100100101101110
a = n<<8     10010010110111000000000
b = 'f'                      1100110
n = a ^ b    10010010110111001100110
```

<p>Now we're ready to generate the output. To invert the bits of <strong>n</strong>, we proceed as follows.</p>

<p>First, we compute the bits in <strong>n</strong>'s binary representation without leading zeroes. Let's call the result <strong>k</strong>. Then, we compute the <strong>k</strong><sup>k</sup> power of <strong>2</strong>, which has <strong>k+1</strong> binary digits: a single <strong>1</strong>, followed by <strong>k</strong> <strong>0</strong>'s. We subtract <strong>1</strong> from the result, yielding a number composed of <strong>k</strong> ones, which we then XOR with <strong>n</strong> to invert its bits. For input <strong>inf</strong> this goes as follows.</p>

```n         4812390   10010010110111001100110
k              23
t = 2**k           100000000000000000000000
t -= 1              11111111111111111111111
n ^= t    3576217    1101101001000110011001
k              22
t = 2**k            10000000000000000000000
t -= 1               1111111111111111111111
n ^= t     618086      10010110111001100110
.
.
.
n               6                       110
k               3
t = 2**k                               1000
t -= 1                                  111
n ^= t          1                         1
k               1
t = 2**k                                 10
t -= 1                                    1
n ^= t          0                         0
```

<p>On additional hurdle in the implementation is that we have to print <strong>n</strong> before the first step, <em>after</em> the last step, and in all steps in between. Python doesn't have do-while loops and a single <em>print</em> statement costs <strong>8</strong> bytes, so we do the following instead.</p>

<p>In the straightforward implementation of the update step, i.e.,</p>

<pre class="lang-python prettyprint-override"><code>while n:print n;n^=2**n.bit_length()-1
print n
</code>```

we replace the loop with an infinite one (while 1) and compute the 1 in the loop as n/n. This is equivalent while n > 0.

Once n = 0, we stay in the loop, print the state once more, then try to update it. However, 0/0 triggers a ZeroDivisionError, breaking out of the loop and exiting with an error. Note that this causes stray output to STDERR, which is allowed by default.

ContentLicense: CC BY-SA 4.0

Title: Count down from "Infinity"

Body:
Seems like an impossible task right? Well, it's actually not that hard. If we write the word Infinity as 8-bit binary ASCII code, we'll get:

```<code>01001001 01101110 01100110 01101001 01101110 01101001 01110100 01111001
</code>```

This can be concatenated, and converted to the decimal value 5291279215216915577. Now that's a number we can work with...

The way you'll count down is:

Output the original string as a decimal number (as shown above)

Remove leading 0s in its binary representation (if any)

Toggle the bits in the binary representation (1->0, 0->1)

Output the number in decimal

Repeat steps 2-4 as until you reach 0.

Challenge:

Create a program or function that takes a string as input, and outputs (on any suitable format) the numbers you'll get when performing the procedure above.

Test case:

I think the challenge will be fairly easy to understand, even though it's only one test case. I'll use Inf instead of Infinity to keep this fairly short.

```<code>Inf
4812390  (10010010110111001100110)
3576217  ( 1101101001000110011001)
618086   (   10010110111001100110)
430489   (    1101001000110011001)
93798    (      10110111001100110)
37273    (       1001000110011001)
28262    (        110111001100110)
4505     (          1000110011001)
3686     (           111001100110)
409      (              110011001)
102      (                1100110)
25       (                  11001)
6        (                    110)
1        (                      1)
0        (                      0)
</code>```

```<code>Input: Inf
Output:
4812390, 3576217, 618086, 430489, 93798, 37273, 28262, 4505, 3686, 409, 102, 25, 6, 1, 0
</code>```

```<code>Input: Infinity
Output:
5291279215216915577, 3932092821637860230, 679593196789527673, 473328307817319302, 103132444486104185, 40982743589751686, 31074850448176249, 4953946570787718, 4053252683953273, 450346943417222, 112603010004089, 28134478351238, 7049893737593, 1746199284614, 452823970937, 96931842950, 40507110521, 28212366214, 6147372153, 2442562438, 1852404857, 295078790, 241792121, 26643334, 6911097, 1477510, 619641, 428934, 95353, 35718, 29817, 2950, 1145, 902, 121, 6, 1, 0
</code>```

Your code must support strings that can be represented as a binary number up to the limit of your language. All strings will only contain printable ASCII-characters from 32-126 (space to tilde).

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Python 2, <s>89</s> <s>82</s> <s>77</s> <s>76</s> 75 bytes

n=0
for c in input():n=n<<8|ord(c)
while 1:print n;n^=2**n.bit_length()-n/n

Test it on Ideone.

How it works

After initializing n to 0, the second line performs the string-to-integer conversion specified in the challenges as follows.

In each step, n is shifted 8 units to the left, then bitwise OR-ed with the the code point of the next character c. For input Inf, this goes as follows.

n                                  0
a = n<<8                           0
b = 'I'                      1001001
n = a ^ b                    1001001
a = n<<8             100100100000000
b = 'n'                      1101110
n = a ^ b            100100101101110
a = n<<8     10010010110111000000000
b = 'f'                      1100110
n = a ^ b    10010010110111001100110

Now we're ready to generate the output. To invert the bits of n, we proceed as follows.

First, we compute the bits in n's binary representation without leading zeroes. Let's call the result k. Then, we compute the kk power of 2, which has k+1 binary digits: a single 1, followed by k 0's. We subtract 1 from the result, yielding a number composed of k ones, which we then XOR with n to invert its bits. For input inf this goes as follows.

n         4812390   10010010110111001100110
k              23
t = 2**k           100000000000000000000000
t -= 1              11111111111111111111111
n ^= t    3576217    1101101001000110011001
k              22
t = 2**k            10000000000000000000000
t -= 1               1111111111111111111111
n ^= t     618086      10010110111001100110
.
.
.
n               6                       110
k               3
t = 2**k                               1000
t -= 1                                  111
n ^= t          1                         1
k               1
t = 2**k                                 10
t -= 1                                    1
n ^= t          0                         0

On additional hurdle in the implementation is that we have to print n before the first step, after the last step, and in all steps in between. Python doesn't have do-while loops and a single print statement costs 8 bytes, so we do the following instead.

In the straightforward implementation of the update step, i.e.,

while n:print n;n^=2**n.bit_length()-1
print n

we replace the loop with an infinite one (while 1) and compute the 1 in the loop as n/n. This is equivalent while n > 0.

Once n = 0, we stay in the loop, print the state once more, then try to update it. However, 0/0 triggers a ZeroDivisionError, breaking out of the loop and exiting with an error. Note that this causes stray output to STDERR, which is allowed by default.

ContentLicense: CC BY-SA 3.0


Title: Count down from "Infinity"

Body:
Perl, 65 bytes

53 bytes code + 12 for -Mbigint -p.

Thanks to @Dada for saving me 13 bytes!

$_=unpack"B*";say(0+"0b$_"),s/^0+//,y/10/01/while$_>0

Fairly straightforward approach, only different to most of these is that the number is stored as binary and printed out in decimal. I'm sure it can be improved, perhaps with storing details in an array. -Mbigint is a bit inconvenient but necessary.

Usage

echo -n 'Inf' | perl -Mbigint -pE'$_=unpack"B*";say(0+"0b$_"),s/^0+//,y/10/01/while$_>0'
4812390
3576217
618086
430489
93798
37273
28262
4505
3686
409
102
25
6
1
0

echo -n 'Infinity' | perl -Mbigint -pE'$_=unpack"B*";say(0+"0b$_"),s/^0+//,y/10/01/while$_>0'
5291279215216915577
3932092821637860230
679593196789527673
473328307817319302
103132444486104185
40982743589751686
31074850448176249
4953946570787718
4053252683953273
450346943417222
112603010004089
28134478351238
7049893737593
1746199284614
452823970937
96931842950
40507110521
28212366214
6147372153
2442562438
1852404857
295078790
241792121
26643334
6911097
1477510
619641
428934
95353
35718
29817
2950
1145
902
121
6
1
0


答:
JavaScript, 82 bytes

Saved a byte thanks to @Arnuald

for(y of prompt(n=0))n=n<<8|y.charCodeAt()
for(;alert(n)|n;)for(i=1;i<=n;i*=2)n^=i```
</div>
</div>
</p>

<p>One of the very few times when a full program outperforms a function (and ES6 does not outperform ES5)...</p>

<hr>

<p>The above supports up to 4-letter words. Add 4 bytes to support up to 6-letter words:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>for(y of prompt(n=0))n=n*256+y.charCodeAt()
for(;alert(n)|n;n=i-n-1)for(i=1;i<=n;)i*=2</code>```

Title: Count down from "Infinity"

Body:
JavaScript, 82 bytes

Saved a byte thanks to @Arnuald

for(y of prompt(n=0))n=n<<8|y.charCodeAt()
for(;alert(n)|n;)for(i=1;i<=n;i*=2)n^=i

One of the very few times when a full program outperforms a function (and ES6 does not outperform ES5)...

The above supports up to 4-letter words. Add 4 bytes to support up to 6-letter words:

for(y of prompt(n=0))n=n*256+y.charCodeAt()
for(;alert(n)|n;n=i-n-1)for(i=1;i<=n;)i*=2


问:
Trick or Treat polyglot
Since Halloween is coming up I thought I might start a fun little code golf challenge!

The challenge is quite simple. You have to write a program that outputs either trick or treat.

"The twist?" you may ask. Well let me explain:

Your program has to do the following:

Be compilable/runnable in two different languages. Different versions of the same language don't count.

When you run the program in one language it should output trick and the other should output treat. The case is irrelevant and padding the string with whitespace characters are allowed (see examples).

This is code-golf,  so the solution with the fewest bytes wins.

A few explanations:

Valid outputs (Just for the words not for running the code in the two languages. Also adding quotes to signalize the beginning or end of the output. Do not include them in your solution!):

```<code>"trick"

"Treat"

"    TReAt"

"
     tRICk          "
</code>```

Invalid outputs:

```<code>"tri ck"

"tr
eat"

"trck"
</code>```

I'm interested to see what you can come up with! Happy Golfing!

I'd like to note that this is my first challenge so if you have suggestions on this question please leave them in the form of a comment.

Leaderboards

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

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

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

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

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

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

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

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

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

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

```

答:
HTML / JavaScript (ES6), 28 bytes

```<code>trick<alert`treat`;var trick
</code>```

Test HTML | Test JS

Explanation

HTML is a lot like ///: it writes out any plain text, ignoring anything after a < until it gets to a >. Since there are no >s, it just writes "trick".

JS is simple: alert`treat`. However, to avoid a ReferenceError for trick not being defined, we have to add a var trick to tell JS that trick is really supposed to be there.

I wanted to add CSS that "prints" or, but it seems to be impossible:

If the CSS is before the <, it gets written to the HTML document.

If the CSS is after the <, it finds a syntax error and stops before running.

Title: Trick or Treat polyglot

Body:
HTML / JavaScript (ES6), 28 bytes

trick<alert`treat`;var trick

Test HTML | Test JS

Explanation

HTML is a lot like ///: it writes out any plain text, ignoring anything after a < until it gets to a >. Since there are no >s, it just writes "trick".

JS is simple: alert`treat`. However, to avoid a ReferenceError for trick not being defined, we have to add a var trick to tell JS that trick is really supposed to be there.

I wanted to add CSS that "prints" or, but it seems to be impossible:

If the CSS is before the <, it gets written to the HTML document.

If the CSS is after the <, it finds a syntax error and stops before running.


答:
PowerShell v2+, 158 bytes

```<code>for($a=-join([char[]]$args[0]|%{([int][convert]::ToString(+$_,2)).ToString('0'*8)});$a){[convert]::ToInt64($a,2);$a=$a.TrimStart('0')-split0-replace1,0-join1}
</code>```

Yeah, so, converting bases in PowerShell is really sucky. And we get to do it twice here.

OK, so this is just a for loop on $a -- i.e., we loop so long as $a exists. We'll eventually reach an empty string (which is falsey), so that's how we'll terminate.

The setup of the loop, $a=-join([char[]]$args[0]|%{([int][convert]::ToString(+$_,2)).ToString('0'*8)}), takes the input $args[0], casts it as a char-array, and loops through each character. We use the .NET [convert]::ToString(int,base) to convert each to a binary string. However, that doesn't include leading zeros, so we need to re-cast that string as an [int] and call its .ToString() method with 8 zeros as the mask. Then those strings are encapsulated in parens and -joined together, then saved into $a.

Inside the loop, we [convert]::ToInt64(string,base) to convert the binary number to a decimal number. That gets left on the pipeline and is subsequently flushed when the loop resets (and therefore implicitly printed). The next section performs the calculations -- we .TrimStart() to remove any leading zeros, -split0 to split on zeros and get a string-array of 1s, -replace those ones with zeros, and finally -join the array back together with 1s. Then, the loop begins again.

```<code>PS C:\Tools\Scripts\golfing> .\count-down-from-infinity.ps1 'PPCG'
1347437383
800046264
273695559
263175352
5260103
3128504
1065799
1031352
17223
15544
839
184
71
56
7
0
</code>```

Title: Count down from "Infinity"

Body:
PowerShell v2+, 158 bytes

for($a=-join([char[]]$args[0]|%{([int][convert]::ToString(+$_,2)).ToString('0'*8)});$a){[convert]::ToInt64($a,2);$a=$a.TrimStart('0')-split0-replace1,0-join1}

Yeah, so, converting bases in PowerShell is really sucky. And we get to do it twice here.

OK, so this is just a for loop on $a -- i.e., we loop so long as $a exists. We'll eventually reach an empty string (which is falsey), so that's how we'll terminate.

The setup of the loop, $a=-join([char[]]$args[0]|%{([int][convert]::ToString(+$_,2)).ToString('0'*8)}), takes the input $args[0], casts it as a char-array, and loops through each character. We use the .NET [convert]::ToString(int,base) to convert each to a binary string. However, that doesn't include leading zeros, so we need to re-cast that string as an [int] and call its .ToString() method with 8 zeros as the mask. Then those strings are encapsulated in parens and -joined together, then saved into $a.

Inside the loop, we [convert]::ToInt64(string,base) to convert the binary number to a decimal number. That gets left on the pipeline and is subsequently flushed when the loop resets (and therefore implicitly printed). The next section performs the calculations -- we .TrimStart() to remove any leading zeros, -split0 to split on zeros and get a string-array of 1s, -replace those ones with zeros, and finally -join the array back together with 1s. Then, the loop begins again.

PS C:\Tools\Scripts\golfing> .\count-down-from-infinity.ps1 'PPCG'
1347437383
800046264
273695559
263175352
5260103
3128504
1065799
1031352
17223
15544
839
184
71
56
7
0


问:
Interlace strings
Your challenge is to write a program or function that, when given two strings of equal length, swaps every other character and outputs/returns the resulting strings in either order.

Examples

```<code>"Hello," "world!" --> "Hollo!" "werld,"
"code" "golf" --> "codf" "gole"
"happy" "angry" --> "hnpry" "aagpy"
"qwerty" "dvorak" --> "qvertk" "dworay"
"1, 2, 3" "a, b, c" --> "1, b, 3" "a, 2, c"
"3.141592653589" "2.718281828459" --> "3.111291623489" "2.748582858559"
"DJMcMayhem" "trichoplax" --> "DrMcMoylex" "tJichapham"
"Doorknob" "Downgoat" --> "Doonkoot" "Dowrgnab"
"Halloween" "Challenge" --> "Hhlloeegn" "Caallwnee"
</code>```

Rules

The strings will only contain ASCII chars (32-126).

The strings will always be the same length, and will never be empty.

You may accept input in any suitable format: separate parameters, items in an array, separated by one or more newlines, even concatenated. The only restriction is that one string must come fully before the other (e.g. a1\nb2\nc3 for "abc", "123" is invalid).

The output may be in either order (i.e. you can start swapping from the first or the second char), and in any valid format mentioned above. (2-item array, separated by newline(s), concatenated, etc.)

Scoring

This is code-golf, so the shortest code in bytes for each language wins.

答:
Java, 68 bytes

```<code>(a,b)->{for(int i=a.length;--i>0;){char t=a[--i];a[i]=b[i];b[i]=t;}}
</code>```

Ungolfed and testing

```<code>import java.util.Arrays;
import java.util.Collection;
import java.util.function.BiConsumer;

public class Main {

  static BiConsumer<char[], char[]> func = (left, right) -> {
      for (int i = left.length; --i > 0;) {
        char temp = left[--i];
        left[i] = right[i];
        right[i] = temp;
      }
    };

  public static void main(String[] args) {
    test("Hello,","world!", "Hollo!", "werld,");
    test("code", "golf", "codf", "gole");
    test("happy", "angry", "hnpry", "aagpy");
  }

  private static void test(String left, String right, String x, String y) {
    char[] leftChars = left.toCharArray();
    char[] rightChars = right.toCharArray();
    func.accept(leftChars, rightChars);
    Collection mixed = Arrays.asList(new String(leftChars), new String(rightChars));
    if (mixed.containsAll(Arrays.asList(x, y))) {
      System.out.println("OK");
    } else {
      System.out.printf("NOK: %s, %s -> %s%n", left, right, mixed);
    }
  }
}
</code>```

Title: Interlace strings

Body:
Java, 68 bytes

(a,b)->{for(int i=a.length;--i>0;){char t=a[--i];a[i]=b[i];b[i]=t;}}

Ungolfed and testing

import java.util.Arrays;
import java.util.Collection;
import java.util.function.BiConsumer;

public class Main {

  static BiConsumer<char[], char[]> func = (left, right) -> {
      for (int i = left.length; --i > 0;) {
        char temp = left[--i];
        left[i] = right[i];
        right[i] = temp;
      }
    };

  public static void main(String[] args) {
    test("Hello,","world!", "Hollo!", "werld,");
    test("code", "golf", "codf", "gole");
    test("happy", "angry", "hnpry", "aagpy");
  }

  private static void test(String left, String right, String x, String y) {
    char[] leftChars = left.toCharArray();
    char[] rightChars = right.toCharArray();
    func.accept(leftChars, rightChars);
    Collection mixed = Arrays.asList(new String(leftChars), new String(rightChars));
    if (mixed.containsAll(Arrays.asList(x, y))) {
      System.out.println("OK");
    } else {
      System.out.printf("NOK: %s, %s -> %s%n", left, right, mixed);
    }
  }
}


答:
Python 3, <s>99</s> 95 bytes

```<code>x=int.from_bytes(bytes(input(),'utf-8'),'big')
while x:print(x);x^=2**x.bit_length()-1
print(0)
</code>```

Main idea is to convert string to bytes to to number. Each iteration print the output and XOR with all 1s to progress towards zero.

Title: Count down from "Infinity"

Body:
Python 3, <s>99</s> 95 bytes

x=int.from_bytes(bytes(input(),'utf-8'),'big')
while x:print(x);x^=2**x.bit_length()-1
print(0)

Main idea is to convert string to bytes to to number. Each iteration print the output and XOR with all 1s to progress towards zero.


答:
Retina, 116 bytes

Byte count assumes ISO 8859-1 encoding. Line 5 contains non-printable bytes. It's T`\x00-\xFF.

```<code>-2`
±
s{`±(.)
$&$1
}T`-`_o`±.
[^±]+
$.&
±

\d+
$*
+`(1+)\1
${1}0
01
1

{*(`1
01
+`10
011
^0+

)M`1
^0+

T`01`10
</code>```

Try it online

Don't try this with input longer than two characters. (It times out using the online interpreter.) We gotta convert the binary to unary before decimal. :D

Unfortunately, there's a trailing zero and linefeed, but I decided to assume that was okay because the output is still correct.

Explanation

```<code>-2`         # Convert ASCII to decimal (ord)
±
s{`±(.)
$&$1
}T`-`_o`±.
[^±]+
$.&
±

\d+         # Decimal to binary
$*
+`(1+)\1
${1}0
01
1

{*(`1       # Loop; Loop print and undo; Convert binary to unary
01
+`10
011
^0+

)M`1        # Unary to decimal; End print and undo
^0+         # Remove leading zeros

T`01`10     # Flip bits; (implicit loop end)
</code>```

Title: Count down from "Infinity"

Body:
Retina, 116 bytes

Byte count assumes ISO 8859-1 encoding. Line 5 contains non-printable bytes. It's T`\x00-\xFF.

-2`
±
s{`±(.)
$&$1
}T`-`_o`±.
[^±]+
$.&
±

\d+
$*
+`(1+)\1
${1}0
01
1

{*(`1
01
+`10
011
^0+

)M`1
^0+

T`01`10

Try it online

Don't try this with input longer than two characters. (It times out using the online interpreter.) We gotta convert the binary to unary before decimal. :D

Unfortunately, there's a trailing zero and linefeed, but I decided to assume that was okay because the output is still correct.

Explanation

-2`         # Convert ASCII to decimal (ord)
±
s{`±(.)
$&$1
}T`-`_o`±.
[^±]+
$.&
±

\d+         # Decimal to binary
$*
+`(1+)\1
${1}0
01
1

{*(`1       # Loop; Loop print and undo; Convert binary to unary
01
+`10
011
^0+

)M`1        # Unary to decimal; End print and undo
^0+         # Remove leading zeros

T`01`10     # Flip bits; (implicit loop end)


问:
Convert to Bubble Letters
So I was playing around with my compose key, and found some cool things, one of them being that by pressing compose + ( + alphanumeric + ), you get that character inside a bubble, like so: ⓐ.

Your task in this challenge is simple, to convert ordinary text to bubble letter text.

Here are the ascii chars, the bubble characters and their Unicode code points:

```<code>0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
⓪①②③④⑤⑥⑦⑧⑨ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ
9450 9312 9313 9314 9315 9316 9317 9318 9319 9320 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423
</code>```

Your input will contain only printable ascii characters, and if a character cannot be bubbleified, leave it as is.

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

Note: This is not isomorphic to my earlier challenge about small-caps conversion since unlike small-caps, bubble letters are in a mostly contiguous segment of code-points, allowing for more interesting approaches.

答:
05AB1E, 19 bytes

Uses CP-1252 encoding.

```<code>žKš52Ý86+8Ý«9312+ç‡
</code>```

Try it online!

Explanation

```<code>žK                    # Push the string "a-zA-Z0-9"
  š                   # switch case: "A-Za-z0-9"
   52Ý                # push range [0 ... 52]
      86+             # add 86: [86 ... 138]
         8Ý«          # concatenate with range [0 ... 8]: [86 ... 138, 0 ... 8]
            9312+     # add 9312: [9398 ... 9450, 9312 ... 9320]
                 ç    # convert to char: ['Ⓐ', ... 'Ⓩ', 'ⓐ', ..., 'ⓩ', '⓪', ..., '⑨']
                  ‡   # transliterate alphabet to bubble alphabet
</code>```

Title: Convert to Bubble Letters

Body:
05AB1E, 19 bytes

Uses CP-1252 encoding.

žKš52Ý86+8Ý«9312+ç‡

Try it online!

Explanation

žK                    # Push the string "a-zA-Z0-9"
  š                   # switch case: "A-Za-z0-9"
   52Ý                # push range [0 ... 52]
      86+             # add 86: [86 ... 138]
         8Ý«          # concatenate with range [0 ... 8]: [86 ... 138, 0 ... 8]
            9312+     # add 9312: [9398 ... 9450, 9312 ... 9320]
                 ç    # convert to char: ['Ⓐ', ... 'Ⓩ', 'ⓐ', ..., 'ⓩ', '⓪', ..., '⑨']
                  ‡   # transliterate alphabet to bubble alphabet


答:
R, <s>124</s> 91 characters

Takes input from stdin. Probably can be golfed with some cleverness. Saved some bytes by replacing the list of bubble characters with UTF code points.

```<code>chartr(paste(c(1:9,LETTERS,letters,0),collapse=""),intToUtf8(c(0:8,86:138)+9312),scan(,""))
</code>```

Title: Convert to Bubble Letters

Body:
So I was playing around with my compose key, and found some cool things, one of them being that by pressing compose + ( + alphanumeric + ), you get that character inside a bubble, like so: ⓐ.

Your task in this challenge is simple, to convert ordinary text to bubble letter text.

Here are the ascii chars, the bubble characters and their Unicode code points:

```<code>0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
⓪①②③④⑤⑥⑦⑧⑨ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ
9450 9312 9313 9314 9315 9316 9317 9318 9319 9320 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423
</code>```

Your input will contain only printable ascii characters, and if a character cannot be bubbleified, leave it as is.

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

Note: This is not isomorphic to my earlier challenge about small-caps conversion since unlike small-caps, bubble letters are in a mostly contiguous segment of code-points, allowing for more interesting approaches.

Body:
R, <s>124</s> 91 characters

Takes input from stdin. Probably can be golfed with some cleverness. Saved some bytes by replacing the list of bubble characters with UTF code points.

chartr(paste(c(1:9,LETTERS,letters,0),collapse=""),intToUtf8(c(0:8,86:138)+9312),scan(,""))


答:
Python 3, 107.

This borrows part of its algorithm from nedla2004's answer.

```<code>lambda x:list(map(lambda p:chr(ord(p)+(((9327+6*('@'<p<'[')*p.isalpha(),9402)[p<'1'],9263)['0'<p<':'])),x))
</code>```

Title: Convert to Bubble Letters

Body:
Python 3, 107.

This borrows part of its algorithm from nedla2004's answer.

lambda x:list(map(lambda p:chr(ord(p)+(((9327+6*('@'<p<'[')*p.isalpha(),9402)[p<'1'],9263)['0'<p<':'])),x))


问:
Next Friday the 13th
What is the shortest program that can predict the next time Friday will fall on the 13th day of the month?

Must be an complete functioning program (not just a function/subroutine)

Must print out date in the following format: YYYY-MM-DD

Allow user to provide a start date either as a command line argument or through STDIN

If user provides no start date, use today as the start date.

If the start date is a Friday the 13th, the program should find the next Friday the 13th.

If I were to run the program today (Feb 16 2011) I should get the following output.

```<code>$ ./fr13th 2013-05-09
2013-09-13
$ ./fr13th 2007-06-29
2007-07-13
$ ./fr13th 2007-07-13
2008-06-13
$ ./fr13th
2011-05-13
</code>```

答:
Python - 166 chars

Reads from stdin, so you need to feed a blank line if you want todays date

```<code>from datetime import*
D=datetime
e=timedelta(1)
I=raw_input()
d=e+(I and D.strptime(I,"%Y-%m-%d")or D.now())
while(d.weekday()+1)*d.day-65:d+=e
print d.strftime("%F")
</code>```

ContentLicense: CC BY-SA 2.5

Title: Next Friday the 13th

Body:
Python - 166 chars

Reads from stdin, so you need to feed a blank line if you want todays date

from datetime import*
D=datetime
e=timedelta(1)
I=raw_input()
d=e+(I and D.strptime(I,"%Y-%m-%d")or D.now())
while(d.weekday()+1)*d.day-65:d+=e
print d.strftime("%F")


答:
C, <s>147</s> <s>135</s> <s>133</s> <s>125</s> <s>122</s> <s>121</s> <s>117</s> <s>115</s> 103 bytes

Saved 5 bytes thanks to @Cyoce!

Saved 2 bytes thanks to @Cyoce and @cleblanc!

Saved 12 bytes thanks to @ceilingcat

i,n;main(p,v)char**v;{while(*v[1])i=i*256+*v[1]++;for(;printf("%d\n",n=i),i;i^=p-1)for(p=2;n/=2;)p*=2;}
```

<p>Ungolfed:</p>

<pre class="lang-c prettyprint-override"><code>int i;
int main (c,v) {
    char**v;
    while (*v[1]) /* put first command line argument into i as binary */
        i = i*256 + *v[1]++;
    while (i != 0) {
        printf("%d\n",i);
        int p = 2,n = i;
        while (n /= 2) /* calculate smallest power of 2 > i */
            p *= 2;
        i ^= p - 1; /* flip bits */
    }
}
</code>```

Title: Count down from "Infinity"

Body:
C, <s>147</s> <s>135</s> <s>133</s> <s>125</s> <s>122</s> <s>121</s> <s>117</s> <s>115</s> 103 bytes

Saved 5 bytes thanks to @Cyoce!

Saved 2 bytes thanks to @Cyoce and @cleblanc!

Saved 12 bytes thanks to @ceilingcat

i,n;main(p,v)char**v;{while(*v[1])i=i*256+*v[1]++;for(;printf("%d\n",n=i),i;i^=p-1)for(p=2;n/=2;)p*=2;}

Ungolfed:

int i;
int main (c,v) {
    char**v;
    while (*v[1]) /* put first command line argument into i as binary */
        i = i*256 + *v[1]++;
    while (i != 0) {
        printf("%d\n",i);
        int p = 2,n = i;
        while (n /= 2) /* calculate smallest power of 2 > i */
            p *= 2;
        i ^= p - 1; /* flip bits */
    }
}


问:
Run-Length Encoding
Write a program uses run-length encoding to shorten a list of non-negative integers it has to read in.

You can assume the non-negative integers can fit in 32bit signed integers.

Input Format

The length, n, of the list on the first line.

On the second line, a space-separated list of integers representing the list of integers.

Output Format

A space separated list of integers. The first 2 integers represent the first run, the next 2 integers the second run and so on. For each pair of integers representing a run, the first integer represents the length of the run and the second represents the value of the integer in the run.

Sample Input

1.

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

2.

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

Sample Output

1.

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

2.

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

Limits

```<code>0<n<10000
</code>```

答:
Retina, 23 bytes

Thanks to @MartinEnder who helped me save 23 (!!) bytes and helped me understand some new features to (hopefully) produce better examples of Retina code in the future!

```<code>A1`
(\d+)( \1|)*
$#2 $1
</code>```

Explanation

The first line is AntiGrep with a limit of 1 to remove the first line.  Then we match any integer followed by either a space and the same integer or nothing which handles our count correctly, so we can just replace with the number of matches of group 2 ($#2), and the original integer ($1).

Try it online!

Title: Run-Length Encoding

Body:
Retina, 23 bytes

Thanks to @MartinEnder who helped me save 23 (!!) bytes and helped me understand some new features to (hopefully) produce better examples of Retina code in the future!

A1`
(\d+)( \1|)*
$#2 $1

Explanation

The first line is AntiGrep with a limit of 1 to remove the first line.  Then we match any integer followed by either a space and the same integer or nothing which handles our count correctly, so we can just replace with the number of matches of group 2 ($#2), and the original integer ($1).

Try it online!


答:
APL, 12

```<code>{↓(⍳⍴⊃⍵)⊖↑⍵}
</code>```

Explanation: {...} defines a function, ⍵ is the right argument.
The take (↑) creates a matrix out of the two strings, then rotates each column (⊖) n times, where n is the part in parenthesis (⍳⍴⊃⍵). That's defined as the iota of the length of the first argument. (Ex: length=5 ==> 1 2 3 4 5).
So first column is rotated once, second twice (getting back to original positions), third column three times, etc...

Try it at tryapl.org

Title: Interlace strings

Body:
Your challenge is to write a program or function that, when given two strings of equal length, swaps every other character and outputs/returns the resulting strings in either order.

Examples

```<code>"Hello," "world!" --> "Hollo!" "werld,"
"code" "golf" --> "codf" "gole"
"happy" "angry" --> "hnpry" "aagpy"
"qwerty" "dvorak" --> "qvertk" "dworay"
"1, 2, 3" "a, b, c" --> "1, b, 3" "a, 2, c"
"3.141592653589" "2.718281828459" --> "3.111291623489" "2.748582858559"
"DJMcMayhem" "trichoplax" --> "DrMcMoylex" "tJichapham"
"Doorknob" "Downgoat" --> "Doonkoot" "Dowrgnab"
"Halloween" "Challenge" --> "Hhlloeegn" "Caallwnee"
</code>```

Rules

The strings will only contain ASCII chars (32-126).

The strings will always be the same length, and will never be empty.

You may accept input in any suitable format: separate parameters, items in an array, separated by one or more newlines, even concatenated. The only restriction is that one string must come fully before the other (e.g. a1\nb2\nc3 for "abc", "123" is invalid).

The output may be in either order (i.e. you can start swapping from the first or the second char), and in any valid format mentioned above. (2-item array, separated by newline(s), concatenated, etc.)

Scoring

This is code-golf, so the shortest code in bytes for each language wins.

Body:
APL, 12

{↓(⍳⍴⊃⍵)⊖↑⍵}

Explanation: {...} defines a function, ⍵ is the right argument.
The take (↑) creates a matrix out of the two strings, then rotates each column (⊖) n times, where n is the part in parenthesis (⍳⍴⊃⍵). That's defined as the iota of the length of the first argument. (Ex: length=5 ==> 1 2 3 4 5).
So first column is rotated once, second twice (getting back to original positions), third column three times, etc...

Try it at tryapl.org


问:
Count up folks!

Introduction

It may sound strange, but we haven't got ONE challenge for counting from 1 to n, inclusive.

This is not the same thing. That one is a (closed) not well-explained challenge.

This is not the same thing. That one is about counting up indefinitely.

Challenge

Write a program or function that prints every integer from 1 to n inclusive.

Rules

You can get n any way.

You can assume that n will always be a positive integer.

You can get n in any base, but you should always output in decimal.

Output must be separated by any character (or pattern) not in 0123456789. Non-decimal leading or trailing characters are allowed (for example when using arrays such as [1, 2, 3, 4, 5, 6]).

Standard loopholes are denied.

We want to find the shortest approach in each language, not the shortest language, so I will not accept any answer.

You must update your answer(s) after this edit, answers posted before the last edit must comply with the change rule about standard loopholes (I didn't want to deny them, but I didn't want to make the community roar, so I denied them).

You can use any post-dating language version (or language). You cannot use any language or language version made just for this challenge.

Bonuses

20%

Your program must be able to count at least up to 18446744073709551615 (2^64-1). For example, if a new datatype is the only way to support big integers, you must construct it. If your language does not have any way to support huge integers up to 2^64-1, the upper limit of that particular language must be supported instead.

EDIT: I've changed the limit from 2^64 to 2^64-1 to allow more answers.

EDIT: I made the 2^64-1 rule a bonus, since there has not been much interest in this challenge. If your answer supports 2^64-1, you can now edit it to include the bonus. Also, you can post an answer not supporting it, if it is shorter.

答:
SQL, 108 Bytes

Golfed:

```<code>CREATE PROCEDURE C @n INT AS BEGIN DECLARE @a INT;SET @a=1;WHILE @a<=@n BEGIN PRINT @a;SET @a=@a+1;END;END
GO
</code>```

(It fails if I put it all on one line!)

Ungolfed:

```<code>CREATE PROCEDURE C
@n INT
AS
BEGIN
DECLARE @a INT;
SET @a=1;
    WHILE @a<=@n
        BEGIN
        PRINT @a;
        SET @a=@a+1;
    END;
END
GO
</code>```

Usage:

```<code>EXEC C 5
</code>```

Output:

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

Title: Count up folks!

Body:
SQL, 108 Bytes

Golfed:

CREATE PROCEDURE C @n INT AS BEGIN DECLARE @a INT;SET @a=1;WHILE @a<=@n BEGIN PRINT @a;SET @a=@a+1;END;END
GO

(It fails if I put it all on one line!)

Ungolfed:

CREATE PROCEDURE C
@n INT
AS
BEGIN
DECLARE @a INT;
SET @a=1;
    WHILE @a<=@n
        BEGIN
        PRINT @a;
        SET @a=@a+1;
    END;
END
GO

Usage:

EXEC C 5

Output:

1
2
3
4
5


答:
Labyrinth, 41 29 23 14 bytes

```<code>?}):
 \ !
@"({
</code>```

Try it online!

Takes the input number and moves it to the auxiliary stack and increments an implicit zero on the main stack. Repeatedly duplicates the top of the stack, outputs the number, moves a copy of the input number from the aux stack and decrements it. If that number is zero, the program exits. Otherwise it outputs a newline and continues the loop.

Title: Count up folks!

Body:
Introduction

It may sound strange, but we haven't got ONE challenge for counting from 1 to n, inclusive.

This is not the same thing. That one is a (closed) not well-explained challenge.

This is not the same thing. That one is about counting up indefinitely.

Challenge

Write a program or function that prints every integer from 1 to n inclusive.

Rules

You can get n any way.

You can assume that n will always be a positive integer.

You can get n in any base, but you should always output in decimal.

Output must be separated by any character (or pattern) not in 0123456789. Non-decimal leading or trailing characters are allowed (for example when using arrays such as [1, 2, 3, 4, 5, 6]).

Standard loopholes are denied.

We want to find the shortest approach in each language, not the shortest language, so I will not accept any answer.

You must update your answer(s) after this edit, answers posted before the last edit must comply with the change rule about standard loopholes (I didn't want to deny them, but I didn't want to make the community roar, so I denied them).

You can use any post-dating language version (or language). You cannot use any language or language version made just for this challenge.

Bonuses

20%

Your program must be able to count at least up to 18446744073709551615 (2^64-1). For example, if a new datatype is the only way to support big integers, you must construct it. If your language does not have any way to support huge integers up to 2^64-1, the upper limit of that particular language must be supported instead.

EDIT: I've changed the limit from 2^64 to 2^64-1 to allow more answers.

EDIT: I made the 2^64-1 rule a bonus, since there has not been much interest in this challenge. If your answer supports 2^64-1, you can now edit it to include the bonus. Also, you can post an answer not supporting it, if it is shorter.

Body:
Labyrinth, 41 29 23 14 bytes

?}):
 \ !
@"({

Try it online!

Takes the input number and moves it to the auxiliary stack and increments an implicit zero on the main stack. Repeatedly duplicates the top of the stack, outputs the number, moves a copy of the input number from the aux stack and decrements it. If that number is zero, the program exits. Otherwise it outputs a newline and continues the loop.


答:
PHP, 26 bytes -20% = 20.8

<?=join(_,range(1,$argn));
```
<p>run as pipe with <code>-F</code>.</p>
<p>or</p>
<pre class="lang-php prettyprint-override"><code>while($i<$argn)echo++$i,_;
</code>```

prints one trailing delimiter; run as pipe with -nR.

Title: Count up folks!

Body:
PHP, 26 bytes -20% = 20.8

<?=join(_,range(1,$argn));

run as pipe with -F.

or

while($i<$argn)echo++$i,_;

prints one trailing delimiter; run as pipe with -nR.


答:
Ruby, <s>104</s> <s>101</s> <s>100</s> <s>81</s> <s>80</s> 65 bytes

19 bytes saved thanks to @WayneConrad!

15 Bytes saved thanks to @philomory!

1 byte saved thanks to @LeeW!

p n=$*[0].unpack('B*')[0].to_i(2)
p n^=2**n.bit_length-1while n>0
```

Takes input via command line arguments.

Inspired by @JimmyJohnson's Python answer

Title: Count down from "Infinity"

Body:
Seems like an impossible task right? Well, it's actually not that hard. If we write the word Infinity as 8-bit binary ASCII code, we'll get:

```<code>01001001 01101110 01100110 01101001 01101110 01101001 01110100 01111001
</code>```

This can be concatenated, and converted to the decimal value 5291279215216915577. Now that's a number we can work with...

The way you'll count down is:

Output the original string as a decimal number (as shown above)

Remove leading 0s in its binary representation (if any)

Toggle the bits in the binary representation (1->0, 0->1)

Output the number in decimal

Repeat steps 2-4 as until you reach 0.

Challenge:

Create a program or function that takes a string as input, and outputs (on any suitable format) the numbers you'll get when performing the procedure above.

Test case:

I think the challenge will be fairly easy to understand, even though it's only one test case. I'll use Inf instead of Infinity to keep this fairly short.

```<code>Inf
4812390  (10010010110111001100110)
3576217  ( 1101101001000110011001)
618086   (   10010110111001100110)
430489   (    1101001000110011001)
93798    (      10110111001100110)
37273    (       1001000110011001)
28262    (        110111001100110)
4505     (          1000110011001)
3686     (           111001100110)
409      (              110011001)
102      (                1100110)
25       (                  11001)
6        (                    110)
1        (                      1)
0        (                      0)
</code>```

```<code>Input: Inf
Output:
4812390, 3576217, 618086, 430489, 93798, 37273, 28262, 4505, 3686, 409, 102, 25, 6, 1, 0
</code>```

```<code>Input: Infinity
Output:
5291279215216915577, 3932092821637860230, 679593196789527673, 473328307817319302, 103132444486104185, 40982743589751686, 31074850448176249, 4953946570787718, 4053252683953273, 450346943417222, 112603010004089, 28134478351238, 7049893737593, 1746199284614, 452823970937, 96931842950, 40507110521, 28212366214, 6147372153, 2442562438, 1852404857, 295078790, 241792121, 26643334, 6911097, 1477510, 619641, 428934, 95353, 35718, 29817, 2950, 1145, 902, 121, 6, 1, 0
</code>```

Your code must support strings that can be represented as a binary number up to the limit of your language. All strings will only contain printable ASCII-characters from 32-126 (space to tilde).

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Ruby, <s>104</s> <s>101</s> <s>100</s> <s>81</s> <s>80</s> 65 bytes

19 bytes saved thanks to @WayneConrad!

15 Bytes saved thanks to @philomory!

1 byte saved thanks to @LeeW!

p n=$*[0].unpack('B*')[0].to_i(2)
p n^=2**n.bit_length-1while n>0

Takes input via command line arguments.

Inspired by @JimmyJohnson's Python answer


Title: Count down from "Infinity"

Body:
C, <s>129</s> <s>120</s> <s>117</s> <S>110</S> <s>107</s> 105 Bytes

long long i,m,n;f(char*v){for(;*v;i<<=8,i+=*v++);for(;printf("%llu,",i),n=i;i^=m-1)for(m=2;n>>=1;m<<=1);}

Tested with

main (int c, char**v) {
    f(v[1]);
}

output

5291279215216915577,3932092821637860230,679593196789527673,473328307817319302,103132444486104185,40982743589751686,31074850448176249,4953946570787718,4053252683953273,450346943417222,112603010004089,28134478351238,7049893737593,1746199284614,452823970937,96931842950,40507110521,28212366214,6147372153,2442562438,1852404857,295078790,241792121,26643334,6911097,1477510,619641,428934,95353,35718,29817,2950,1145,902,121,6,1,0,


问:
Tips for Golfing in Brain-Flak
Brain-flak is a stack-based turing-tarpit language, written collaboratively between me, DJMcMayhem, and 1000000000.

Some users  are very experienced in the mysterious ways of Brain-Flak. So I thought it a good idea to set up this question as a way for us, and hopefully others too, to share our knowledge with the community and lower the bar of entry to this language "designed to be painful to use". And perhaps even teach those of us with more experience some new tricks.

So what tips do you have for golfing in brain-flak? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to brain-flak (e.g. "remove comments" is not an answer).

Please post one tip per answer.

答:
Finding modulus/remainder

Finding n modulo m is one of the basic arithmetic operations, important for many challenges. For cases m > 0 and n >= 0, the following 46-byte snippet may be used. It assumes that n is on top of the active stack with m the next one down, and replaces them with n mod m. It leaves the rest of the stacks intact.

```<code>({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})
</code>```

This annotated version shows the stack contents at some points in the program. ; separates the two stacks and . marks the active stack.

```<code>. n m;
({}(<>))<>
{   . m; r 0   (r = n - km)
    (({}))
    . m m; r 0
    {({}[()])<>}
    {}
}
m-n%m-1 m; . 0
{}<>([{}()]{})
. n%m;
</code>```

Title: Tips for Golfing in Brain-Flak

Body:
Finding modulus/remainder

Finding n modulo m is one of the basic arithmetic operations, important for many challenges. For cases m > 0 and n >= 0, the following 46-byte snippet may be used. It assumes that n is on top of the active stack with m the next one down, and replaces them with n mod m. It leaves the rest of the stacks intact.

({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})

This annotated version shows the stack contents at some points in the program. ; separates the two stacks and . marks the active stack.

. n m;
({}(<>))<>
{   . m; r 0   (r = n - km)
    (({}))
    . m m; r 0
    {({}[()])<>}
    {}
}
m-n%m-1 m; . 0
{}<>([{}()]{})
. n%m;


问:
Markov Chain Quine
A simple Markov Model will be used in this question. For more information about Markov Chains, see http://setosa.io/ev/markov-chains/.

Take a string. For this example, we will use the word:

```<code>reader
</code>```

Now, for each character, take the characters that appear after each occurence of the character in the string. (`^` represents the start of the string and `$` represents the end)

```<code>`^` -> {'r'}       # After the start of the string, there is an `r`.
'r' -> {'e', `$`}  # After the first `r` (*r*eader), there is an `e`
                   # after the second (reade*r*), there is the end of the string.
'e' -> {'a', 'r'}
'a' -> {'d'}
'd' -> {'e'}
</code>```

Now, starting from the start of the string, pick randomly from one of the characters in the next set. Append this character and then pick from the characters in its next set, and so on until you get to the end. Here are some example words:

```<code>r
rereader
rer
readereader
</code>```

If a character appears after another character multiple times, it is more likely to be chosen. For example, in cocoa can, after a c, there is a two thirds of a chance of getting an o and a one thirds chance of getting an a.

```<code>'c' -> {'o', 'o', 'a'}
</code>```

Challenge

Create a program that takes no input and outputs a random string generated using a Markov Chain, like above, where the input to the chain is the program's source.

The program must have at least two characters, two of which must be the same (To prevent "boring" chains that only have one output)

You can modify the model to use bytes instead of characters if you wish, but change "characters" to "bytes" in rule 1

The program should output strings randomly with the expected frequency in theory

This is code-golf, so the shortest program wins!

答:
Pip, 64 bytes

This was fun.

```<code>t:V Y\"m:"Yt@0T9=A OyY@>RC(t(Xy).'.)"ST["t:V Y"RPy";Vm"C9]\";Vm<tab>
</code>```

<tab> represents a literal tab character (0x09). Try it online!

How?

TL;DR: escaped-string syntax, repr, and eval.

For strings that need to contain literal " characters, Pip has escaped strings, using \" as the delimiter. A standard quine using escaped strings would look like this:

```<code>V Y\""V Y".RPy\"
</code>```

That is: Yank (storing as y) a string containing "V Y".RPy and eVal it. RPy takes the repr of y, to which we prepend the literal string V Y. Finally, output the result of the eval.

The structure of the Markov quine is similar, except that we want to save the code instead of outputting it and then do some stuff with it afterwards. t:V Y\"...\" assigns the eval result to t. Inside the eval'd code, m:"..." assigns a string of code to m, which we will evaluate at the end with Vm.

ST["t:V Y"RPy";Vm"C9] builds a list containing

```<code>"t:V Y"  Literal string
RPy      Repr(y)
";Vm"    Literal string
C9       Tab character
</code>```

and converts it to a string, which by default concatenates all the items. This section is equivalent to "V Y".RPy in the original quine. Since it is the last expression in the big eval string, its value is what the V operator returns, and thus what gets assigned to t.

Thus, after the eval and assignment, t is equal to the full code, and m contains

```<code>Yt@0T9=A OyY@>RC(t(Xy).'.)
</code>```

Now Vm evaluates that as code. Let's break down what happens.

```<code>                            We'll use y to hold the current character in the chain
Yt@0                        Yank first character of t into y (chain always starts there)
         Oy                 Output y without newline each time we...
    T9=A                    Loop till ASCII code of y equals 9 (tab)
                            Since there's only one literal tab, at the end of the program,
                              this satisfies the Markov chain ending requirement
                   Xy       Generate a regex that matches y
                  (  ).'.   Concatenate . to regex: now matches y followed by any character
                (t       )  Find all matches in t (returns a list)
              RC            Random choice from that list
           Y@>              Slice off the first character and yank the remaining one into y
</code>```

A couple notes:

Ending the code with a literal tab was shorter than doing a regex test for "next character or end of string."

The regex I used does not work properly if there are doubled characters in the code; for instance, applying it to xxy would return only xx and not xy in the matches. Fortunately, however, there are no doubled characters in this code, so it doesn't matter.

Title: Markov Chain Quine

Body:
Pip, 64 bytes

This was fun.

t:V Y\"m:"Yt@0T9=A OyY@>RC(t(Xy).'.)"ST["t:V Y"RPy";Vm"C9]\";Vm<tab>

<tab> represents a literal tab character (0x09). Try it online!

How?

TL;DR: escaped-string syntax, repr, and eval.

For strings that need to contain literal " characters, Pip has escaped strings, using \" as the delimiter. A standard quine using escaped strings would look like this:

V Y\""V Y".RPy\"

That is: Yank (storing as y) a string containing "V Y".RPy and eVal it. RPy takes the repr of y, to which we prepend the literal string V Y. Finally, output the result of the eval.

The structure of the Markov quine is similar, except that we want to save the code instead of outputting it and then do some stuff with it afterwards. t:V Y\"...\" assigns the eval result to t. Inside the eval'd code, m:"..." assigns a string of code to m, which we will evaluate at the end with Vm.

ST["t:V Y"RPy";Vm"C9] builds a list containing

"t:V Y"  Literal string
RPy      Repr(y)
";Vm"    Literal string
C9       Tab character

and converts it to a string, which by default concatenates all the items. This section is equivalent to "V Y".RPy in the original quine. Since it is the last expression in the big eval string, its value is what the V operator returns, and thus what gets assigned to t.

Thus, after the eval and assignment, t is equal to the full code, and m contains

Yt@0T9=A OyY@>RC(t(Xy).'.)

Now Vm evaluates that as code. Let's break down what happens.

                            We'll use y to hold the current character in the chain
Yt@0                        Yank first character of t into y (chain always starts there)
         Oy                 Output y without newline each time we...
    T9=A                    Loop till ASCII code of y equals 9 (tab)
                            Since there's only one literal tab, at the end of the program,
                              this satisfies the Markov chain ending requirement
                   Xy       Generate a regex that matches y
                  (  ).'.   Concatenate . to regex: now matches y followed by any character
                (t       )  Find all matches in t (returns a list)
              RC            Random choice from that list
           Y@>              Slice off the first character and yank the remaining one into y

A couple notes:

Ending the code with a literal tab was shorter than doing a regex test for "next character or end of string."

The regex I used does not work properly if there are doubled characters in the code; for instance, applying it to xxy would return only xx and not xy in the matches. Fortunately, however, there are no doubled characters in this code, so it doesn't matter.


答:
Labyrinth/Perl, 38 bytes

As cat -v:

```<code>$_=116.114.105.99.107.$@^"^@^@^L^B^_";print
</code>```

Where ^@ represents ASCII 0 (␀), ^B represents ASCII 2 (␂), ^L represents ASCII 12 (␌), and ^_ represents ASCII 31 (␟). Or, as a hexdump -C:

```<code>00000000  24 5f 3d 31 31 36 2e 31  31 34 2e 31 30 35 2e 39  |$_=116.114.105.9|
00000010  39 2e 31 30 37 2e 24 40  5e 22 00 00 0c 02 1f 22  |9.107.$@^"....."|
00000020  3b 70 72 69 6e 74                                 |;print|
00000026
</code>```

I have wanted to post a Labyrinth/Perl answer since reading Emigna's Labyrinth/><> answer. In that answer, Labyrinth code looks very much like it starts with a Perl version string.

So, in this answer, Labyrinth just does the following:

```<code>$_=                    → dummy operations
116.114.105.99.107.    → print string
$                      → dummy op
@                      → end
</code>```

while Perl does:

```<code>$_=                    → set the $_ variable to:
 116.114.105.99.107    →  a version string for the other language
 .$@                   →  concatenated with $EVAL_ERROR (null when no eval error)
 ^"^@^@^L^B^_";        →  XORed with "\0\0\x0c\2\x1F", to get "treat" from "trick"
print                  → and finally print the string
</code>```

Labyrinth/Perl alternate version, 105 bytes

Here is another version, modifying the string in Labyrinth code, instead of in Perl code:

```<code>; $_=116.114.105.99.107.$@
; ;print;      1+ 7+ 16
; ;;;;;;;;;;;;; 1
;              ;;
;;;;;9^_9^10^00 ^a
</code>```

Labyrinth code follows the path. The last line modifies the code, rotating columns using ^. After the last line has been interpreted, the field looks like:

```<code>; $_=116.114.101.97.116.$@
; ;     ;       +  +
; ;;;;;;;;;;;;;;1
;               ;
;;;;;9^_9^10^005^ 9  07
</code>```

After finishing interpreting the last line, Labyrinth follows the path upwards. Then, the 1 makes it attempt to turn rightwards, but hitting the wall makes it turn leftwards instead. Afterwards, Labyrinth just follows the path, eventually reaching code already explained for the first approach (where Perl modifies the string).

As you'll notice,  (in 9^_9^10^00 ^ 1) numbers in Perl can have _ in them, to make them more readable.

Labyrinth/Perl, linear labyrinth version, 76 bytes

Not as fun as the previous one, but does the trick (or treat, as it may be):

```<code>25^25^25^23^0;$;=116.114.105.99.107.$@
        ; print$    ;   ;  1+ 7+ 16
;
</code>```

Labyrinth/Perl, boring version, 49 bytes

Separate code paths for Labyrinth and Perl:

```<code>;print 116.114.105.99.107
;
116.114.101.97.116.$@
</code>```

Title: Trick or Treat polyglot

Body:
Since Halloween is coming up I thought I might start a fun little code golf challenge!

The challenge is quite simple. You have to write a program that outputs either trick or treat.

"The twist?" you may ask. Well let me explain:

Your program has to do the following:

Be compilable/runnable in two different languages. Different versions of the same language don't count.

When you run the program in one language it should output trick and the other should output treat. The case is irrelevant and padding the string with whitespace characters are allowed (see examples).

This is code-golf,  so the solution with the fewest bytes wins.

A few explanations:

Valid outputs (Just for the words not for running the code in the two languages. Also adding quotes to signalize the beginning or end of the output. Do not include them in your solution!):

```<code>"trick"

"Treat"

"    TReAt"

"
     tRICk          "
</code>```

Invalid outputs:

```<code>"tri ck"

"tr
eat"

"trck"
</code>```

I'm interested to see what you can come up with! Happy Golfing!

I'd like to note that this is my first challenge so if you have suggestions on this question please leave them in the form of a comment.

Leaderboards

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

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

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

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

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

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

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

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

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

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

As cat -v:

$_=116.114.105.99.107.$@^"^@^@^L^B^_";print

Where ^@ represents ASCII 0 (␀), ^B represents ASCII 2 (␂), ^L represents ASCII 12 (␌), and ^_ represents ASCII 31 (␟). Or, as a hexdump -C:

00000000  24 5f 3d 31 31 36 2e 31  31 34 2e 31 30 35 2e 39  |$_=116.114.105.9|
00000010  39 2e 31 30 37 2e 24 40  5e 22 00 00 0c 02 1f 22  |9.107.$@^"....."|
00000020  3b 70 72 69 6e 74                                 |;print|
00000026

I have wanted to post a Labyrinth/Perl answer since reading Emigna's Labyrinth/><> answer. In that answer, Labyrinth code looks very much like it starts with a Perl version string.

So, in this answer, Labyrinth just does the following:

$_=                    → dummy operations
116.114.105.99.107.    → print string
$                      → dummy op
@                      → end

while Perl does:

$_=                    → set the $_ variable to:
 116.114.105.99.107    →  a version string for the other language
 .$@                   →  concatenated with $EVAL_ERROR (null when no eval error)
 ^"^@^@^L^B^_";        →  XORed with "\0\0\x0c\2\x1F", to get "treat" from "trick"
print                  → and finally print the string

Labyrinth/Perl alternate version, 105 bytes

Here is another version, modifying the string in Labyrinth code, instead of in Perl code:

; $_=116.114.105.99.107.$@
; ;print;      1+ 7+ 16
; ;;;;;;;;;;;;; 1
;              ;;
;;;;;9^_9^10^00 ^a

Labyrinth code follows the path. The last line modifies the code, rotating columns using ^. After the last line has been interpreted, the field looks like:

; $_=116.114.101.97.116.$@
; ;     ;       +  +
; ;;;;;;;;;;;;;;1
;               ;
;;;;;9^_9^10^005^ 9  07

After finishing interpreting the last line, Labyrinth follows the path upwards. Then, the 1 makes it attempt to turn rightwards, but hitting the wall makes it turn leftwards instead. Afterwards, Labyrinth just follows the path, eventually reaching code already explained for the first approach (where Perl modifies the string).

As you'll notice,  (in 9^_9^10^00 ^ 1) numbers in Perl can have _ in them, to make them more readable.

Labyrinth/Perl, linear labyrinth version, 76 bytes

Not as fun as the previous one, but does the trick (or treat, as it may be):

25^25^25^23^0;$;=116.114.105.99.107.$@
        ; print$    ;   ;  1+ 7+ 16
;

Labyrinth/Perl, boring version, 49 bytes

Separate code paths for Labyrinth and Perl:

;print 116.114.105.99.107
;
116.114.101.97.116.$@


答:
Rust, 564 bytes (not competitive)

extern crate rand;fn main(){let t=("extern crate rand;fn main(){let t=", ";let mut s=format!(\"{}{:?}{}\",t.0,t,t.1).into_bytes();s.push(0);let mut r=rand::thread_rng();let mut c=s[0];while c!=0{print!(\"{}\",c as char);let u=s.windows(2);c=rand::sample(&mut r,u.filter(|x|x[0]==c),1)[0][1];}}");let mut s=format!("{}{:?}{}",t.0,t,t.1).into_bytes();s.push(0);let mut r=rand::thread_rng();let mut c=s[0];while c!=0{print!("{}",c as char);let u=s.windows(2);c=rand::sample(&mut r,u.filter(|x|x[0]==c),1)[0][1];}}
```

<p>Since I already had written a pretty neat Rust quine for another question, I thought I'd adapt it for this, since it seemed simple enough. While the original was small, though, for this I have made very little attempt to minimize size. Here's an expanded version to explain what's going on:</p>

<pre class="lang-rs prettyprint-override"><code>// Random numbers are removed from the standard library in Rust,
// I had to make a cargo project to even compile this...
// Rust is hardly a golfing language.
extern crate rand;

fn main(){

    // The quine is fairly simple, we just make a tuple with
    // "everything before this tuple" as first element, and
    // "everything after this tuple" with any quotes escaped
    // as second. That makes it really easy to print.
    let t=("[...before...]", "[...after...]");

    // Instead of printing it, we save it as a byte vector
    // and append 0
    let mut s=format!("{}{:?}{}",t.0,t,t.1).into_bytes();
    s.push(0);

    // Start with the first character
    let mut c=s[0];
    let mut r=rand::thread_rng();

    while c!=0 {
        print!("{}",c as char);

        // We slide a 2 wide window over it to save a vector
        // of all bigrams.
        let u=s.windows(2);

        // Filter it to only those which have the current character
        // as first. Take one at random, its second is our next
        // character.
        c=rand::sample(&mut r, u.filter(|x|x[0]==c), 1)[0][1];

        // Keep at it until the 0 byte is generated.
    }
}
</code>```

Sample output 1:

eran(),0{ller=samarin chas c).pr,teteran mut madoletet manthilaplerng().wind_byt.wit();let.u.0][*s=[*s.plleas.wshit, rnd:Vec<_byte mputextet ut t leat=r,t rant!=r().filllet rng();lar("{}{let.ind_byt.what amusarando_ramut!=st ct!(\").0]=colet!(&lec<_ret.plec=s.whrararandormpr=saile ret=r,0]=r);le(\"),t und;fint.prilt!();ler(2).forap(&ler=s(),t ut rat mu:t=ramund:Ve s.putec==[0];wst and_byt sh(\"et c s[1), munwhras[0];c=s=s="etornws(2)[0, ain(|x|x[0,0,0];fowile c ct(&l=",tes().co_byt().wrmat ash(|x|x[*s.lethrant.wrarmu.file(\"et, r==[1);uterile().0,t ando_rinwhas=[0{}"ect.wilant!("{ple mut, mut mamprmant,0];le(&lec=s.1),t co_>=fin mamustec!(\",c=[0];}}",0];leteteat.ust(",ternwhashrarmut ler("erat,0]==file and_reter==s.utet an letet.ut=", ras.1);fin("{:?}"et t letes[*sado_bytet rnd::Verain s[0];whant(){}{}\"echin s(2);lerad;wst reth(\",t u.iletermat c 1];}{}
```

<p>Sample output 2:</p>

<pre class="lang-rs prettyprint-override"><code>et!().0][0][0{}
</code>```

Title: Markov Chain Quine

Body:
A simple Markov Model will be used in this question. For more information about Markov Chains, see http://setosa.io/ev/markov-chains/.

Take a string. For this example, we will use the word:

```<code>reader
</code>```

Now, for each character, take the characters that appear after each occurence of the character in the string. (`^` represents the start of the string and `$` represents the end)

```<code>`^` -> {'r'}       # After the start of the string, there is an `r`.
'r' -> {'e', `$`}  # After the first `r` (*r*eader), there is an `e`
                   # after the second (reade*r*), there is the end of the string.
'e' -> {'a', 'r'}
'a' -> {'d'}
'd' -> {'e'}
</code>```

Now, starting from the start of the string, pick randomly from one of the characters in the next set. Append this character and then pick from the characters in its next set, and so on until you get to the end. Here are some example words:

```<code>r
rereader
rer
readereader
</code>```

If a character appears after another character multiple times, it is more likely to be chosen. For example, in cocoa can, after a c, there is a two thirds of a chance of getting an o and a one thirds chance of getting an a.

```<code>'c' -> {'o', 'o', 'a'}
</code>```

Challenge

Create a program that takes no input and outputs a random string generated using a Markov Chain, like above, where the input to the chain is the program's source.

The program must have at least two characters, two of which must be the same (To prevent "boring" chains that only have one output)

You can modify the model to use bytes instead of characters if you wish, but change "characters" to "bytes" in rule 1

The program should output strings randomly with the expected frequency in theory

This is code-golf, so the shortest program wins!

Body:
Rust, 564 bytes (not competitive)

extern crate rand;fn main(){let t=("extern crate rand;fn main(){let t=", ";let mut s=format!(\"{}{:?}{}\",t.0,t,t.1).into_bytes();s.push(0);let mut r=rand::thread_rng();let mut c=s[0];while c!=0{print!(\"{}\",c as char);let u=s.windows(2);c=rand::sample(&mut r,u.filter(|x|x[0]==c),1)[0][1];}}");let mut s=format!("{}{:?}{}",t.0,t,t.1).into_bytes();s.push(0);let mut r=rand::thread_rng();let mut c=s[0];while c!=0{print!("{}",c as char);let u=s.windows(2);c=rand::sample(&mut r,u.filter(|x|x[0]==c),1)[0][1];}}

Since I already had written a pretty neat Rust quine for another question, I thought I'd adapt it for this, since it seemed simple enough. While the original was small, though, for this I have made very little attempt to minimize size. Here's an expanded version to explain what's going on:

// Random numbers are removed from the standard library in Rust,
// I had to make a cargo project to even compile this...
// Rust is hardly a golfing language.
extern crate rand;

fn main(){

    // The quine is fairly simple, we just make a tuple with
    // "everything before this tuple" as first element, and
    // "everything after this tuple" with any quotes escaped
    // as second. That makes it really easy to print.
    let t=("[...before...]", "[...after...]");

    // Instead of printing it, we save it as a byte vector
    // and append 0
    let mut s=format!("{}{:?}{}",t.0,t,t.1).into_bytes();
    s.push(0);

    // Start with the first character
    let mut c=s[0];
    let mut r=rand::thread_rng();

    while c!=0 {
        print!("{}",c as char);

        // We slide a 2 wide window over it to save a vector
        // of all bigrams.
        let u=s.windows(2);

        // Filter it to only those which have the current character
        // as first. Take one at random, its second is our next
        // character.
        c=rand::sample(&mut r, u.filter(|x|x[0]==c), 1)[0][1];

        // Keep at it until the 0 byte is generated.
    }
}

Sample output 1:

eran(),0{ller=samarin chas c).pr,teteran mut madoletet manthilaplerng().wind_byt.wit();let.u.0][*s=[*s.plleas.wshit, rnd:Vec<_byte mputextet ut t leat=r,t rant!=r().filllet rng();lar("{}{let.ind_byt.what amusarando_ramut!=st ct!(\").0]=colet!(&lec<_ret.plec=s.whrararandormpr=saile ret=r,0]=r);le(\"),t und;fint.prilt!();ler(2).forap(&ler=s(),t ut rat mu:t=ramund:Ve s.putec==[0];wst and_byt sh(\"et c s[1), munwhras[0];c=s=s="etornws(2)[0, ain(|x|x[0,0,0];fowile c ct(&l=",tes().co_byt().wrmat ash(|x|x[*s.lethrant.wrarmu.file(\"et, r==[1);uterile().0,t ando_rinwhas=[0{}"ect.wilant!("{ple mut, mut mamprmant,0];le(&lec=s.1),t co_>=fin mamustec!(\",c=[0];}}",0];leteteat.ust(",ternwhashrarmut ler("erat,0]==file and_reter==s.utet an letet.ut=", ras.1);fin("{:?}"et t letes[*sado_bytet rnd::Verain s[0];whant(){}{}\"echin s(2);lerad;wst reth(\",t u.iletermat c 1];}{}

Sample output 2:

et!().0][0][0{}


答:
C, 306 328 585 611 615 623 673 707 bytes

Source code:

p[256][256]={0};char*X="p[256][256]={0};char*X=%c%s%c,Y[999],c,j,*a;main(){sprintf(Y,X,34,X,34);for(a=Y;*a;a++)p[*a][*(a+1)]++;for(j=*Y;putchar(c=j);)while(p[c][++j]<<16<rand());}",Y[999],c,j,*a;main(){sprintf(Y,X,34,X,34);for(a=Y;*a;a++)p[*a][*(a+1)]++;for(j=*Y;putchar(c=j);)while(p[c][++j]<<16<rand());}
```

<p>With newlines and whitespace added for legibility/explanation:</p>

<pre class="lang-c prettyprint-override"><code>01  p[256][256]={0};
02  char*X="p[256][256]={0};char*X=%c%s%c,Y[999],c,j,*a;main(){sprintf(Y,X,34,X,34);for(a=Y;*a;a++)p[*a][*(a+1)]++;for(j=*Y;putchar(c=j);)while(p[c][++j]<<16<rand());}",
03  Y[999],c,j,*a;
04  main(){
05      sprintf(Y,X,34,X,34);
06      for(a=Y;*a;a++)p[*a][*(a+1)]++;
07      for(j=*Y;putchar(c=j);)
08          while(p[c][++j]<<16<rand());
09  }
</code>```

Explanation

Line 01: p[][] holds the counts of one character following another.

Line 02: X contains the program's source, escaped with %c%s%c.

Line 03: Y will contain the program's literal source. c, j, *a are counting variables.

Line 05: Set Y to contain the quine.

Line 06: Count letter occurrences in p[][].

Line 07: Print the current state.

Line 08: Find the next character randomly, proportional to the counts in p[][].

Sample output:

p[++);p[99]=Y;putfor(aind(a++j,*a+j=j,c][c,*an(arile(pr*Y,Y[256]<<1);)][*Y,Y;)wha+++j=*aintfor*Y;prin(a+j]=j][256<1)pr(a;a;f(p[char(Y;for());};a;ma;ma=%s%chain(Y;ar(j][256<<<1)p[256<<raile(cha][9]<rin(j,34,34,Y[256]+j,Y,34,Y,c=Y,*a;*a;for(){0}

Title: Markov Chain Quine

Body:
C, 306 328 585 611 615 623 673 707 bytes

Source code:

p[256][256]={0};char*X="p[256][256]={0};char*X=%c%s%c,Y[999],c,j,*a;main(){sprintf(Y,X,34,X,34);for(a=Y;*a;a++)p[*a][*(a+1)]++;for(j=*Y;putchar(c=j);)while(p[c][++j]<<16<rand());}",Y[999],c,j,*a;main(){sprintf(Y,X,34,X,34);for(a=Y;*a;a++)p[*a][*(a+1)]++;for(j=*Y;putchar(c=j);)while(p[c][++j]<<16<rand());}

With newlines and whitespace added for legibility/explanation:

01  p[256][256]={0};
02  char*X="p[256][256]={0};char*X=%c%s%c,Y[999],c,j,*a;main(){sprintf(Y,X,34,X,34);for(a=Y;*a;a++)p[*a][*(a+1)]++;for(j=*Y;putchar(c=j);)while(p[c][++j]<<16<rand());}",
03  Y[999],c,j,*a;
04  main(){
05      sprintf(Y,X,34,X,34);
06      for(a=Y;*a;a++)p[*a][*(a+1)]++;
07      for(j=*Y;putchar(c=j);)
08          while(p[c][++j]<<16<rand());
09  }

Explanation

Line 01: p[][] holds the counts of one character following another.

Line 02: X contains the program's source, escaped with %c%s%c.

Line 03: Y will contain the program's literal source. c, j, *a are counting variables.

Line 05: Set Y to contain the quine.

Line 06: Count letter occurrences in p[][].

Line 07: Print the current state.

Line 08: Find the next character randomly, proportional to the counts in p[][].

Sample output:

p[++);p[99]=Y;putfor(aind(a++j,*a+j=j,c][c,*an(arile(pr*Y,Y[256]<<1);)][*Y,Y;)wha+++j=*aintfor*Y;prin(a+j]=j][256<1)pr(a;a;f(p[char(Y;for());};a;ma;ma=%s%chain(Y;ar(j][256<<<1)p[256<<raile(cha][9]<rin(j,34,34,Y[256]+j,Y,34,Y,c=Y,*a;*a;for(){0}


问:
Faux Source Code
Output one random character for each character of source code (as illustrated below). The probability of each character is its frequency in the original source code. Thus the output will be fake source code resembling a quine.

Specification

Restrictions

Standard quine constrains apply. No empty programs or functions. Also no reading your own source.

Output

The number of characters output should be exactly the number of characters in the source code

Each output character should be randomly choosen

The probability of choosing any character is equal to (occurrences in source) / (length of source)

This means that even a unary solution needs to 'randomly' choose 1 with probability 1. Which is to say that the output can't be hard coded.

Winning

This is code golf, so fewest bytes wins

Example

```<code>Program           Frequency           Probability           Possible Output
-------           ---------           -----------           ---------------
 a@!@              a - 1               a - 25%               @@a@
                   ! - 1               ! - 25%
                   @ - 2               @ - 50%
</code>```

```<code>Program           Frequency           Probability           Possible Output
-------           ---------           -----------           ---------------
caBaDBcDaBDB       a - 3               a - 25%               aaaBBBBccDDD
                   B - 4               B - 33%
                   c - 2               c - 17%
                   D - 3               D - 25%
</code>```

答:
JavaScript, 128 bytes

```<code>a=";a+=uneval(a);alert(a.replace(/./g,_=>a[Math.random()*64|0]))a=";a+=uneval(a);alert(a.replace(/./g,_=>a[Math.random()*64|0]))
</code>```

Note: only works in Firefox due to the use of uneval.

Sample runs:

```<code>)a(rgc=d6m_a4uar=hp(lll(,d=m=dee(M(gtraoan0)(M(aaaa(M]c)e)/M()/u//M6_n/a"*unea(/>atugrn(a=nav"|;)|=)/,ataa,aaangtue;am)t0;|ctoa/
=lvct;eee,,a.e=6r0;);Mtaaoa.aeea4)a[r.6]e/ll+l.)=)|a[(c"rao4ea/=_acaMh=veerva"a(_(d(l)lgn.;rM">=ea40a*).e(h(laa6r)4a)rhlar=t(ta[
[rt]ll]n))aota.e)g;>ae*;..4tt];l[;].*lnr4(mnM|alg(a.ag(.=e(a>>aa>.hga;a/pat+elc];apc=(ag)tao.).ll4u)dah]r(ul)>lr;,)ret(e/g(=_c*r
M.r)_;.a(lraalg("mac>dmrlr"0/ah(a()ead|/0a(m.|u0)(a(0_[dn)a]/raal;eata)a.ataeaa*l)=ra()la=(a)*aaea>n;.a.)ca)orM(tm*a,a=)p;(>r)aa
</code>```

Title: Faux Source Code

Body:
JavaScript, 128 bytes

a=";a+=uneval(a);alert(a.replace(/./g,_=>a[Math.random()*64|0]))a=";a+=uneval(a);alert(a.replace(/./g,_=>a[Math.random()*64|0]))

Note: only works in Firefox due to the use of uneval.

Sample runs:

)a(rgc=d6m_a4uar=hp(lll(,d=m=dee(M(gtraoan0)(M(aaaa(M]c)e)/M()/u//M6_n/a"*unea(/>atugrn(a=nav"|;)|=)/,ataa,aaangtue;am)t0;|ctoa/
=lvct;eee,,a.e=6r0;);Mtaaoa.aeea4)a[r.6]e/ll+l.)=)|a[(c"rao4ea/=_acaMh=veerva"a(_(d(l)lgn.;rM">=ea40a*).e(h(laa6r)4a)rhlar=t(ta[
[rt]ll]n))aota.e)g;>ae*;..4tt];l[;].*lnr4(mnM|alg(a.ag(.=e(a>>aa>.hga;a/pat+elc];apc=(ag)tao.).ll4u)dah]r(ul)>lr;,)ret(e/g(=_c*r
M.r)_;.a(lraalg("mac>dmrlr"0/ah(a()ead|/0a(m.|u0)(a(0_[dn)a]/raal;eata)a.ataeaa*l)=ra()la=(a)*aaea>n;.a.)ca)orM(tm*a,a=)p;(>r)aa


问:
How many significant figures?
Given a number as input, determine how many significant figures it has. This number will should be taken as a string because you have to do some special formatting. You'll see what I mean soon (I think).

A digit is a sig-fig if at least one of the following apply:

Non-zero digits are always significant.

Any zeros between two significant digits are significant.

final zero or trailing zeros in the decimal portion only are significant.

all digits are significant if nothing follows the decimal place.

when there are only zeroes, all but the last zero are considered leading zeroes

Input

A string or string array of the number. It might have a decimal point at the end without a digit after it. It might not have a decimal point at all.

Output

How many sig-figs there are.

Examples

```<code>1.240 -> 4
0. -> 1
83900 -> 3
83900.0 -> 6
0.025 -> 2
0.0250 -> 3
2.5 -> 2
970. -> 3
0.00 -> 1
</code>```

答:
Retina, <s>29</s> 27 bytes

Saved 2 bytes thanks to @MartinEnder

```<code>^0\.0*.|^\d(\d*?)0+$
1$1
\d
</code>```

Try it online! | Test suite

Title: How many significant figures?

Body:
Retina, <s>29</s> 27 bytes

Saved 2 bytes thanks to @MartinEnder

^0\.0*.|^\d(\d*?)0+$
1$1
\d

Try it online! | Test suite


答:
05AB1E, <s>11</s> 10 bytes

```<code>D.ïi0Ü}þïg
</code>```

Try it online! or as a Test suite

Explanation

```<code>D            # duplicate
 .ïi  }      # if it is an integer
    0Ü       # remove trailing zeroes
       þ     # remove the "." if present
        ï    # convert to int
         g   # length
</code>```

Title: How many significant figures?

Body:
Given a number as input, determine how many significant figures it has. This number will should be taken as a string because you have to do some special formatting. You'll see what I mean soon (I think).

A digit is a sig-fig if at least one of the following apply:

Non-zero digits are always significant.

Any zeros between two significant digits are significant.

final zero or trailing zeros in the decimal portion only are significant.

all digits are significant if nothing follows the decimal place.

when there are only zeroes, all but the last zero are considered leading zeroes

Input

A string or string array of the number. It might have a decimal point at the end without a digit after it. It might not have a decimal point at all.

Output

How many sig-figs there are.

Examples

```<code>1.240 -> 4
0. -> 1
83900 -> 3
83900.0 -> 6
0.025 -> 2
0.0250 -> 3
2.5 -> 2
970. -> 3
0.00 -> 1
</code>```

Body:
05AB1E, <s>11</s> 10 bytes

D.ïi0Ü}þïg

Try it online! or as a Test suite

Explanation

D            # duplicate
 .ïi  }      # if it is an integer
    0Ü       # remove trailing zeroes
       þ     # remove the "." if present
        ï    # convert to int
         g   # length


答:
C, 136 bytes

```<code>main(a){for(a=136;a--;)rand()%68?putchar("main(a){for(a=136;a--;)rand()%68?putchar([rand()%67]):putchar(34);}"[rand()%67]):putchar(34);}
</code>```

Example output:

```<code>;%7c(u)"r4-hd)nnr-%n6;6(4or(n4(6(a:=a3r-:()hp(:aa%;4rru}h;(a()3mh3rdi7));a-u36:r3on[4?p((]6n6?()-6t736unhr%:[%[[d(p:[ru)-n(6r=:](p-})8"]
</code>```

This program outputs 136 characters randomly.

The entire source code (less " quotation marks) is contained in a string. The program determines the probability of outputting a quotation mark as 2/136, otherwise outputting one of the other 67 characters randomly.

There are two occurrences of each character in the string in the program. The probability of outputting a character from the string is 134/136. The probability of choosing a specific character in the string is 1/67. So the chance of outputting a character in the string is 134/136 * 1/67 = 2/136. There are two occurrences of each string character in the program, so there is a 1/136 probability of outputting a character for each occurrence in the program.

The order of symbols inside the string doesn't matter.

Title: Faux Source Code

Body:
Output one random character for each character of source code (as illustrated below). The probability of each character is its frequency in the original source code. Thus the output will be fake source code resembling a quine.

Specification

Restrictions

Standard quine constrains apply. No empty programs or functions. Also no reading your own source.

Output

The number of characters output should be exactly the number of characters in the source code

Each output character should be randomly choosen

The probability of choosing any character is equal to (occurrences in source) / (length of source)

This means that even a unary solution needs to 'randomly' choose 1 with probability 1. Which is to say that the output can't be hard coded.

Winning

This is code golf, so fewest bytes wins

Example

```<code>Program           Frequency           Probability           Possible Output
-------           ---------           -----------           ---------------
 a@!@              a - 1               a - 25%               @@a@
                   ! - 1               ! - 25%
                   @ - 2               @ - 50%
</code>```

```<code>Program           Frequency           Probability           Possible Output
-------           ---------           -----------           ---------------
caBaDBcDaBDB       a - 3               a - 25%               aaaBBBBccDDD
                   B - 4               B - 33%
                   c - 2               c - 17%
                   D - 3               D - 25%
</code>```

Body:
C, 136 bytes

main(a){for(a=136;a--;)rand()%68?putchar("main(a){for(a=136;a--;)rand()%68?putchar([rand()%67]):putchar(34);}"[rand()%67]):putchar(34);}

Example output:

;%7c(u)"r4-hd)nnr-%n6;6(4or(n4(6(a:=a3r-:()hp(:aa%;4rru}h;(a()3mh3rdi7));a-u36:r3on[4?p((]6n6?()-6t736unhr%:[%[[d(p:[ru)-n(6r=:](p-})8"]

This program outputs 136 characters randomly.

The entire source code (less " quotation marks) is contained in a string. The program determines the probability of outputting a quotation mark as 2/136, otherwise outputting one of the other 67 characters randomly.

There are two occurrences of each character in the string in the program. The probability of outputting a character from the string is 134/136. The probability of choosing a specific character in the string is 1/67. So the chance of outputting a character in the string is 134/136 * 1/67 = 2/136. There are two occurrences of each string character in the program, so there is a 1/136 probability of outputting a character for each occurrence in the program.

The order of symbols inside the string doesn't matter.