问:
Compiled quine variant
Thinking about various quine puzzles here, I got an idea for another one:

Compose a program that outputs its own compiled code to a file (or multiple files, if the compiled code is). (This means that only compiled languages are eligible.)

Rules

Standard quine rules - no cheating allowed. In particular:

The program cannot read the compiled code from disk, cannot store it somewhere etc. It must compute it somehow without external help.

If the program is compiled to several files (i.e. several Java .class files), it must output them all.

You can use any existing libraries available for your language. However:

The libraries you use cannot be something created just for this task. (For example in order to keep some information away from what's considered to be the program.)

Any libraries you use must be older than your program. You cannot just create a program that loads a piece of data from an external library, compile the program, and copy the compiled code into the library - that'd be cheating.

You cannot embed a compiler of your language in any form. In particular, you cannot just take a standard quine and hook it up with a compiler to produce the compiled output.

As mentioned, only compiled languages are eligible. You can use a scripting language as long as it can be compiled to a bytecode that's reasonably different from the source form (if you're not sure, better ask).

Notes

Most likely, this puzzle can be solved reasonably only in languages that compile to some sort of bytecode that can be manipulated. For example, Java and compiled bytecode seems good for the task. (But if you find a genuine solution in some other compiled language, that's fine too, as long as it isn't some sort of cheating.)

Submission

Don't submit the compiled program (as this could be potentially dangerous). Instead post your sources and a description what to do to create the final program.

Evaluation

Let voters decide the best solution. Personally I'd appreciate solution that are elegant, short (in their source form) and didactic - that explain what's going on.

Bonuses

Bonus points for

Let the program output a compressed file containing its compiled code. This has the additional benefit that if the program is compiled into more files, the output will be a single packed file. For example, in Java try to create an executable JAR file that outputs the JAR itself.

Outputting the MD5 sum of the compiled file(s) - so the program would write its compiled code and its MD5 sum.

Title: Compiled quine variant

Body:
Python 2.7.3

#!/usr/bin/env python
import sys
import time
import struct
import compiledquine

_ = '\x63\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x40\x00\x00\x00\x73\x6e\x00\x00\x00\x64\x00\x00\x64\x01\x00\x6c\x00\x00\x5a\x00\x00\x64\x00\x00\x64\x01\x00\x6c\x01\x00\x5a\x01\x00\x64\x00\x00\x64\x01\x00\x6c\x02\x00\x5a\x02\x00\x64\x00\x00\x64\x01\x00\x6c\x03\x00\x5a\x03\x00\x64\x02\x00\x5a\x04\x00\x65\x00\x00\x6a\x05\x00\x6a\x06\x00\x64\x03\x00\x65\x02\x00\x6a\x07\x00\x64\x04\x00\x65\x08\x00\x65\x01\x00\x6a\x01\x00\x83\x00\x00\x83\x01\x00\x83\x02\x00\x17\x65\x04\x00\x65\x04\x00\x16\x17\x83\x01\x00\x01\x64\x01\x00\x53\x28\x05\x00\x00\x00\x69\xff\xff\xff\xff\x4e\x73\x08\x00\x00\x00%s\x73\x04\x00\x00\x00\x03\xf3\x0d\x0a\x74\x01\x00\x00\x00\x49\x28\x09\x00\x00\x00\x74\x03\x00\x00\x00\x73\x79\x73\x74\x04\x00\x00\x00\x74\x69\x6d\x65\x74\x06\x00\x00\x00\x73\x74\x72\x75\x63\x74\x74\x0d\x00\x00\x00\x63\x6f\x6d\x70\x69\x6c\x65\x64\x71\x75\x69\x6e\x65\x74\x01\x00\x00\x00\x5f\x74\x06\x00\x00\x00\x73\x74\x64\x6f\x75\x74\x74\x05\x00\x00\x00\x77\x72\x69\x74\x65\x74\x04\x00\x00\x00\x70\x61\x63\x6b\x74\x03\x00\x00\x00\x69\x6e\x74\x28\x00\x00\x00\x00\x28\x00\x00\x00\x00\x28\x00\x00\x00\x00\x73\x1c\x00\x00\x00\x2f\x68\x6f\x6d\x65\x2f\x67\x72\x61\x6e\x74\x2f\x63\x6f\x6d\x70\x69\x6c\x65\x64\x71\x75\x69\x6e\x65\x2e\x70\x79\x74\x08\x00\x00\x00\x3c\x6d\x6f\x64\x75\x6c\x65\x3e\x02\x00\x00\x00\x73\x0a\x00\x00\x00\x0c\x01\x0c\x01\x0c\x01\x0c\x02\x06\x01'
sys.stdout.write('\x03\xf3\x0d\x0a' + struct.pack('I', int(time.time())) + _ % _)

Note that this must be saved as compiledquine.py. These are the results I get:

$ ./compiledquine.py > compiledquine.py.out
$ md5sum compiledquine.pyc compiledquine.py.out
4b82e7d94d0d59e3d647d775fffc1948  compiledquine.pyc
4b82e7d94d0d59e3d647d775fffc1948  compiledquine.py.out

I won't guarantee that it'll work for you, but it does consistently work for me. Here's what happens:

At the bottom of the import statements, the script itself is imported. This compiles it to a .pyc file.

The variable _ is filled with the program's bytecode starting at byte 0x08, except %s is put in place of the variable itself.

The script fills in the first 4 'magic' bytes, which are specific to Python 2.7.3, followed by the timestamp in the next 4 bytes, which is generated by struct.pack and time.time, and then adds _ % _ to complete the output. (That last bit is borrowed from some other Python quines.)

Because of the timestamp at the beginning, this script technically isn't always accurate. If the self-import and the last line execute in different seconds, the output will be a byte off.


问:
Average an image
Here is an image:

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

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

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

Average the values of the ASCII characters in each section.

Round this average and convert it to an ASCII character.

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

Repeat this for all sections.

So the average of the image above looks like this:

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

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

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

答:
Python, 319 bytes

def f(A):
 L,R,S=len,range,A.split('\n')
 if L(S[0])%2:S=[s+' 'for s in S]
 m=L(S[0])
 if L(S)%2:S+=[' '*m]
 C=[chr(int(sum(map(ord,[S[i][j],S[i+1][j],S[i][j+1],S[i+1][j+1]]))/4.0+0.5))for i in R(0,L(S),2)for j in R(0,m,2)]
 f=t='';i=0
 while i<L(C):
    t+=C[i]*2
    i+=1
    if i%(m/2)<1:f+=(t+'\n')*2;t=''
 f=f[:-1]
 print f
```

2nd indentation is tabs.

Stuff before C is padding, C is the averaging process to single letters and rest is output

ContentLicense: CC BY-SA 3.0

Title: Average an image

Body:
Python, 319 bytes

def f(A):
 L,R,S=len,range,A.split('\n')
 if L(S[0])%2:S=[s+' 'for s in S]
 m=L(S[0])
 if L(S)%2:S+=[' '*m]
 C=[chr(int(sum(map(ord,[S[i][j],S[i+1][j],S[i][j+1],S[i+1][j+1]]))/4.0+0.5))for i in R(0,L(S),2)for j in R(0,m,2)]
 f=t='';i=0
 while i<L(C):
    t+=C[i]*2
    i+=1
    if i%(m/2)<1:f+=(t+'\n')*2;t=''
 f=f[:-1]
 print f

2nd indentation is tabs.

Stuff before C is padding, C is the averaging process to single letters and rest is output


问:
Random Golf of the Day #7: A distinctly random character

About the Series

This is a guest entry for the Random Golf of the Day series.

First off, you may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges. You can find the leaderboard along with some more information about the series in the first post.

Input

No input is taken.

Output

A single letter of the alphabet (case irrelevant), with an optional trailing newline. Each letter must have non-zero probability of being chosen, and all 26 probabilities must be distinct. To remove all ambiguity: Distinct means that there must not be two probabilities that are equal to each other.

Scoring

This is code golf. Shortest code in bytes wins.

A valid entry is a full program or function that has zero probability of not terminating.

Alphabet

To avoid confusion, the particular alphabet to be used is the Latin alphabet:

Either

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

or

```<code>abcdefghijklmnopqrstuvwxyz
</code>```

You may choose to output upper case or lower case. Alternatively, you may choose to output different cases on different runs if that helps. The probability for a given letter is the probability of that letter appearing in either case (upper or lower).

Explanation

As it won't be at all obvious from the output, please include a clear explanation of how you achieved the 26 distinct probabilities.

Leaderboard

(from here)

var QUESTION_ID=89621,OVERRIDE_USER=20283;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

```
</div>
</div>
</p>

<p><strong>The first post of the series also generates an overall leaderboard.</strong></p>

<p>To make sure that your answers show up, please start every answer with a headline, using the following Markdown template:</p>

```## Language Name, N bytes
```

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

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

(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)

答:
MATL, 6 Characters

```<code>1Y2Xr)
</code>```

Explanation:

Xr Take a normally distributed random number
) Use this to index into...
1Y2 The alphabet

The distribution is symmetrical around 0, and the translation of number to char is symmetrical around 0.5. As such the probabilities should be distinct.

Body:
MATL, 6 Characters

1Y2Xr)

Explanation:

Xr Take a normally distributed random number
) Use this to index into...
1Y2 The alphabet

The distribution is symmetrical around 0, and the translation of number to char is symmetrical around 0.5. As such the probabilities should be distinct.


答:
TI-Basic, 39 bytes

```<code>sub("ABCDEFGHIJKLMNOPQRSTUVWXYZ",int(26^rand),1
</code>```

rand generates a uniform value in (0,1]. This gives 26^rand a different probability to equal the integers from 1 to 26.

Older version, 45 bytes

```<code>sub("ABCDEFGHIJKLMNOPQRSTUVWXYZAAA",1+int(4abs(invNorm(rand))),1
</code>```

Limited precision of the TI-Basic integers limits normal distributions to generating numbers within µ±7.02σ (see randNorm(). So we get the absolute value of a random number with µ 0 and σ 1, multiplying by four to increase the practical range mentioned before to µ±28.08σ. Then, we floor the value and add 1, since sub( is 1-indexed, giving us a range from 1-29 with different probabilities of each.

Title: Random Golf of the Day #7: A distinctly random character

Body:
About the Series

This is a guest entry for the Random Golf of the Day series.

First off, you may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges. You can find the leaderboard along with some more information about the series in the first post.

Input

No input is taken.

Output

A single letter of the alphabet (case irrelevant), with an optional trailing newline. Each letter must have non-zero probability of being chosen, and all 26 probabilities must be distinct. To remove all ambiguity: Distinct means that there must not be two probabilities that are equal to each other.

Scoring

This is code golf. Shortest code in bytes wins.

A valid entry is a full program or function that has zero probability of not terminating.

Alphabet

To avoid confusion, the particular alphabet to be used is the Latin alphabet:

Either

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

or

```<code>abcdefghijklmnopqrstuvwxyz
</code>```

You may choose to output upper case or lower case. Alternatively, you may choose to output different cases on different runs if that helps. The probability for a given letter is the probability of that letter appearing in either case (upper or lower).

Explanation

As it won't be at all obvious from the output, please include a clear explanation of how you achieved the 26 distinct probabilities.

Leaderboard

(from here)

var QUESTION_ID=89621,OVERRIDE_USER=20283;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

```
</div>
</div>
</p>

<p><strong>The first post of the series also generates an overall leaderboard.</strong></p>

<p>To make sure that your answers show up, please start every answer with a headline, using the following Markdown template:</p>

```## Language Name, N bytes
```

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

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

(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)

Body:
TI-Basic, 39 bytes

sub("ABCDEFGHIJKLMNOPQRSTUVWXYZ",int(26^rand),1

rand generates a uniform value in (0,1]. This gives 26^rand a different probability to equal the integers from 1 to 26.

Older version, 45 bytes

sub("ABCDEFGHIJKLMNOPQRSTUVWXYZAAA",1+int(4abs(invNorm(rand))),1

Limited precision of the TI-Basic integers limits normal distributions to generating numbers within µ±7.02σ (see randNorm(). So we get the absolute value of a random number with µ 0 and σ 1, multiplying by four to increase the practical range mentioned before to µ±28.08σ. Then, we floor the value and add 1, since sub( is 1-indexed, giving us a range from 1-29 with different probabilities of each.


问:
Fibonacci function or sequence
The Fibonacci sequence is a sequence of numbers, where every number in the sequence is the sum of the two numbers preceding it.  The first two numbers in the sequence are both 1. Here are the first few terms:

```<code>1 1 2 3 5 8 13 21 34 55 89 ...
</code>```

Write the shortest code that either:

Generates the Fibonacci sequence without end.

Given n calculates the nth term of the sequence. (Either 1 or zero indexed)

You may use standard forms of input and output.

(I gave both options in case one is easier to do in your chosen language than the other.)

For the function that takes an n, a reasonably large return value (the largest Fibonacci number that fits your computer's normal word size, at a minimum) has to be supported.

Leaderboard

/* Configuration */

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

/* App */

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

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

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

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

function process() {
  var valid = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
R, <s>33</s> 32 bytes

CAUTION: This attempts to print the whole Fibonacci sequence. It does not stop.

```<code>a=b=1;repeat print(a<-(b=b+a)-a)
</code>```

Pretty simple. Initialize a and b. Then a repeat loop which adds them to find the next number and print it. This loop will not stop, though eventually the overflow means it just prints NaN repeatedly.

Edit: saved 1 byte by switching to a=b=1 which required a different loop control mechanism to print the first few values, and then a different assignment location, etc.

ContentLicense: CC BY-SA 4.0

Title: Fibonacci function or sequence

Body:
R, <s>33</s> 32 bytes

CAUTION: This attempts to print the whole Fibonacci sequence. It does not stop.

a=b=1;repeat print(a<-(b=b+a)-a)

Pretty simple. Initialize a and b. Then a repeat loop which adds them to find the next number and print it. This loop will not stop, though eventually the overflow means it just prints NaN repeatedly.

Edit: saved 1 byte by switching to a=b=1 which required a different loop control mechanism to print the first few values, and then a different assignment location, etc.


问:
List of possible birth years of living humans
The Challenge

Output a list of years that starts with the current year and ends 120 years ago. The birth year of every living human would be included in this list.

Details

The list should be in descending order.

Every built-in function to manipulate arrays and/or lists is allowed.

Shortest code in bytes wins.

When run this year 2016, the output would be

2016, 2015, ..., 1897, 1896

When run next year 2017, the output would be

2017, 2016, ..., 1898, 1897

Etc.

Update

Some have asked about the format of the list. As most have guessed, it doesn't matter. Insert any separator between the numbers. Intuitively most inserted a comma or space or both, newline or output an array.

Quasi superhumans like Jeanne Calment are an exception to the rule stated in my question.

答:
Vim, <s>32</s> 29 keystrokes

Thanks to @daniero for some help on saving some keystrokes and making the output a little neater.

```<code>"=strftime('%Y')<Enter>pqqYp<Ctrl-x>q118@q
</code>```

<Enter> is Enter

<Ctrl-x> is Ctrl + X

Explanation:

```<code>"                                          # Put into the register {
 =strftime('%Y')                           #   This year in YYYY form
                <Enter>                    # }
                       p                   # Paste the register
                        qq                 # Record macro q {
                          Y                #   Yank (copy) the current line
                           p               #   Paste
                            <Ctrl-x>       #   Decrment number at cursor
                                    q      # }
                                     118@q # Do macro q 118 times
</code>```

Output format:

Each number is on a separate line like below.

```<code>2016
2015
.
.
.
1898
1897
</code>```

Body:
Vim, <s>32</s> 29 keystrokes

Thanks to @daniero for some help on saving some keystrokes and making the output a little neater.

"=strftime('%Y')<Enter>pqqYp<Ctrl-x>q118@q

<Enter> is Enter

<Ctrl-x> is Ctrl + X

Explanation:

"                                          # Put into the register {
 =strftime('%Y')                           #   This year in YYYY form
                <Enter>                    # }
                       p                   # Paste the register
                        qq                 # Record macro q {
                          Y                #   Yank (copy) the current line
                           p               #   Paste
                            <Ctrl-x>       #   Decrment number at cursor
                                    q      # }
                                     118@q # Do macro q 118 times

Output format:

Each number is on a separate line like below.

2016
2015
.
.
.
1898
1897


问:
Sort the months of the year
Write a function or program that takes string inputs, fully-spelled, English month names in title case: January, February, March, etc. (null/CR/LF terminated OK, delimited with some non-alpha character if you so choose) and either

compares two inputs, returning a Truthy value if the second input is greater (in month order) than the first. Equal values result in a Falsey value

or sorts an arbitrary sequence (list, delimited string, etc.) of them in chronological order

(The crux of the challenge is defining a method/expression that gives the correct lexicographical sort. Some languages might have a shorter answer with one or the other)

You cannot use any internal time parsing methods (e.g. strptime) to translate the month name into a number or a pre-canned mapping of month names. Use properties of the strings themselves, a parsimonious look-up table you define, or something clever.

Example

Functioning examples, though the first is prohibited by the rules...

```<code>import datetime
def is_later_month(a, b):
    '''
    Example of prohibited code because it relies on language
    features about how to parse month names
    '''
    return datetime.strptime(a, '%B') < datetime.strptime(b, '%B')
</code>```

The below versions are OK though, because we code that info

```<code>months = {
    'January':  1, 'February':  2, 'March':      3,
    'April':    4, 'May':       5, 'June':       6,
    'July':     7, 'August':    8, 'September':  9,
    'October': 10, 'November': 11, 'December':  12,
}
def is_later_month(a, b):
    """
    Returns True/False when comparing two months.
    """
    return months[a] < months[b]
</code>```

Or you could do a sorting function

```<code>months = {'as above...'}
def sort_months(l):
    """
    Sorts list and returns it. Different input and output than the above,
    but equally valid. Sorting versus comparing might be shorter in your
    favorite language.
    """
    return sorted(l, key=lambda x: months[x])
</code>```

Example tests

```<code>assert is_later_month('January', 'February')
assert is_later_month('January', 'December')
assert is_later_month('November', 'December')
assert not is_later_month('July', 'July')
assert not is_later_month('October', 'September')
</code>```

答:
Python 83 82 bytes

```<code>lambda x,y,m=(lambda a:'2&9<@FD6A?L%'.find(chr(sum(map(ord,a[:3]))%77))):m(x)<m(y)
</code>```

Test: https://repl.it/repls/TimelyDecimalBrowsers

Gets the sum of the first 3 chars and creates a single char to search.

Title: Sort the months of the year

Body:
Python 83 82 bytes

lambda x,y,m=(lambda a:'2&9<@FD6A?L%'.find(chr(sum(map(ord,a[:3]))%77))):m(x)<m(y)

Test: https://repl.it/repls/TimelyDecimalBrowsers

Gets the sum of the first 3 chars and creates a single char to search.


答:
Java, 71 chars

Single number: (Binet formula, considering 1.62 as the golden ratio))

```<code>int f(int n){return(Math.pow(1.62,n)-(Math.pow(-1.62,-n))/Math.sqrt(5)}
</code>```

I know this isn't surprisingly short, however Math is beautiful and this formula is even more!

Title: Fibonacci function or sequence

Body:
The Fibonacci sequence is a sequence of numbers, where every number in the sequence is the sum of the two numbers preceding it.  The first two numbers in the sequence are both 1. Here are the first few terms:

```<code>1 1 2 3 5 8 13 21 34 55 89 ...
</code>```

Write the shortest code that either:

Generates the Fibonacci sequence without end.

Given n calculates the nth term of the sequence. (Either 1 or zero indexed)

You may use standard forms of input and output.

(I gave both options in case one is easier to do in your chosen language than the other.)

For the function that takes an n, a reasonably large return value (the largest Fibonacci number that fits your computer's normal word size, at a minimum) has to be supported.

Leaderboard

/* Configuration */

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

/* App */

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

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

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

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

function process() {
  var valid = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
Java, 71 chars

Single number: (Binet formula, considering 1.62 as the golden ratio))

int f(int n){return(Math.pow(1.62,n)-(Math.pow(-1.62,-n))/Math.sqrt(5)}

I know this isn't surprisingly short, however Math is beautiful and this formula is even more!


答:
Bash, 101 bytes

this is function like is_later

```<code>f(){ s=ubMAanlseovc a=$1$1$1 b=$2$2$2 c=${a:10:1} d=${b:10:1} e=${s%$c*} f=${s%$d*};((${#e}<${#f}));}
</code>```

test

```<code>$ f January December && echo later || echo not later
not later
</code>```

Title: Sort the months of the year

Body:
Write a function or program that takes string inputs, fully-spelled, English month names in title case: January, February, March, etc. (null/CR/LF terminated OK, delimited with some non-alpha character if you so choose) and either

compares two inputs, returning a Truthy value if the second input is greater (in month order) than the first. Equal values result in a Falsey value

or sorts an arbitrary sequence (list, delimited string, etc.) of them in chronological order

(The crux of the challenge is defining a method/expression that gives the correct lexicographical sort. Some languages might have a shorter answer with one or the other)

You cannot use any internal time parsing methods (e.g. strptime) to translate the month name into a number or a pre-canned mapping of month names. Use properties of the strings themselves, a parsimonious look-up table you define, or something clever.

Example

Functioning examples, though the first is prohibited by the rules...

```<code>import datetime
def is_later_month(a, b):
    '''
    Example of prohibited code because it relies on language
    features about how to parse month names
    '''
    return datetime.strptime(a, '%B') < datetime.strptime(b, '%B')
</code>```

The below versions are OK though, because we code that info

```<code>months = {
    'January':  1, 'February':  2, 'March':      3,
    'April':    4, 'May':       5, 'June':       6,
    'July':     7, 'August':    8, 'September':  9,
    'October': 10, 'November': 11, 'December':  12,
}
def is_later_month(a, b):
    """
    Returns True/False when comparing two months.
    """
    return months[a] < months[b]
</code>```

Or you could do a sorting function

```<code>months = {'as above...'}
def sort_months(l):
    """
    Sorts list and returns it. Different input and output than the above,
    but equally valid. Sorting versus comparing might be shorter in your
    favorite language.
    """
    return sorted(l, key=lambda x: months[x])
</code>```

Example tests

```<code>assert is_later_month('January', 'February')
assert is_later_month('January', 'December')
assert is_later_month('November', 'December')
assert not is_later_month('July', 'July')
assert not is_later_month('October', 'September')
</code>```

Body:
Bash, 101 bytes

this is function like is_later

f(){ s=ubMAanlseovc a=$1$1$1 b=$2$2$2 c=${a:10:1} d=${b:10:1} e=${s%$c*} f=${s%$d*};((${#e}<${#f}));}

test

$ f January December && echo later || echo not later
not later


答:
Jelly, 5 bytes

```<code>ØA»ẊX
</code>```

Try it online!

How it works

```<code>ØA«ẊX  Main link. No arguments.

ØA     Set argument and return value to the alphabet.
   Ẋ   Shuffle it.
  »    Yield the maximum of each letter in the sorted alphabet, and the
       corresponding character in the shuffled one.
    X  Pseudo-randomly select a letter of the resulting array.
</code>```

Background

Let L0, …, L25 denotes the letters of the alphabet in their natural order, and S0, …, S25 a uniformly at random selected permutation of L. Define the finite sequence M by Mn = max(Ln, Sn).

Fix n in 0, … 25 and define k as the index such that Ln = Sk.

With probability 1 / 26, Ln = Sn and n = k, so Mn = Ln and Ln occurrs once in M.

With probability 25 /26, Ln ≠ Sn and n ≠ k. In this case, the following happens.

With probability n / 25, Sn is one of L0, …, Ln - 1, so Ln > Sn and Mn = Ln.

Independently, also with probability n / 25, k is one of 0, … n - 1, so Sk > Lk and Mk = Sk = Ln.

Thus, the expected number of occurrences of Ln in M is 1/26 + 25/26 · (n/25 + n/25) = (2n + 1)/26.

Finally, if we now select a term m of M uniformly at random, the letter Ln we be chosen with probability (2n + 1)/26 / 26 = (2n + 1)/676.

This yields the following distribution of probabilities.

```<code>p(m = A) =  1/676 ≈ 0.00148
p(m = B) =  3/676 ≈ 0.00444
p(m = C) =  5/676 ≈ 0.00740
p(m = D) =  7/676 ≈ 0.01036
p(m = E) =  9/676 ≈ 0.01331
p(m = F) = 11/676 ≈ 0.01627
p(m = G) = 13/676 ≈ 0.01923
p(m = H) = 15/676 ≈ 0.02219
p(m = I) = 17/676 ≈ 0.02515
p(m = J) = 19/676 ≈ 0.02811
p(m = K) = 21/676 ≈ 0.03107
p(m = L) = 23/676 ≈ 0.03402
p(m = M) = 25/676 ≈ 0.03698
p(m = N) = 27/676 ≈ 0.03994
p(m = O) = 29/676 ≈ 0.04290
p(m = P) = 31/676 ≈ 0.04586
p(m = Q) = 33/676 ≈ 0.04882
p(m = R) = 35/676 ≈ 0.05178
p(m = S) = 37/676 ≈ 0.05473
p(m = T) = 39/676 ≈ 0.05769
p(m = U) = 41/676 ≈ 0.06065
p(m = V) = 43/676 ≈ 0.06361
p(m = W) = 45/676 ≈ 0.06657
p(m = X) = 47/676 ≈ 0.06953
p(m = Y) = 49/676 ≈ 0.07249
p(m = Z) = 51/676 ≈ 0.07544
</code>```

You can empirically verify the distribution by calling the link 100,000 times (takes a few seconds).

Body:
Jelly, 5 bytes

ØA»ẊX

Try it online!

How it works

ØA«ẊX  Main link. No arguments.

ØA     Set argument and return value to the alphabet.
   Ẋ   Shuffle it.
  »    Yield the maximum of each letter in the sorted alphabet, and the
       corresponding character in the shuffled one.
    X  Pseudo-randomly select a letter of the resulting array.

Background

Let L0, …, L25 denotes the letters of the alphabet in their natural order, and S0, …, S25 a uniformly at random selected permutation of L. Define the finite sequence M by Mn = max(Ln, Sn).

Fix n in 0, … 25 and define k as the index such that Ln = Sk.

With probability 1 / 26, Ln = Sn and n = k, so Mn = Ln and Ln occurrs once in M.

With probability 25 /26, Ln ≠ Sn and n ≠ k. In this case, the following happens.

With probability n / 25, Sn is one of L0, …, Ln - 1, so Ln > Sn and Mn = Ln.

Independently, also with probability n / 25, k is one of 0, … n - 1, so Sk > Lk and Mk = Sk = Ln.

Thus, the expected number of occurrences of Ln in M is 1/26 + 25/26 · (n/25 + n/25) = (2n + 1)/26.

Finally, if we now select a term m of M uniformly at random, the letter Ln we be chosen with probability (2n + 1)/26 / 26 = (2n + 1)/676.

This yields the following distribution of probabilities.

p(m = A) =  1/676 ≈ 0.00148
p(m = B) =  3/676 ≈ 0.00444
p(m = C) =  5/676 ≈ 0.00740
p(m = D) =  7/676 ≈ 0.01036
p(m = E) =  9/676 ≈ 0.01331
p(m = F) = 11/676 ≈ 0.01627
p(m = G) = 13/676 ≈ 0.01923
p(m = H) = 15/676 ≈ 0.02219
p(m = I) = 17/676 ≈ 0.02515
p(m = J) = 19/676 ≈ 0.02811
p(m = K) = 21/676 ≈ 0.03107
p(m = L) = 23/676 ≈ 0.03402
p(m = M) = 25/676 ≈ 0.03698
p(m = N) = 27/676 ≈ 0.03994
p(m = O) = 29/676 ≈ 0.04290
p(m = P) = 31/676 ≈ 0.04586
p(m = Q) = 33/676 ≈ 0.04882
p(m = R) = 35/676 ≈ 0.05178
p(m = S) = 37/676 ≈ 0.05473
p(m = T) = 39/676 ≈ 0.05769
p(m = U) = 41/676 ≈ 0.06065
p(m = V) = 43/676 ≈ 0.06361
p(m = W) = 45/676 ≈ 0.06657
p(m = X) = 47/676 ≈ 0.06953
p(m = Y) = 49/676 ≈ 0.07249
p(m = Z) = 51/676 ≈ 0.07544

You can empirically verify the distribution by calling the link 100,000 times (takes a few seconds).


问:
Swap 2 objects, without using a temporary variable
There are two objects:

```<code>Object1, Object2
</code>```

You can easily swap them by:

```<code>Object3 = Object1
Object1 = Object2
Object2 = Object3
</code>```

However, you must solve this problem by using no temporary object and Object1 should be changed to Object 2. (and vice versa)

答:
PHP

Objects / arrays / resources:

```<code>list($a, $b) = [$b, $a];
</code>```

Integers / booleans / strings of equal length:

```<code>$a ^= $b ^= $a ^= $b;
</code>```

Body:
PHP

Objects / arrays / resources:

list($a, $b) = [$b, $a];

Integers / booleans / strings of equal length:

$a ^= $b ^= $a ^= $b;


答:
Julia, 33 bytes

```<code>f()=['A':'Z'][ceil(26*√rand())]
</code>```

Applies the square root to RNG.

Graph showing distribution:

Generated with:

```<code>using Gadfly
plot(x=ceil(26*√rand(10000)),Geom.histogram)
</code>```

Body:
Julia, 33 bytes

f()=['A':'Z'][ceil(26*√rand())]

Applies the square root to RNG.

Graph showing distribution:

Generated with:

using Gadfly
plot(x=ceil(26*√rand(10000)),Geom.histogram)


答:
PowerShell, 96 88 63 bytes

```<code>$input|Sort{'anebarprayunulugepctovec'.IndexOf((-join$_[1,2]))}
</code>```

e.g.

```<code>PS C:\Code> 'February', 'January', 'December', 'April' | .\monthsort.ps1
January
February
April
December
</code>```

Now does the second challenge of sorting a list into order; previous versions did the comparison of two month test:

```<code>v2.
$l,$r=$args|%{-join$_[1,2]};($d='anebarprayunulugepctovec').indexof($l)-lt$d.IndexOf($r)

v1.
$l,$r=$args|%{-join$_[1,2]};$r-match('an|eb|ar|pr|ay|un|ul|ug|ep|ct|ov|ec'-split$l)[1].Trim('|')

e.g.

PS C:\code> .\Test-MonthsInOrder.ps1 January February
True
</code>```

Based on the second two characters in the month name.

Title: Sort the months of the year

Body:
PowerShell, 96 88 63 bytes

$input|Sort{'anebarprayunulugepctovec'.IndexOf((-join$_[1,2]))}

e.g.

PS C:\Code> 'February', 'January', 'December', 'April' | .\monthsort.ps1
January
February
April
December

Now does the second challenge of sorting a list into order; previous versions did the comparison of two month test:

v2.
$l,$r=$args|%{-join$_[1,2]};($d='anebarprayunulugepctovec').indexof($l)-lt$d.IndexOf($r)

v1.
$l,$r=$args|%{-join$_[1,2]};$r-match('an|eb|ar|pr|ay|un|ul|ug|ep|ct|ov|ec'-split$l)[1].Trim('|')

e.g.

PS C:\code> .\Test-MonthsInOrder.ps1 January February
True

Based on the second two characters in the month name.


问:
Make a (somewhat) self-referential string
You want to make a string where the (1-indexed) character at index n is n. When n is less than 10, this is easy: "123456789". When n is 12, for example, it becomes impossible, since numbers greater than 9 (in base 10) take up more than one character. We can compromise by dividing the string into two-character substrings: "020406081012". Now the index of the end of each substring n is n.

This can be generalized for any d-digit number. Here's an explanation for the "0991021" part of the string for a three-digit number:

```<code>Index:     ... * 97  98  99*100 101 102*103 ...
               *           *           *
               *---+---+---*---+---+---*---+
Character: ... * 0 | 9 | 9 * 1 | 0 | 2 * 1 | ...
               *---+---+---*---+---+---*---+
</code>```

If you haven't figured it out yet, you are to write a program/function that takes a string or integer and output its self-referential string as specified above. You can also output an array of single-digit numbers, chars, or single-character strings.

The given integer will always be positive and divisible by its length (e.g. 126 is divisible by 3; 4928 is divisible by 4). Your program should theoretically work for an arbitrarily large input, but you can assume it is smaller than your language's maximum integer and/or string length.

Some observations if you still don't get it: The length of the output will always be the input itself, and the numbers that appear in the output will be divisible by the number of digits in the input.

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

Test cases

```<code>1    => 1
9    => 123456789
10   => 0204060810
105  => 003006009012015018021024027030033036039042045048051054057060063066069072075078081084087090093096099102105
1004 => 00040008001200160020002400280032003600400044004800520056006000640068007200760080008400880092009601000104010801120116012001240128013201360140014401480152015601600164016801720176018001840188019201960200020402080212021602200224022802320236024002440248025202560260026402680272027602800284028802920296030003040308031203160320032403280332033603400344034803520356036003640368037203760380038403880392039604000404040804120416042004240428043204360440044404480452045604600464046804720476048004840488049204960500050405080512051605200524052805320536054005440548055205560560056405680572057605800584058805920596060006040608061206160620062406280632063606400644064806520656066006640668067206760680068406880692069607000704070807120716072007240728073207360740074407480752075607600764076807720776078007840788079207960800080408080812081608200824082808320836084008440848085208560860086408680872087608800884088808920896090009040908091209160920092409280932093609400944094809520956096009640968097209760980098409880992099610001004
</code>```

答:
R, <s>66</s> <s>64</s> 62 bytes

edit:

x=nchar(n<-scan());paste0(str_pad(1:(n/x)*x,x,,0),collapse="")

first golf attempt...


答:
CJam, 10 bytes

CJam approach #3...

```<code>26mr)mr'A+
</code>```

Try it online!

This creates a uniformly random number x between 1 and 26 and then uses that to create a uniformly random number between 0 and x-1 which is added to A. This biases results towards smaller characters.

Body:
CJam, 10 bytes

CJam approach #3...

26mr)mr'A+

Try it online!

This creates a uniformly random number x between 1 and 26 and then uses that to create a uniformly random number between 0 and x-1 which is added to A. This biases results towards smaller characters.


答:
><>, 14 bytes

```<code>lx
;>dd+%'A'+o
</code>```

 ><> is a toroidal 2D language, and the distinct probabilities part just naturally happens due to the language's only source of randomness. Try it online!

The relevant commands are:

```<code>[Row 1]
l          Push length of stack
x          Change the instruction pointer direction to one of up/down/left/right
           This gives a 50/50 chance of continuing on the first row (moving
           left/right) or going to the next row (moving up/down, wrapping if up)

[Row 2]
>          Change IP direction to right
dd+%       Take top of stack mod 26 (dd+ = 13+13 = 26)
'A'+       Add 65
o          Output as character
;          Halt
</code>```

Thus the output probabilities are:

```<code>A:  1/2^1  + 1/2^27 + 1/2^53 + ... = 33554432 / 67108863 ~ 0.50000000745
B:  1/2^2  + 1/2^28 + 1/2^54 + ... = half of chance for A
C:  1/2^3  + 1/2^29 + 1/2^55 + ... = half of chance for B
...
Z:  1/2^26 + 1/2^52 + 1/2^78 + ... = half of chance for Y
</code>```

Body:
><>, 14 bytes

lx
;>dd+%'A'+o

 ><> is a toroidal 2D language, and the distinct probabilities part just naturally happens due to the language's only source of randomness. Try it online!

The relevant commands are:

[Row 1]
l          Push length of stack
x          Change the instruction pointer direction to one of up/down/left/right
           This gives a 50/50 chance of continuing on the first row (moving
           left/right) or going to the next row (moving up/down, wrapping if up)

[Row 2]
>          Change IP direction to right
dd+%       Take top of stack mod 26 (dd+ = 13+13 = 26)
'A'+       Add 65
o          Output as character
;          Halt

Thus the output probabilities are:

A:  1/2^1  + 1/2^27 + 1/2^53 + ... = 33554432 / 67108863 ~ 0.50000000745
B:  1/2^2  + 1/2^28 + 1/2^54 + ... = half of chance for A
C:  1/2^3  + 1/2^29 + 1/2^55 + ... = half of chance for B
...
Z:  1/2^26 + 1/2^52 + 1/2^78 + ... = half of chance for Y


答:
Ruby, 47 40 39 bytes

```<code>p [*0..Time.new.year].last(121).reverse
</code>```

Thanks to @Value Ink for 7 bytes!

Ideone link: https://ideone.com/yRovUl

Title: List of possible birth years of living humans

Body:
The Challenge

Output a list of years that starts with the current year and ends 120 years ago. The birth year of every living human would be included in this list.

Details

The list should be in descending order.

Every built-in function to manipulate arrays and/or lists is allowed.

Shortest code in bytes wins.

When run this year 2016, the output would be

2016, 2015, ..., 1897, 1896

When run next year 2017, the output would be

2017, 2016, ..., 1898, 1897

Etc.

Update

Some have asked about the format of the list. As most have guessed, it doesn't matter. Insert any separator between the numbers. Intuitively most inserted a comma or space or both, newline or output an array.

Quasi superhumans like Jeanne Calment are an exception to the rule stated in my question.

Body:
Ruby, 47 40 39 bytes

p [*0..Time.new.year].last(121).reverse

Thanks to @Value Ink for 7 bytes!

Ideone link: https://ideone.com/yRovUl


答:
Labyrinth, 19 bytes

```<code>__v6%_65+.@
" )
"^2
</code>```

Try it online!

This is a loop which, at each iteration, either a) increments a counter which starts at zero or b) terminates, both with probability 50%. At the end of the loop, the counter is taken modulo 26 and added to 65 to give a letter between A and Z.

This gives a probability for A just a bit over 50%, B just a bit over 25% and so on up to Z just a bit over 1/226. In theory, there is the possibility of this running forever, but this event has probability zero as required by the challenge (in practice that's probably not possible anyway because the PRNG will return both possible results at some point over its period).

Body:
About the Series

This is a guest entry for the Random Golf of the Day series.

First off, you may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges. You can find the leaderboard along with some more information about the series in the first post.

Input

No input is taken.

Output

A single letter of the alphabet (case irrelevant), with an optional trailing newline. Each letter must have non-zero probability of being chosen, and all 26 probabilities must be distinct. To remove all ambiguity: Distinct means that there must not be two probabilities that are equal to each other.

Scoring

This is code golf. Shortest code in bytes wins.

A valid entry is a full program or function that has zero probability of not terminating.

Alphabet

To avoid confusion, the particular alphabet to be used is the Latin alphabet:

Either

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

or

```<code>abcdefghijklmnopqrstuvwxyz
</code>```

You may choose to output upper case or lower case. Alternatively, you may choose to output different cases on different runs if that helps. The probability for a given letter is the probability of that letter appearing in either case (upper or lower).

Explanation

As it won't be at all obvious from the output, please include a clear explanation of how you achieved the 26 distinct probabilities.

Leaderboard

(from here)

var QUESTION_ID=89621,OVERRIDE_USER=20283;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

```
</div>
</div>
</p>

<p><strong>The first post of the series also generates an overall leaderboard.</strong></p>

<p>To make sure that your answers show up, please start every answer with a headline, using the following Markdown template:</p>

```## Language Name, N bytes
```

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

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

(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)

Body:
Labyrinth, 19 bytes

__v6%_65+.@
" )
"^2

Try it online!

This is a loop which, at each iteration, either a) increments a counter which starts at zero or b) terminates, both with probability 50%. At the end of the loop, the counter is taken modulo 26 and added to 65 to give a letter between A and Z.

This gives a probability for A just a bit over 50%, B just a bit over 25% and so on up to Z just a bit over 1/226. In theory, there is the possibility of this running forever, but this event has probability zero as required by the challenge (in practice that's probably not possible anyway because the PRNG will return both possible results at some point over its period).


问:
Print a 10 by 10 grid of asterisks

Background

This is a standard textbook example to demonstrate for loops.

This is one of the first programs I learnt when I started learning programming ~10 years ago.

Task

You are to print this exact text:

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

Specs

You may have extra trailing newlines.

You may have extra trailing spaces (U+0020) at the end of each line, including the extra trailing newlines.

Scoring

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

答:
Grocery List, 72 bytes

```<code>G

number ten
v
z
v
P
s
u
c
l
number ten
l
b
c
p
u
n
s
e
x
u
c
p
b
n
s
e</code>```

Try it online

Title: Print a 10 by 10 grid of asterisks

Body:
Grocery List, 72 bytes

G

number ten
v
z
v
P
s
u
c
l
number ten
l
b
c
p
u
n
s
e
x
u
c
p
b
n
s
e

Try it online


答:
Forth

```<code>swap
</code>```

As i have to include more than 30 characters, here's a link to a Forth primer

Title: Swap 2 objects, without using a temporary variable

Body:
There are two objects:

```<code>Object1, Object2
</code>```

You can easily swap them by:

```<code>Object3 = Object1
Object1 = Object2
Object2 = Object3
</code>```

However, you must solve this problem by using no temporary object and Object1 should be changed to Object 2. (and vice versa)

Body:
Forth

swap

As i have to include more than 30 characters, here's a link to a Forth primer


答:
Ruby, <s>180</s> <s>158</s> <s>148</s> <s>128 + 4</s> 124 + 4 = 128 bytes

Run with $ ruby -nl (+4 bytes for -nl flags). Takes input on STDIN.

y,x=x,$_.scan(/..?/)
(puts [x.zip(y).map{|c|(("%2s"*2%c).bytes.reduce(:+)/4.0).round.chr*2}*""]*2
y,x=x,[])if$.%2<1||$<.eof?
```

<p>See it on ideone: http://ideone.com/brmP3L</p>

<h2>Ungolfed & explanation</h2>

<p>Per <code>man ruby</code>, the <code>-n</code> flag "[c]auses Ruby to assume the following loop around your script ... <code>while gets ... end</code>". The special variable <code>$_</code> contains the last line read by <code>gets</code>. The <code>-l</code> flag removes the <code>\n</code> from each line, equivalent to <code>$_.chop!</code>.</p>

<pre class="lang-ruby prettyprint-override"><code>y, x = x, $_.scan(/..?/)

( puts [
    x.zip(y).map {|c|
      (("%2s" * 2 % c).bytes.reduce(:+) / 4.0).round.chr * 2
    } * ""
  ] * 2
  y, x = x, []
) if $. % 2 < 1 || $<.eof?
</code>```

The special variable $. is the number of lines that have been read so far, and $< is STDIN. The pairs of characters from every second line gets zipped with the previous line's. The format string %2s%2s combines the characters and pads it with spaces, then the characters are averaged.

Title: Average an image

Body:
Here is an image:

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

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

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

Average the values of the ASCII characters in each section.

Round this average and convert it to an ASCII character.

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

Repeat this for all sections.

So the average of the image above looks like this:

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

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

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

Body:
Ruby, <s>180</s> <s>158</s> <s>148</s> <s>128 + 4</s> 124 + 4 = 128 bytes

Run with $ ruby -nl (+4 bytes for -nl flags). Takes input on STDIN.

y,x=x,$_.scan(/..?/)
(puts [x.zip(y).map{|c|(("%2s"*2%c).bytes.reduce(:+)/4.0).round.chr*2}*""]*2
y,x=x,[])if$.%2<1||$<.eof?

See it on ideone: http://ideone.com/brmP3L

Ungolfed & explanation

Per man ruby, the -n flag "[c]auses Ruby to assume the following loop around your script ... while gets ... end". The special variable $_ contains the last line read by gets. The -l flag removes the \n from each line, equivalent to $_.chop!.

y, x = x, $_.scan(/..?/)

( puts [
    x.zip(y).map {|c|
      (("%2s" * 2 % c).bytes.reduce(:+) / 4.0).round.chr * 2
    } * ""
  ] * 2
  y, x = x, []
) if $. % 2 < 1 || $<.eof?

The special variable $. is the number of lines that have been read so far, and $< is STDIN. The pairs of characters from every second line gets zipped with the previous line's. The format string %2s%2s combines the characters and pads it with spaces, then the characters are averaged.


答:
PHP, 40 35 33 bytes

```<code>while($i<121)echo date(Y)-$i++._;
</code>```

I'm just going to pretend that error reporting is always disabled for code golfing... :)

[Edit 1: Saved 5 bytes via manatwork]

[Edit 2: Saved 2 bytes via Titus]

Body:
PHP, 40 35 33 bytes

while($i<121)echo date(Y)-$i++._;

I'm just going to pretend that error reporting is always disabled for code golfing... :)

[Edit 1: Saved 5 bytes via manatwork]

[Edit 2: Saved 2 bytes via Titus]


问:
Minimal Word Search
Last week, we worked to create the shortest 1-D string using the top 10,000 words in the English language.  Now, lets try the same challenge in 2D!

What you need to do is to take all of the above words, and put them in a rectangle as small as possible, allowing for overlaps.  For example, if your words were ["ape","pen","ab","be","pa"], then a possible rectangle would be:

```<code>.b..
apen
</code>```

The above rectangle would give a score of 5.

Rules:

Overlapping multiple letters in a word is allowed

Words can go in any of the 8 directions

Words cannot wrap around

You can use any character for the empty locations

You need to create a word search that contains these top 10,000 words in English (according to Google).  Your score is equal to the number of characters in your word search (excluding unused characters).  If there is a tie, or if a submission is proven to be optimal, then the submission that is first posted wins.

答:
PHP

this one does the job theroratically; but 10000 are probably too many words for recursion. The script is running now. (still ran 24 hours later)

works fine on small directories, but I may make an iterative version next week.

$f=array("pen","op","po","ne","pro","aaa","abcd","dcba");
will output
abcd
apen
arop
ao..
although this is not an optimal result (scoring was changed ... I´m working on a generator). One optimal result is this:
open
.r.a
.o.a
dcba`

It is also not very fast; only removes substrings and sorts the remains by length,

the rest is brute force: try to fit the words into a rectangle, try on a larger rectangle if it fails.

btw: The substring part needs 4.5 minutes on my machine for the large directory

and cuts it down to 6,190 words; the sort on them takes 11 seconds.

```<code>$f=file('https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt');
// A: remove substrings - forward or reversed
$s=join(' ',$f);
$haystack="$s ".strrev($s);
foreach($f as$w)
{
    $r=strrev($w=trim($w)); // remove trailing line break and create reverse word
    if(!preg_match("%$w\w|\w$w%",$haystack)
        // no substr match ... now: is the reverse word in the list?
        // if so, keep only the lower one (ascii values)
        &!($w>$r&&strstr($s,$r))
        // strstr does NOT render the reverse substr regex obsolete:
        // this is only executed for $w=abc, not for $w=bca!
    )
        $g[]=$w
    ;
}

// B: sort the words by length
usort($g,function($a,$b){return strlen($a)-strlen($b);});

// C1: function to fit $words into $map
function gomap($words,$map)
{
    $h=count($map);$w=strlen($map[0]);
    $len=strlen($word=array_pop($words));
    // $x,$y=position; $d=0:horizontal, $d=1:vertical; $r=0: word, $r=1: reverse word
    for($x=$w-$len;$x>=0;$x--)for($y=$h-$len;$y>=0;$y--)for($d=0;$d<2;$d++)for($r=0;$r<2;$r++)
    {
        // does the word fit there?
        $drow=$r?strrev($word):$word;
        for($ok=1,$i=0;$ok&$i<$len;$i++)
            $ok=in_array($map[$y+$d*$i][$x+$i-$d*$i], [' ',$drow[$i]])
        ;
        // it does, paint it
        if($ok)
        {
            for($i=0;$i<$len;$i++)
                $map[$y+$d*$i][$x+$i-$d*$i]=$drow[$i];
            if(!count($words))      // this was the last word: return map
                return $map;
            else                    // there are more words: recurse
                if ($ok=gomap($words,$map))
                    return $ok;
            // no fit, try next position
        }
    }
    return 0;
}

// C2: rectangle loop
for($h=0;++$h;)for($w=0;$w++<$h;)   // define a rectangle
{
    // and try to fit the words in there
    if($map=gomap($g,
        array_fill(0,$h,str_repeat(' ',$w))
    ))
    {
        // words fit; output and break loops
        echo '```',implode("\n",$map),'```';
        break 2;
    }
}
</code>```

Title: Minimal Word Search

Body:
PHP

this one does the job theroratically; but 10000 are probably too many words for recursion. The script is running now. (still ran 24 hours later)

works fine on small directories, but I may make an iterative version next week.

$f=array("pen","op","po","ne","pro","aaa","abcd","dcba");
will output
abcd
apen
arop
ao..
although this is not an optimal result (scoring was changed ... I´m working on a generator). One optimal result is this:
open
.r.a
.o.a
dcba`

It is also not very fast; only removes substrings and sorts the remains by length,

the rest is brute force: try to fit the words into a rectangle, try on a larger rectangle if it fails.

btw: The substring part needs 4.5 minutes on my machine for the large directory

and cuts it down to 6,190 words; the sort on them takes 11 seconds.

$f=file('https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt');
// A: remove substrings - forward or reversed
$s=join(' ',$f);
$haystack="$s ".strrev($s);
foreach($f as$w)
{
    $r=strrev($w=trim($w)); // remove trailing line break and create reverse word
    if(!preg_match("%$w\w|\w$w%",$haystack)
        // no substr match ... now: is the reverse word in the list?
        // if so, keep only the lower one (ascii values)
        &!($w>$r&&strstr($s,$r))
        // strstr does NOT render the reverse substr regex obsolete:
        // this is only executed for $w=abc, not for $w=bca!
    )
        $g[]=$w
    ;
}

// B: sort the words by length
usort($g,function($a,$b){return strlen($a)-strlen($b);});

// C1: function to fit $words into $map
function gomap($words,$map)
{
    $h=count($map);$w=strlen($map[0]);
    $len=strlen($word=array_pop($words));
    // $x,$y=position; $d=0:horizontal, $d=1:vertical; $r=0: word, $r=1: reverse word
    for($x=$w-$len;$x>=0;$x--)for($y=$h-$len;$y>=0;$y--)for($d=0;$d<2;$d++)for($r=0;$r<2;$r++)
    {
        // does the word fit there?
        $drow=$r?strrev($word):$word;
        for($ok=1,$i=0;$ok&$i<$len;$i++)
            $ok=in_array($map[$y+$d*$i][$x+$i-$d*$i], [' ',$drow[$i]])
        ;
        // it does, paint it
        if($ok)
        {
            for($i=0;$i<$len;$i++)
                $map[$y+$d*$i][$x+$i-$d*$i]=$drow[$i];
            if(!count($words))      // this was the last word: return map
                return $map;
            else                    // there are more words: recurse
                if ($ok=gomap($words,$map))
                    return $ok;
            // no fit, try next position
        }
    }
    return 0;
}

// C2: rectangle loop
for($h=0;++$h;)for($w=0;$w++<$h;)   // define a rectangle
{
    // and try to fit the words in there
    if($map=gomap($g,
        array_fill(0,$h,str_repeat(' ',$w))
    ))
    {
        // words fit; output and break loops
        echo '<pre>',implode("\n",$map),'</pre>';
        break 2;
    }
}


问:
Automatic box expander

Introduction

Sometimes, my boxes are too small to fit anything in it. I need you to make a box expander! So, what makes a box a box in this challenge.

```<code> OOOO
O    O
O    O
O    O
 OOOO
</code>```

The corners of the box are always spaces. The box itself can be made out of the same character. That character can be any printable ASCII character, except a space. So, that's these characters:

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

The side lengths of the box above are 4, 3. You may assume that the side length is always positive. That means that this is the smallest box you need to handle:

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

In order to expand a box, you need to increment each side length. Let's go through this, step by step, with the above example. We first take the upper side of the box, which is:

```<code> OOOO
</code>```

We expand this by one, so we get:

```<code> OOOOO
</code>```

This is the upper and lower part of the box now. After that, we do the same with the sides on the left and right:

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

Becomes:

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

Now we reassemble the box, which results into:

```<code> OOOOO
O     O
O     O
O     O
O     O
 OOOOO
</code>```

The task

Given a box, expand it by 1. The box can be given in multiple lines, or in an array.

Test cases

```<code> OOOO          OOOOO
O    O    >   O     O
 OOOO         O     O
               OOOOO

 XXXXXX        XXXXXXX
X      X  >   X       X
X      X      X       X
 XXXXXX       X       X
               XXXXXXX

 ~             ~~
~ ~       >   ~  ~
 ~            ~  ~
               ~~
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

答:
JavaScript (ES6), <s>57</s> <s>53</s> 52 bytes

```<code>s=>s.replace(/^.(.)/gm,s="$&$1").replace(/(\n.*)/,s)
</code>```

Explanation: The first regexp duplicates the second column and the second regexp duplicates the second row, thus enlarging the box as desired. Edit: Saved 4 bytes thanks to MartinEnder♦.

Title: Automatic box expander

Body:
JavaScript (ES6), <s>57</s> <s>53</s> 52 bytes

s=>s.replace(/^.(.)/gm,s="$&$1").replace(/(\n.*)/,s)

Explanation: The first regexp duplicates the second column and the second regexp duplicates the second row, thus enlarging the box as desired. Edit: Saved 4 bytes thanks to MartinEnder♦.


答:
Retina, 20 bytes

Byte count assumes ISO 8859-1 encoding.

```<code>1`¶
¶$%'¶
%2=`.
$&$&
</code>```

Try it online! (There's several additional lines which enable a test suite where the test cases are separated by two linefeeds.)

Explanation

```<code>1`¶
¶$%'¶
</code>```

1 is a limit which restricts Retina to apply the substitution only to the first match it finds. ¶ matches a single linefeed, so we only need to consider replacing the linefeed at the end of the first line. It is replace with ¶$%'¶, where $%' inserts the entire line following the match (a Retina-specific substitution element). Hence, this duplicates the second line.

```<code>%2=`.
$&$&
</code>```

Here, % is per-line mode, so each line is processed individually, and the lines are joined again afterwards. 2= is also a limit. This one means "apply the substitution only to the second match". The match itself is simple a single character and the substitution duplicates it. Hence, this stage duplicates the second column.

Title: Automatic box expander

Body:
Introduction

Sometimes, my boxes are too small to fit anything in it. I need you to make a box expander! So, what makes a box a box in this challenge.

```<code> OOOO
O    O
O    O
O    O
 OOOO
</code>```

The corners of the box are always spaces. The box itself can be made out of the same character. That character can be any printable ASCII character, except a space. So, that's these characters:

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

The side lengths of the box above are 4, 3. You may assume that the side length is always positive. That means that this is the smallest box you need to handle:

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

In order to expand a box, you need to increment each side length. Let's go through this, step by step, with the above example. We first take the upper side of the box, which is:

```<code> OOOO
</code>```

We expand this by one, so we get:

```<code> OOOOO
</code>```

This is the upper and lower part of the box now. After that, we do the same with the sides on the left and right:

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

Becomes:

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

Now we reassemble the box, which results into:

```<code> OOOOO
O     O
O     O
O     O
O     O
 OOOOO
</code>```

The task

Given a box, expand it by 1. The box can be given in multiple lines, or in an array.

Test cases

```<code> OOOO          OOOOO
O    O    >   O     O
 OOOO         O     O
               OOOOO

 XXXXXX        XXXXXXX
X      X  >   X       X
X      X      X       X
 XXXXXX       X       X
               XXXXXXX

 ~             ~~
~ ~       >   ~  ~
 ~            ~  ~
               ~~
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

Body:
Retina, 20 bytes

Byte count assumes ISO 8859-1 encoding.

1`¶
¶$%'¶
%2=`.
$&$&

Try it online! (There's several additional lines which enable a test suite where the test cases are separated by two linefeeds.)

Explanation

1`¶
¶$%'¶

1 is a limit which restricts Retina to apply the substitution only to the first match it finds. ¶ matches a single linefeed, so we only need to consider replacing the linefeed at the end of the first line. It is replace with ¶$%'¶, where $%' inserts the entire line following the match (a Retina-specific substitution element). Hence, this duplicates the second line.

%2=`.
$&$&

Here, % is per-line mode, so each line is processed individually, and the lines are joined again afterwards. 2= is also a limit. This one means "apply the substitution only to the second match". The match itself is simple a single character and the substitution duplicates it. Hence, this stage duplicates the second column.


答:
PowerShell v2+, <s>57</s> <s>53</s> 52 bytes

```<code>param($n)($n-replace'^.(.)','$&$1')[0,1+1..$n.count]
</code>```

Slightly similar to Neil's JavaScript answer. The first replace matches the beginning of the line and the next two characters, and replaces them with the first character and second-character-twice. Instead of a second replace, it's swapped out for array-indexing to duplicate the second line. Takes input as an array of strings. The resultant array slices are left on the pipeline and printing is implicit.

Saved 4 bytes thanks to Martin.

Some examples:

```<code>PS C:\Tools\Scripts\golfing> .\automatic-box-expander.ps1 ' oooo ','o    o',' oooo '
 ooooo
o     o
o     o
 ooooo

PS C:\Tools\Scripts\golfing> .\automatic-box-expander.ps1 ' # ','# #',' # '
 ##
#  #
#  #
 ##
</code>```

Title: Automatic box expander

Body:
PowerShell v2+, <s>57</s> <s>53</s> 52 bytes

param($n)($n-replace'^.(.)','$&$1')[0,1+1..$n.count]

Slightly similar to Neil's JavaScript answer. The first replace matches the beginning of the line and the next two characters, and replaces them with the first character and second-character-twice. Instead of a second replace, it's swapped out for array-indexing to duplicate the second line. Takes input as an array of strings. The resultant array slices are left on the pipeline and printing is implicit.

Saved 4 bytes thanks to Martin.

Some examples:

PS C:\Tools\Scripts\golfing> .\automatic-box-expander.ps1 ' oooo ','o    o',' oooo '
 ooooo
o     o
o     o
 ooooo

PS C:\Tools\Scripts\golfing> .\automatic-box-expander.ps1 ' # ','# #',' # '
 ##
#  #
#  #
 ##