问:
What's the Binary Time?

What's the Binary Time?

Everybody knows what the normal time is. It's up there in the top-right (or wherever you put it) of your screen. But a question people rarely seem to ask themselves is this: What's the binary time?

Binary Time

Binary Time (True Binary Time) works by first reading the most significant bit (MSB) of the number. If that number is 0, the time expressed is before noon. If that number is 1, the time expressed is after noon. The next bit splits the half of the day the first bit expressed into two more equal halves, this time of 6 hours. The following bit splits into 3 hours, the next 90 minutes, and so on. Times like 12:00:00, where it seems it should be neither, become 1.

I can only understand this strange system of timing, so I need a program to convert to that for me. But as binary numbers are Base-2, and 2 is a small number, your program must be as short as possible.

Requirements

Your program should take a time (as 24-hour-time) as input and output the corresponding binary time number.

The output number should have 16-bit precision (the number should be 16 digits long).

You cannot use a builtin that does all of that conversion for you.

You should floor if it needs to be rounded.

Rules

Standard loopholes are forbidden.

Your program should not write anything to STDERR.

Test Cases

00:00:00 ==> 0000000000000000

12:00:00 ==> 1000000000000000

01:30:00 ==> 0001000000000000

10:33:06 ==> 0111000010001101

09:57:30 ==> 0110101000111000

06:00:00 ==> 0100000000000000

18:00:00 ==> 1100000000000000

Scoring

To win, as I mentioned earlier, you must have the least bytes.

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Title: What's the Binary Time?

Body:
Pyth, <s>31</s> 27 bytes

.[\016.Bs*512cisMcQ\:60 675

Test suite.

Converts the input into number of seconds passed, multiply by a factor of 2^16 / 24*60*60, and then floor and convert to 16-bit binary.

Saved 4 bytes by simplifying 65536/86400 into 512/675 (stupid me).

Input/output

00:00:00    0000000000000000
11:00:00    0111010101010101
12:00:00    1000000000000000
01:30:00    0001000000000000
10:33:06    0111000010001101
09:57:30    0110101000111000
06:00:00    0100000000000000
18:00:00    1100000000000000
23:59:59    1111111111111111


问:
Find the smallest number bigger than the input whose digital sum is the input
"Digital sum" refers to the sum of all the digits in a number.

For example, the digital sum of 1324 is 10, because 1+3+2+4 = 10.

The challenge is to write a program/function to calculate the smallest number bigger than the input whose digital sum is the input.

Example with walkthrough

As an example, take the number 9 as the input:

```<code>9 = 1+8 -> 18
9 = 2+7 -> 27
9 = 3+6 -> 36
...
9 = 8+1 -> 81
9 = 9+0 -> 90
</code>```

The valid output would be the smallest number above, which is 18.

Specs

Note that 9 is not the valid output for this example, because the reversed number must be greater than the original number.

Note that the input will be positive.

Test-Cases:

```<code> 2 => 11      (2 = 1 + 1)
 8 => 17      (8 = 1 + 7)
12 => 39     (12 = 3 + 9)
16 => 79     (16 = 7 + 9)
18 => 99     (18 = 9 + 9)
24 => 699    (24 = 6 + 9 + 9)
32 => 5999   (32 = 5 + 9 + 9 + 9)
</code>```

References:

This is OEIS A161561.

Edit: Added an additional Testcase (18)

Thanks to Martin Ender for the Leaderboard Snippet

var QUESTION_ID=81047,OVERRIDE_USER=31373;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

```

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

```<code>`QtV!UsG-
</code>```

Try it online!

Explanation

```<code>`        % Do...while
  Q      %   Add 1. Takes input implicitly the first time
  t      %   Duplicate
  V!Us   %   To string, transpose, to number, sum. Gives sum of digits
  G-     %   Subtract input. If 0, the loop ends and the stack is implicitly displayed
</code>```

ContentLicense: CC BY-SA 3.0

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

`QtV!UsG-

Try it online!

Explanation

`        % Do...while
  Q      %   Add 1. Takes input implicitly the first time
  t      %   Duplicate
  V!Us   %   To string, transpose, to number, sum. Gives sum of digits
  G-     %   Subtract input. If 0, the loop ends and the stack is implicitly displayed


答:
05AB1E, <s>19</s> <s>17</s> 8 bytes

Code:

```<code>[>DSO¹Q#
</code>```

Explained:

```<code>[            # start infinite loop
 >           # increase loop variable, will initially be input
  DSO        # make a copy and sum the digits
     ¹Q#     # if it equals the input, break
             # else return to start of loop
             # implicitly print
</code>```

Try it online

Edit: Saved 9 bytes thanks to @Adnan

Title: Find the smallest number bigger than the input whose digital sum is the input

Body:
"Digital sum" refers to the sum of all the digits in a number.

For example, the digital sum of 1324 is 10, because 1+3+2+4 = 10.

The challenge is to write a program/function to calculate the smallest number bigger than the input whose digital sum is the input.

Example with walkthrough

As an example, take the number 9 as the input:

```<code>9 = 1+8 -> 18
9 = 2+7 -> 27
9 = 3+6 -> 36
...
9 = 8+1 -> 81
9 = 9+0 -> 90
</code>```

The valid output would be the smallest number above, which is 18.

Specs

Note that 9 is not the valid output for this example, because the reversed number must be greater than the original number.

Note that the input will be positive.

Test-Cases:

```<code> 2 => 11      (2 = 1 + 1)
 8 => 17      (8 = 1 + 7)
12 => 39     (12 = 3 + 9)
16 => 79     (16 = 7 + 9)
18 => 99     (18 = 9 + 9)
24 => 699    (24 = 6 + 9 + 9)
32 => 5999   (32 = 5 + 9 + 9 + 9)
</code>```

References:

This is OEIS A161561.

Edit: Added an additional Testcase (18)

Thanks to Martin Ender for the Leaderboard Snippet

var QUESTION_ID=81047,OVERRIDE_USER=31373;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:
05AB1E, <s>19</s> <s>17</s> 8 bytes

Code:

[>DSO¹Q#

Explained:

[            # start infinite loop
 >           # increase loop variable, will initially be input
  DSO        # make a copy and sum the digits
     ¹Q#     # if it equals the input, break
             # else return to start of loop
             # implicitly print

Try it online

Edit: Saved 9 bytes thanks to @Adnan


问:
24 and 12 Hour Times
Write a program or function with no input that prints or returns this string of 24-hour and 12-hour times:

```<code>00:00 12:00am
01:00  1:00am
02:00  2:00am
03:00  3:00am
04:00  4:00am
05:00  5:00am
06:00  6:00am
07:00  7:00am
08:00  8:00am
09:00  9:00am
10:00 10:00am
11:00 11:00am
12:00 12:00pm
13:00  1:00pm
14:00  2:00pm
15:00  3:00pm
16:00  4:00pm
17:00  5:00pm
18:00  6:00pm
19:00  7:00pm
20:00  8:00pm
21:00  9:00pm
22:00 10:00pm
23:00 11:00pm
</code>```

The string must be output exactly as it appears here. The only exception is that it may optionally have a single trailing newline.

So the MD5 hash of your output should be

```<code>827ae6e2dbb1df494930baedb3ee2653
</code>```

if you do not have a trailing newline and

```<code>cd4c3d18abee9bafb495f390a919a13f
</code>```

if you do. (Your hash could be different if your system uses another type of newline but that's OK.)

The shortest code in bytes wins. Tiebreaker is earlier answer.

Title: 24 and 12 Hour Times

Body:
Swift, 85 bytes

for x in 0...23{print(String(format:"%02d:00 %2d:00\(x<12 ?"a":"p")m",x,12+x % -12))}


答:
APL (Dyalog), <s>24</s> 21 bytes

The rules have now been clarified.

Prompts for time as 3-element list.

```<code>(16/2)⊤⌊512×675÷⍨60⊥⎕
</code>```

Edit: Updated (⌈ → ⌊) to match new result for 10:33:06.

Try it online!

⎕ prompt for input

60⊥ evaluate in base-60

675÷⍨ divide by 675

512× multiply by 512

⌊ floor

(…)⊤ convert to (mnemonic: upside-down base is anti-base) the following number system:

 16/2 replicate 2 sixteen times (i.e. 16-bit binary)

Title: What's the Binary Time?

Body:
What's the Binary Time?

Everybody knows what the normal time is. It's up there in the top-right (or wherever you put it) of your screen. But a question people rarely seem to ask themselves is this: What's the binary time?

Binary Time

Binary Time (True Binary Time) works by first reading the most significant bit (MSB) of the number. If that number is 0, the time expressed is before noon. If that number is 1, the time expressed is after noon. The next bit splits the half of the day the first bit expressed into two more equal halves, this time of 6 hours. The following bit splits into 3 hours, the next 90 minutes, and so on. Times like 12:00:00, where it seems it should be neither, become 1.

I can only understand this strange system of timing, so I need a program to convert to that for me. But as binary numbers are Base-2, and 2 is a small number, your program must be as short as possible.

Requirements

Your program should take a time (as 24-hour-time) as input and output the corresponding binary time number.

The output number should have 16-bit precision (the number should be 16 digits long).

You cannot use a builtin that does all of that conversion for you.

You should floor if it needs to be rounded.

Rules

Standard loopholes are forbidden.

Your program should not write anything to STDERR.

Test Cases

00:00:00 ==> 0000000000000000

12:00:00 ==> 1000000000000000

01:30:00 ==> 0001000000000000

10:33:06 ==> 0111000010001101

09:57:30 ==> 0110101000111000

06:00:00 ==> 0100000000000000

18:00:00 ==> 1100000000000000

Scoring

To win, as I mentioned earlier, you must have the least bytes.

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
APL (Dyalog), <s>24</s> 21 bytes

The rules have now been clarified.

Prompts for time as 3-element list.

(16/2)⊤⌊512×675÷⍨60⊥⎕

Edit: Updated (⌈ → ⌊) to match new result for 10:33:06.

Try it online!

⎕ prompt for input

60⊥ evaluate in base-60

675÷⍨ divide by 675

512× multiply by 512

⌊ floor

(…)⊤ convert to (mnemonic: upside-down base is anti-base) the following number system:

 16/2 replicate 2 sixteen times (i.e. 16-bit binary)


答:
PHP, <s>67</s> <s>65</s> 64 bytes

This uses IBM-850 encoding.

```<code>for(;$i<24;)printf(~┌¤═ø┼¤¤┌╠ø┼¤¤┌îÆ§,$i,$i%12?:12,$i++>11?p:a);
</code>```

With the unencoded string (66 bytes):

```<code>for(;$i<24;)printf("%02d:00%3d:00%sm\n",$i,$i%12?:12,$i++>11?p:a);
</code>```

Run like this:

```<code>php -n -r 'for(;$i<24;)printf(~┌¤═ø┼¤¤┌╠ø┼¤¤┌îÆ§,$i,$i%12?:12,$i++>11?p:a);'
</code>```

Tweaks

Saved 2 bytes by improving sprintf format

Saved a byte by getting rid of unnecessary space (thx @Titus)

Title: 24 and 12 Hour Times

Body:
Write a program or function with no input that prints or returns this string of 24-hour and 12-hour times:

```<code>00:00 12:00am
01:00  1:00am
02:00  2:00am
03:00  3:00am
04:00  4:00am
05:00  5:00am
06:00  6:00am
07:00  7:00am
08:00  8:00am
09:00  9:00am
10:00 10:00am
11:00 11:00am
12:00 12:00pm
13:00  1:00pm
14:00  2:00pm
15:00  3:00pm
16:00  4:00pm
17:00  5:00pm
18:00  6:00pm
19:00  7:00pm
20:00  8:00pm
21:00  9:00pm
22:00 10:00pm
23:00 11:00pm
</code>```

The string must be output exactly as it appears here. The only exception is that it may optionally have a single trailing newline.

So the MD5 hash of your output should be

```<code>827ae6e2dbb1df494930baedb3ee2653
</code>```

if you do not have a trailing newline and

```<code>cd4c3d18abee9bafb495f390a919a13f
</code>```

if you do. (Your hash could be different if your system uses another type of newline but that's OK.)

The shortest code in bytes wins. Tiebreaker is earlier answer.

Body:
PHP, <s>67</s> <s>65</s> 64 bytes

This uses IBM-850 encoding.

for(;$i<24;)printf(~┌¤═ø┼¤¤┌╠ø┼¤¤┌îÆ§,$i,$i%12?:12,$i++>11?p:a);

With the unencoded string (66 bytes):

for(;$i<24;)printf("%02d:00%3d:00%sm\n",$i,$i%12?:12,$i++>11?p:a);

Run like this:

php -n -r 'for(;$i<24;)printf(~┌¤═ø┼¤¤┌╠ø┼¤¤┌îÆ§,$i,$i%12?:12,$i++>11?p:a);'

Tweaks

Saved 2 bytes by improving sprintf format

Saved a byte by getting rid of unnecessary space (thx @Titus)


问:
Self Referential Polynomials
For every given degree \$n\$ it is possible to construct (at least one) an integral polynomial \$p \in \mathbb Z[X]\$ such that \$p(k)\$ (\$p\$ evaluated in \$k\$) is the coefficient of the term \$x^k\$ in the polynomial for all \$0 \leqslant k \leqslant n\$. To make them unique, we require the leading coefficient (the coefficient of \$x^n\$) to be positive and minimal.

These polynomials have some interesting properties, you can find some references in the thread that inspired me to do this challenge. You can also find those polynomials in https://oeis.org/A103423

One of the a priori unexpected properties is how the roots behave depending on \$n\$:

source (by /u/zorngov and /u/EpicSauceSc2)

Task

Given a nonnegative integer \$n\$ output the self referential integral polynomial of degree \$n\$ with minimal positive leading coefficient.

Details

The output can be in any human readable form, as string x^2-x-1, or also as a list of coefficients [1,-1,-1]. (The order of the coefficients can also be the other way around, it just needs to be consistent.)

First few outputs

```<code>n=0: 1
n=1: x
n=2: x^2-x-1
n=3: 10*x^3-29*x^2-6*x+19
n=4: 57*x^4-325*x^3+287*x^2+423*x-19
n=5: 12813*x^5-120862*x^4+291323*x^3+44088*x^2-355855*x-227362
</code>```

ContentLicense: CC BY-SA 4.0

Title: Self Referential Polynomials

Body:
Mathematica, 55 bytes

NullSpace@Table[x^c-Boole[r==c]/.x->r,{r,0,#},{c,0,#}]&

Output is the list coefficients, beginning from the constant term. Example:

In[1084] := Do[Print[%1077[n] // StandardForm], {n, 0, 7}]

{{1}}

{{0,1}}

{{-1,-1,1}}

{{19,-6,-29,10}}

{{-19,423,287,-325,57}}

{{-227362,-355855,44088,291323,-120862,12813}}

{{145991969,64989065,-123338281,-85635661,79841909,-18146731,1286795}}

{{-5958511844199,3384370785404,8437850634901,489428412300,-4499161007143,1776194531596,-258931801371,13131073916}}

This simply finds the vector such that (A - I)v = 0, similar to the MAPLE code in OEIS. The NullSpace method seems to always pick the minimal positive number for the last element, which matches the task description.

The x^c-…/.x->r indirection is to prevent having 0^0 == Indeterminate.


答:
Sage, 74 bytes

lambda n:kernel(matrix(n+1,[j^-i-(-i==j)for i in[-n..0]for j in[0..n]])).0
```

The -i and [-n..0] could be i and [0..n], if not for the positive leading coefficient requirement.

Try it on Sage Cell

Title: Self Referential Polynomials

Body:
For every given degree \$n\$ it is possible to construct (at least one) an integral polynomial \$p \in \mathbb Z[X]\$ such that \$p(k)\$ (\$p\$ evaluated in \$k\$) is the coefficient of the term \$x^k\$ in the polynomial for all \$0 \leqslant k \leqslant n\$. To make them unique, we require the leading coefficient (the coefficient of \$x^n\$) to be positive and minimal.

These polynomials have some interesting properties, you can find some references in the thread that inspired me to do this challenge. You can also find those polynomials in https://oeis.org/A103423

One of the a priori unexpected properties is how the roots behave depending on \$n\$:

source (by /u/zorngov and /u/EpicSauceSc2)

Task

Given a nonnegative integer \$n\$ output the self referential integral polynomial of degree \$n\$ with minimal positive leading coefficient.

Details

The output can be in any human readable form, as string x^2-x-1, or also as a list of coefficients [1,-1,-1]. (The order of the coefficients can also be the other way around, it just needs to be consistent.)

First few outputs

```<code>n=0: 1
n=1: x
n=2: x^2-x-1
n=3: 10*x^3-29*x^2-6*x+19
n=4: 57*x^4-325*x^3+287*x^2+423*x-19
n=5: 12813*x^5-120862*x^4+291323*x^3+44088*x^2-355855*x-227362
</code>```

Body:
Sage, 74 bytes

lambda n:kernel(matrix(n+1,[j^-i-(-i==j)for i in[-n..0]for j in[0..n]])).0

The -i and [-n..0] could be i and [0..n], if not for the positive leading coefficient requirement.

Try it on Sage Cell


答:
JavaScript (ES2015), 45 39 33 bytes

Saved another 6 bytes thanks to @Conor O'Brien and @Shaun H.

I think I'll leave it as is, because this version differs from @Neil's answer by using String.repeat().

```<code>v=>+(v>9?v%9+'9'.repeat(v/9):v+9)
</code>```

Previous version (saved 6 bytes thanks to @Qwertiy):

```<code>f=v=>+(v/9>1?v%9+'9'.repeat(v/9|0):v+9)
</code>```

First version:

```<code>f=v=>+(v/9>1?v%9+'9'.repeat(~~(v/9)):'1'+v-1)
</code>```

Body:
JavaScript (ES2015), 45 39 33 bytes

Saved another 6 bytes thanks to @Conor O'Brien and @Shaun H.

I think I'll leave it as is, because this version differs from @Neil's answer by using String.repeat().

v=>+(v>9?v%9+'9'.repeat(v/9):v+9)

Previous version (saved 6 bytes thanks to @Qwertiy):

f=v=>+(v/9>1?v%9+'9'.repeat(v/9|0):v+9)

First version:

f=v=>+(v/9>1?v%9+'9'.repeat(~~(v/9)):'1'+v-1)


答:
Python 3, <s>128</s> <s>94</s> <s>84</s> 74 Bytes

Without output, direct approach, beginner codegolfer ;)

```<code>def r(n):
 m=n
 while 1:
  m+=1
  if sum(map(int,str(m)))==n:return(m)
</code>```

Body:
Python 3, <s>128</s> <s>94</s> <s>84</s> 74 Bytes

Without output, direct approach, beginner codegolfer ;)

def r(n):
 m=n
 while 1:
  m+=1
  if sum(map(int,str(m)))==n:return(m)


答:
PowerShell v2+, 62 bytes

```<code>param($n)for($a=$n+1;([char[]]"$a"-join'+'|iex)-ne$n;$a++){}$a
</code>```

Takes input $n then executes a for loop. We initialize the loop by setting our target number, $a, to be one larger than $n (since it has to be bigger, plus this ensures 1..9 work correctly). Each loop we increment $a++. Nothing happens in the loop proper, but the conditional is where the program logic happens. We're literally taking the target number as a string, casting it as a char-array, -joining the array with + and then piping it to iex (similar to eval). We test whether that's equal to our input number or not, and continue looping accordingly. Once we've exited the loop, we've reached where our target number is digit-sum equal to our input number, so $a is placed on the pipeline and output is implicit.

For reference, here's the "construct a string with the appropriate number of 9's" method that other folks have done, at 67 bytes

```<code>param($n)(($n+9),(+(""+($n%9)+'9'*(($n/9)-replace'\..*'))))[$n-gt9]
</code>```

or the "pure integer arithmetic" method that other folks have done, at 70 bytes

```<code>param($n)(($n+9),("(1+$n%9)*1e$(($n/9)-replace'\..*')-1"|iex))[$n-gt9]
</code>```

Neither of which are shorter, but both of which are more interesting.

Body:
PowerShell v2+, 62 bytes

param($n)for($a=$n+1;([char[]]"$a"-join'+'|iex)-ne$n;$a++){}$a

Takes input $n then executes a for loop. We initialize the loop by setting our target number, $a, to be one larger than $n (since it has to be bigger, plus this ensures 1..9 work correctly). Each loop we increment $a++. Nothing happens in the loop proper, but the conditional is where the program logic happens. We're literally taking the target number as a string, casting it as a char-array, -joining the array with + and then piping it to iex (similar to eval). We test whether that's equal to our input number or not, and continue looping accordingly. Once we've exited the loop, we've reached where our target number is digit-sum equal to our input number, so $a is placed on the pipeline and output is implicit.

For reference, here's the "construct a string with the appropriate number of 9's" method that other folks have done, at 67 bytes

param($n)(($n+9),(+(""+($n%9)+'9'*(($n/9)-replace'\..*'))))[$n-gt9]

or the "pure integer arithmetic" method that other folks have done, at 70 bytes

param($n)(($n+9),("(1+$n%9)*1e$(($n/9)-replace'\..*')-1"|iex))[$n-gt9]

Neither of which are shorter, but both of which are more interesting.


Title: What's the Binary Time?

Body:
JavaScript (ES6), 72 <s>76</s> bytes

Edit 4 bytes save thx @Neil

<s>Still unclear about the rounding. </s>This one truncates and that's ok.

t=>(t.split`:`.map(v=>t=+v+60*~~t),t*512/675|65536).toString(2).slice(1)

Test

f=t=>(t.split`:`.map(v=>t=+v+60*~~t),t*512/675|65536).toString(2).slice(1)

function test() {
  var v=I.value
  R.textContent=f(v)
}

test()

;`00:00:00 ==> 0000000000000000
12:00:00 ==> 1000000000000000
01:30:00 ==> 0001000000000000
10:33:06 ==> 0111000010001101
09:57:30 ==> 0110101000111000
06:00:00 ==> 0100000000000000
18:00:00 ==> 1100000000000000`
.split('\n').forEach(t=>{
  [i,k]=t.split(' ==> ')
  r=f(i)
  ok=r==k
  O.textContent += (ok ? 'OK ':'KO ')+ i + ' -> ' + r + (ok? '\n' : ' Expected '+k+'\n')
})

<input id=I value='12:34:56' oninput=test()>
<span id=R></span>
<pre id=O></pre>


答:
TSQL(sqlserver 2012), 103 bytes

```<code>DECLARE @d datetime = '10:33:06'

DECLARE @ char(16)='',@x INT=cast(@d as real)*131072WHILE
len(@)<16SELECT @x/=2,@=concat(@x%2,@)PRINT @
</code>```

Try it online

Ungolfed

```<code>DECLARE @d datetime = '10:33:06'

DECLARE @ char(16)='',
        @x INT=cast(@d as real)*131072
WHILE len(@)<16
SELECT @x/=2,@=concat(@x%2,@)
PRINT @
</code>```

TSQL(sqlserver 2012), <s>119</s> 106 bytes

Also included a different version without the variable @x, however it was a few bytes longer. Including the ungolfed version for those interested:

```<code>DECLARE @d datetime = '23:59:59'

DECLARE @ varchar(16) =''
WHILE LEN(@)<16
SET @+=LEFT(CAST(@d as decimal(9,9))*2*POWER(2,LEN(@))%2,1)
PRINT @
</code>```

Title: What's the Binary Time?

Body:
TSQL(sqlserver 2012), 103 bytes

DECLARE @d datetime = '10:33:06'

DECLARE @ char(16)='',@x INT=cast(@d as real)*131072WHILE
len(@)<16SELECT @x/=2,@=concat(@x%2,@)PRINT @

Try it online

Ungolfed

DECLARE @d datetime = '10:33:06'

DECLARE @ char(16)='',
        @x INT=cast(@d as real)*131072
WHILE len(@)<16
SELECT @x/=2,@=concat(@x%2,@)
PRINT @

TSQL(sqlserver 2012), <s>119</s> 106 bytes

Also included a different version without the variable @x, however it was a few bytes longer. Including the ungolfed version for those interested:

DECLARE @d datetime = '23:59:59'

DECLARE @ varchar(16) =''
WHILE LEN(@)<16
SET @+=LEFT(CAST(@d as decimal(9,9))*2*POWER(2,LEN(@))%2,1)
PRINT @


答:
Ruby, 38 bytes

```<code>f=->n{n<11?n+9:"#{n<19?n-9:f.(n-9)}9"}
</code>```

This answer returns a string or int depending on input size. It is a recursive solution that asks for a solution for 9 less then adds a "9" to the end.

Ruby, 39 bytes

```<code>f=->n{n<11?n+9:(n<19?n-9:f.(n-9))*10+9}
</code>```

For one more byte, this answer always returns an int. same algorithm as above but with numbers.

Body:
Ruby, 38 bytes

f=->n{n<11?n+9:"#{n<19?n-9:f.(n-9)}9"}

This answer returns a string or int depending on input size. It is a recursive solution that asks for a solution for 9 less then adds a "9" to the end.

Ruby, 39 bytes

f=->n{n<11?n+9:(n<19?n-9:f.(n-9))*10+9}

For one more byte, this answer always returns an int. same algorithm as above but with numbers.


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

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

The Rules

Each submission must be a full program.

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

The program must not write anything to STDERR.

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

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

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

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

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

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

For inspiration, check the Hello World Collection.

The Catalogue

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

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

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

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

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

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

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

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

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
EEL, 93 bytes

(Also known as Extensible Esoteric Language)

```<code>def(z|-1;x;z)
def(d|c;z)
72
d
101
d
108
c
d
111
d
44
d
32
d
87
d
111
d
114
d
108
d
100
d
33
d
</code>```

I'm sure this could be golfed quite a lot, but this is something I whipped up pretty quick. All it does is define some helpful functions and use them to display "Hello, World!"

Also, this DOES print "Hello, World!" with the characters separated by newlines, but I can't do anything about that, it's impossible in EEL.

Title: "Hello, World!"

Body:
EEL, 93 bytes

(Also known as Extensible Esoteric Language)

def(z|-1;x;z)
def(d|c;z)
72
d
101
d
108
c
d
111
d
44
d
32
d
87
d
111
d
114
d
108
d
100
d
33
d

I'm sure this could be golfed quite a lot, but this is something I whipped up pretty quick. All it does is define some helpful functions and use them to display "Hello, World!"

Also, this DOES print "Hello, World!" with the characters separated by newlines, but I can't do anything about that, it's impossible in EEL.


问:
Collide against walls

Statement

Given an input like this 35 15 0 0 10 that matches the following constrains:

Width in characters of the grid (5-50)

Height in characters of the grid (5-25)

Initial X position of the ball (0-(Width-1)

Initial Y position of the ball (0-(Height-1)

Number of movements to simulate

Generate a grid that shows the trajectory of the ball, knowing it's direction is initially DR (down-right) and that colliding with a wall will reverse the increment being applied to that axis. In other words, if we are going DR and hit the bottom we will now be going UR until we collide again.

The trajectory is not affected by passing twice over the same point since it's not the game snake, it's the trajectory of an object in 2d.

The input will be a string such as the one above and the output should be similar to this, not caring about which characters represent the wall, trajectory or ball, as long as they're consistent.

Points

Your score is the length of your submission, in characters.

Winners by language

var QUESTION_ID=81035,OVERRIDE_USER=19121;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

```

答:
Python 180 <s>172</s> <s>171</s> <s>163</s> 145 Bytes

(-2 Bytes with Python3)

```<code>def r(m,n,x,y,t):
 s=([' ']*m+['\n'])*n;a=b=1
 for c in'o'*(t-1)+'x':s[x+y*m+y],x,y=c,x+a,y+b;a*=2*(0<x<m-1)-1;b*=2*(0<y<n-1)-1
 print''.join(s)
</code>```

To save 2 more bytes with Python3 (thanks to shooqie) replace second line with

```<code> s=[*' '*m,'\n']*n
</code>```

Had to use a list of characters because python does not support string item assignement. The x+y*m+y part is from x+y*(m+1) because of the '\n' add each line end

Edit1: right after posting, saw how to get rid of the overwriting 'x'

Edit2: space after print

Edit3: using < and > instead ==, also tabs for 2nd indentation

Edit4: Replaced the if statements with assignements, daisy-chaining less-than and placing the loop in one line (thanks to RootTwo)

Title: Collide against walls

Body:
Python 180 <s>172</s> <s>171</s> <s>163</s> 145 Bytes

(-2 Bytes with Python3)

def r(m,n,x,y,t):
 s=([' ']*m+['\n'])*n;a=b=1
 for c in'o'*(t-1)+'x':s[x+y*m+y],x,y=c,x+a,y+b;a*=2*(0<x<m-1)-1;b*=2*(0<y<n-1)-1
 print''.join(s)

To save 2 more bytes with Python3 (thanks to shooqie) replace second line with

 s=[*' '*m,'\n']*n

Had to use a list of characters because python does not support string item assignement. The x+y*m+y part is from x+y*(m+1) because of the '\n' add each line end

Edit1: right after posting, saw how to get rid of the overwriting 'x'

Edit2: space after print

Edit3: using < and > instead ==, also tabs for 2nd indentation

Edit4: Replaced the if statements with assignements, daisy-chaining less-than and placing the loop in one line (thanks to RootTwo)


答:
Ruby, 33 bytes

This is a int arithmetic version that just happens to be the same as xnor's python answer. It is an anonymous function that takes and returns an int.

```<code>->n{n<10?n+9:(1+n%9)*10**(n/9)-1}
</code>```

Body:
"Digital sum" refers to the sum of all the digits in a number.

For example, the digital sum of 1324 is 10, because 1+3+2+4 = 10.

The challenge is to write a program/function to calculate the smallest number bigger than the input whose digital sum is the input.

Example with walkthrough

As an example, take the number 9 as the input:

```<code>9 = 1+8 -> 18
9 = 2+7 -> 27
9 = 3+6 -> 36
...
9 = 8+1 -> 81
9 = 9+0 -> 90
</code>```

The valid output would be the smallest number above, which is 18.

Specs

Note that 9 is not the valid output for this example, because the reversed number must be greater than the original number.

Note that the input will be positive.

Test-Cases:

```<code> 2 => 11      (2 = 1 + 1)
 8 => 17      (8 = 1 + 7)
12 => 39     (12 = 3 + 9)
16 => 79     (16 = 7 + 9)
18 => 99     (18 = 9 + 9)
24 => 699    (24 = 6 + 9 + 9)
32 => 5999   (32 = 5 + 9 + 9 + 9)
</code>```

References:

This is OEIS A161561.

Edit: Added an additional Testcase (18)

Thanks to Martin Ender for the Leaderboard Snippet

var QUESTION_ID=81047,OVERRIDE_USER=31373;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, 33 bytes

This is a int arithmetic version that just happens to be the same as xnor's python answer. It is an anonymous function that takes and returns an int.

->n{n<10?n+9:(1+n%9)*10**(n/9)-1}


答:
C 73 65 bytes

A macro with a helper function.

```<code>e(y){return y?10*e(y-1):1;}
#define F(n) n<9?n+9:(1+n%9)*e(n/9)-1
</code>```

The e function just calculates powers of ten, and the F macro uses the same solving method as this ruby, and this python answer. sadly, it is longer than about the same length as both those answers put together. But it is the first C answer.

(8 bytes saved by  Lynn's trick of removing int.)

Body:
C 73 65 bytes

A macro with a helper function.

e(y){return y?10*e(y-1):1;}
#define F(n) n<9?n+9:(1+n%9)*e(n/9)-1

The e function just calculates powers of ten, and the F macro uses the same solving method as this ruby, and this python answer. sadly, it is longer than about the same length as both those answers put together. But it is the first C answer.

(8 bytes saved by  Lynn's trick of removing int.)


问:
Debunking Stroustrup's debunking of the myth “C++ is for large, complicated, programs only”
Stroustrup has recently posted a series of posts debunking popular myths about C++. The fifth myth is: “C++ is for large, complicated, programs only”. To debunk it, he wrote a simple C++ program downloading a web page and extracting links from it. Here it is:

#include <string>
#include <set>
#include <iostream>
#include <sstream>
#include <regex>
#include <boost/asio.hpp>

using namespace std;

set<string> get_strings(istream& is, regex pat)
{
    set<string> res;
    smatch m;
    for (string s; getline(is, s);)  // read a line
        if (regex_search(s, m, pat))
            res.insert(m[0]);              // save match in set
    return res;
}

void connect_to_file(iostream& s, const string& server, const string& file)
// open a connection to server and open an attach file to s
// skip headers
{
    if (!s)
        throw runtime_error{ "can't connect\n" };

    // Request to read the file from the server:
    s << "GET " << "http://" + server + "/" + file << " HTTP/1.0\r\n";
    s << "Host: " << server << "\r\n";
    s << "Accept: */*\r\n";
    s << "Connection: close\r\n\r\n";

    // Check that the response is OK:
    string http_version;
    unsigned int status_code;
    s >> http_version >> status_code;

    string status_message;
    getline(s, status_message);
    if (!s || http_version.substr(0, 5) != "HTTP/")
        throw runtime_error{ "Invalid response\n" };

    if (status_code != 200)
        throw runtime_error{ "Response returned with status code" };

    // Discard the response headers, which are terminated by a blank line:
    string header;
    while (getline(s, header) && header != "\r")
        ;
}

int main()
{
    try {
        string server = "www.stroustrup.com";
        boost::asio::ip::tcp::iostream s{ server, "http" };  // make a connection
        connect_to_file(s, server, "C++.html");    // check and open file

        regex pat{ R"((http://)?www([./#\+-]\w*)+)" }; // URL
        for (auto x : get_strings(s, pat))    // look for URLs
            cout << x << '\n';
    }
    catch (std::exception& e) {
        std::cout << "Exception: " << e.what() << "\n";
        return 1;
    }
}
```
<p>Let's show Stroustrup what <strong>small and readable</strong> program actually is.</p>
<ol>
<li><p>Download <code>http://www.stroustrup.com/C++.html</code></p>
</li>
<li><p>List all links:</p>
``` http://www-h.eng.cam.ac.uk/help/tpl/languages/C++.html
 http://www.accu.org
 http://www.artima.co/cppsource
 http://www.boost.org
 ...
```

You can use any language, but no third-party libraries are allowed.

Winner

C++ answer won by votes, but it relies on a semi-third-party library (which is disallowed by rules), and, along with another close competitor Bash, relies on a hacked together HTTP client (it won't work with HTTPS, gzip, redirects etc.). So Wolfram is a clear winner. Another solution which comes close in terms of size and readability is PowerShell (with improvement from comments), but it hasn't received much attention. Mainstream languages (Python, C#) came pretty close too.

Comment on subjectivity

The most upvoted answer (C++) at the moment votes were counted was disqualified for not following the rules listed here in the question. There's nothing subjective about it. The second most upvoted question at that moment (Wolfram) was declared winner. The third answer's (Bash) "disqualification" is subjective, but it's irrelevant as the answer didn't win by votes at any point in time. You can consider it a comment if you like. Furthermore, right now the Wolfram answer is the most upvoted answer, the accepted one, and is declared winner, which means there's zero debate or subjectivity.

答:
Swift (2.2)

What? Please write the Swift version. That square bracket nonsense is hurting my eyes :)

Mister Smith on the Objective-C answer.

```<code>let x = try!NSString(contentsOfURL:NSURL(string:"http://www.stroustrup.com/C++.html")!,encoding:4)
for y in try!NSRegularExpression(pattern:"\"((http)s?://.*?)\"",options:[]).matchesInString(x as String,options:[],range:NSMakeRange(0,x.length)){print(x.substringWithRange(y.range))}
</code>```

Ungolfed:

```<code>let url = NSURL(string: "http://www.stroustrup.com/C++.html")!
let html = try! NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding)
let regex = try! NSRegularExpression(pattern: "\"((http)s?://.*?)\"", options: [])
let results = regex.matchesInString(html as String, options: [], range: NSMakeRange(0, html.length))
for result in results {
    print(html.substringWithRange(result.range))
}
</code>```

Assumes Foundation has been implicitly imported.

I can't access the original page for some reason, so this was tested with the Google Cached version: http://webcache.googleusercontent.com/search?q=cache:USk4BseSofcJ:www.stroustrup.com/C%2B%2B.html+&cd=1&hl=en&ct=clnk&gl=us

282 bytes.  Slightly shorter than the 292 byte Objective-C answer.  I'm falling back onto Foundation APIs, so there may be room for improvement by using pure Swift types.  The Cocoa APIs have also changed since the Objective-C answer was posted.

stringWithContentsOfURL: has been deprecated on NSString in favor of stringWithContentsOfURL:encoding:error:.  We lose some bytes on the encoding parameter, but gain some back because the ErrorPointer is no longer passed in with Swift.  The function now throws its NSError so instead, I'm using try! to force the execution of the NSString and NSRegularExpression initializers.  I also save some bytes by passing the raw value 4 as the value of the encoding parameter instead of the constant NSUTF8StringEncoding.  19 bytes saved.  But I lose some bytes by having to pass in an empty array ([]) instead of 0 to represent no options.  2 bytes lost there.  I also lose two bytes for every variable declaration since Swift requires whitespace characters on either side of the = character.

I lose 10 bytes by having to cast the NSString as a Swift String when calling matchesInString.  This is required because I'm using the NSString method contentsOfURL to get the web page HTML, but the NSRegularExpression method matchesInString takes in a Swift String as a parameter.  The implicit conversion between NSString and String isn't available here, so I am forced to use as to explicitly convert the types.

Interestingly enough matchesInString has not been completely converted to use Swift types.  It still requires its range parameter to be an NSRange struct instead of a Swift Range<String>.  I have to fall back and use NSMakeRange to create the range of the string.  I could save 4 bytes by using x.characters.indices of type Range<String.CharacterView.Index> instead, but Swift Range structs are not compatible with Foundation NSRange structs.  Additionally, if x were a Swift String, I might be able to save a few bytes by replacing substringWithRange with a subscript on String.  I haven't found a great way to do that yet, as creating two Index structs is currently longer than using substringWithRange.

Body:
Swift (2.2)

What? Please write the Swift version. That square bracket nonsense is hurting my eyes :)

Mister Smith on the Objective-C answer.

let x = try!NSString(contentsOfURL:NSURL(string:"http://www.stroustrup.com/C++.html")!,encoding:4)
for y in try!NSRegularExpression(pattern:"\"((http)s?://.*?)\"",options:[]).matchesInString(x as String,options:[],range:NSMakeRange(0,x.length)){print(x.substringWithRange(y.range))}

Ungolfed:

let url = NSURL(string: "http://www.stroustrup.com/C++.html")!
let html = try! NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding)
let regex = try! NSRegularExpression(pattern: "\"((http)s?://.*?)\"", options: [])
let results = regex.matchesInString(html as String, options: [], range: NSMakeRange(0, html.length))
for result in results {
    print(html.substringWithRange(result.range))
}

Assumes Foundation has been implicitly imported.

I can't access the original page for some reason, so this was tested with the Google Cached version: http://webcache.googleusercontent.com/search?q=cache:USk4BseSofcJ:www.stroustrup.com/C%2B%2B.html+&cd=1&hl=en&ct=clnk&gl=us

282 bytes.  Slightly shorter than the 292 byte Objective-C answer.  I'm falling back onto Foundation APIs, so there may be room for improvement by using pure Swift types.  The Cocoa APIs have also changed since the Objective-C answer was posted.

stringWithContentsOfURL: has been deprecated on NSString in favor of stringWithContentsOfURL:encoding:error:.  We lose some bytes on the encoding parameter, but gain some back because the ErrorPointer is no longer passed in with Swift.  The function now throws its NSError so instead, I'm using try! to force the execution of the NSString and NSRegularExpression initializers.  I also save some bytes by passing the raw value 4 as the value of the encoding parameter instead of the constant NSUTF8StringEncoding.  19 bytes saved.  But I lose some bytes by having to pass in an empty array ([]) instead of 0 to represent no options.  2 bytes lost there.  I also lose two bytes for every variable declaration since Swift requires whitespace characters on either side of the = character.

I lose 10 bytes by having to cast the NSString as a Swift String when calling matchesInString.  This is required because I'm using the NSString method contentsOfURL to get the web page HTML, but the NSRegularExpression method matchesInString takes in a Swift String as a parameter.  The implicit conversion between NSString and String isn't available here, so I am forced to use as to explicitly convert the types.

Interestingly enough matchesInString has not been completely converted to use Swift types.  It still requires its range parameter to be an NSRange struct instead of a Swift Range<String>.  I have to fall back and use NSMakeRange to create the range of the string.  I could save 4 bytes by using x.characters.indices of type Range<String.CharacterView.Index> instead, but Swift Range structs are not compatible with Foundation NSRange structs.  Additionally, if x were a Swift String, I might be able to save a few bytes by replacing substringWithRange with a subscript on String.  I haven't found a great way to do that yet, as creating two Index structs is currently longer than using substringWithRange.


问:
Fairly rank values

Task

Given an input list of integers x1…xn, compute a list of ranks r1…rn (a permutation of {1…n}) so that xr1 ≤ xr2 ≤ … ≤ xrn. Then, for each xi, replace its rank by the arithmetic mean of the ranks of all values in x that are equal to xi. (That is, whenever there is a tie between equal values in x, fairly redistribute the ranks among all of them.) Output the modified list of ranks r’1…r’n.

(For statistics geeks: such a ranking of observations is used in the Mann–Whitney U test (method two, step 1.))

Example

Given an input list [3, -6, 3, 3, 14, 3], the first list of ranks would be [2, 1, 3, 4, 6, 5], which would sort the list into [-6, 3, 3, 3, 3, 14]. Then, the ranks for all 3s in the input list are evened out into (2 + 3 + 4 + 5) ÷ 4 = 3.5. The final output is [3.5, 1, 3.5, 3.5, 6, 3.5].

Test cases

```<code>[4, 1, 4] -> [2.5, 1.0, 2.5]
[5, 14, 14, 14, 14, 5, 14] -> [1.5, 5.0, 5.0, 5.0, 5.0, 1.5, 5.0]
[9, 9, -5, -5, 13, -5, 13, 9, 9, 13] -> [5.5, 5.5, 2.0, 2.0, 9.0, 2.0, 9.0, 5.5, 5.5, 9.0]
[13, 16, 2, -5, -5, -5, 13, 16, -5, -5] -> [7.5, 9.5, 6.0, 3.0, 3.0, 3.0, 7.5, 9.5, 3.0, 3.0]
</code>```

Rules

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

答:
MATL, 14 bytes

```<code>7#utG&S&S2XQw)
</code>```

Try it online! Or verify all test cases (slightly modified version of the code; each result is on a different line).

```<code>      % Implicit input. Example: [5 14 14 14 14 5 14]
7#u   % Replace each value by a unique, integer label. Example: [1; 2; 2; 2; 2; 1; 2]
t     % Duplicate
G&S   % Push input again. Sort and get indices of the sorting. Example: [1 6 2 3 4 5 7]
&S    % Sort and get the indices, again. This gives the ranks. Example: [1 3 4 5 6 2 7]
2XQ   % Compute mean of ranks for equal values of the integer label. Example: [1.5; 5]
w     % Swap top two elements in stack
)     % Index the means with the integer labels. Example: [1.5; 5; 5; 5; 5; 1.5; 5]
      % Implicit display
</code>```

Title: Fairly rank values

Body:
MATL, 14 bytes

7#utG&S&S2XQw)

Try it online! Or verify all test cases (slightly modified version of the code; each result is on a different line).

      % Implicit input. Example: [5 14 14 14 14 5 14]
7#u   % Replace each value by a unique, integer label. Example: [1; 2; 2; 2; 2; 1; 2]
t     % Duplicate
G&S   % Push input again. Sort and get indices of the sorting. Example: [1 6 2 3 4 5 7]
&S    % Sort and get the indices, again. This gives the ranks. Example: [1 3 4 5 6 2 7]
2XQ   % Compute mean of ranks for equal values of the integer label. Example: [1.5; 5]
w     % Swap top two elements in stack
)     % Index the means with the integer labels. Example: [1.5; 5; 5; 5; 5; 1.5; 5]
      % Implicit display


答:
Pyth, 12

```<code>m+l<#dQ.OS/Q
</code>```

Test Suite

For each value this computes the arithmetic mean of [1..frequency] and adds the count of values less than the current one.

This works because for each value we would compute:

```<code>(1 / frequency) * sum (i = 1..frequency) i + count_less
</code>```

which we can simplify to:

```<code>(1 / frequency) * [ frequency * (frequency + 1) / 2 + count_less * frequency ]
</code>```

and again to:

```<code>(frequency + 1) / 2 + count_less
</code>```

However, in Pyth it was golfier to compute the first summand by using the mean builtin, rather than this other formula.

Title: Fairly rank values

Body:
Task

Given an input list of integers x1…xn, compute a list of ranks r1…rn (a permutation of {1…n}) so that xr1 ≤ xr2 ≤ … ≤ xrn. Then, for each xi, replace its rank by the arithmetic mean of the ranks of all values in x that are equal to xi. (That is, whenever there is a tie between equal values in x, fairly redistribute the ranks among all of them.) Output the modified list of ranks r’1…r’n.

(For statistics geeks: such a ranking of observations is used in the Mann–Whitney U test (method two, step 1.))

Example

Given an input list [3, -6, 3, 3, 14, 3], the first list of ranks would be [2, 1, 3, 4, 6, 5], which would sort the list into [-6, 3, 3, 3, 3, 14]. Then, the ranks for all 3s in the input list are evened out into (2 + 3 + 4 + 5) ÷ 4 = 3.5. The final output is [3.5, 1, 3.5, 3.5, 6, 3.5].

Test cases

```<code>[4, 1, 4] -> [2.5, 1.0, 2.5]
[5, 14, 14, 14, 14, 5, 14] -> [1.5, 5.0, 5.0, 5.0, 5.0, 1.5, 5.0]
[9, 9, -5, -5, 13, -5, 13, 9, 9, 13] -> [5.5, 5.5, 2.0, 2.0, 9.0, 2.0, 9.0, 5.5, 5.5, 9.0]
[13, 16, 2, -5, -5, -5, 13, 16, -5, -5] -> [7.5, 9.5, 6.0, 3.0, 3.0, 3.0, 7.5, 9.5, 3.0, 3.0]
</code>```

Rules

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

Body:
Pyth, 12

m+l<#dQ.OS/Q

Test Suite

For each value this computes the arithmetic mean of [1..frequency] and adds the count of values less than the current one.

This works because for each value we would compute:

(1 / frequency) * sum (i = 1..frequency) i + count_less

which we can simplify to:

(1 / frequency) * [ frequency * (frequency + 1) / 2 + count_less * frequency ]

and again to:

(frequency + 1) / 2 + count_less

However, in Pyth it was golfier to compute the first summand by using the mean builtin, rather than this other formula.


答:
CJam, 20 bytes

```<code>l':/60b9m<675/2bG0e[
</code>```

Test suite.

Explanation

Makes use of the fact that 65536 (216) over 86400 (the number of seconds in a day) simplifies to 512 over 675.

```<code>l     e# Read input.
':/   e# Split around ':', so we get ["hh" "mm" "ss"].
60b   e# Interpret as base-60 digits, which computes hh*60^2 + mm*60 + ss,
      e# i.e. it computes the total number of seconds. Note that this implicitly
      e# converts all three strings to integers.
9m<   e# Bitwise left-shift by 9 positions, which is the same as multiplying by
      e# 2^9 = 512.
675/  e# Divide by 675, flooring the result.
2b    e# Convert to binary.
G0e[  e# Left-pad with zeros to 16 digits.
</code>```

Title: What's the Binary Time?

Body:
What's the Binary Time?

Everybody knows what the normal time is. It's up there in the top-right (or wherever you put it) of your screen. But a question people rarely seem to ask themselves is this: What's the binary time?

Binary Time

Binary Time (True Binary Time) works by first reading the most significant bit (MSB) of the number. If that number is 0, the time expressed is before noon. If that number is 1, the time expressed is after noon. The next bit splits the half of the day the first bit expressed into two more equal halves, this time of 6 hours. The following bit splits into 3 hours, the next 90 minutes, and so on. Times like 12:00:00, where it seems it should be neither, become 1.

I can only understand this strange system of timing, so I need a program to convert to that for me. But as binary numbers are Base-2, and 2 is a small number, your program must be as short as possible.

Requirements

Your program should take a time (as 24-hour-time) as input and output the corresponding binary time number.

The output number should have 16-bit precision (the number should be 16 digits long).

You cannot use a builtin that does all of that conversion for you.

You should floor if it needs to be rounded.

Rules

Standard loopholes are forbidden.

Your program should not write anything to STDERR.

Test Cases

00:00:00 ==> 0000000000000000

12:00:00 ==> 1000000000000000

01:30:00 ==> 0001000000000000

10:33:06 ==> 0111000010001101

09:57:30 ==> 0110101000111000

06:00:00 ==> 0100000000000000

18:00:00 ==> 1100000000000000

Scoring

To win, as I mentioned earlier, you must have the least bytes.

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
CJam, 20 bytes

l':/60b9m<675/2bG0e[

Test suite.

Explanation

Makes use of the fact that 65536 (216) over 86400 (the number of seconds in a day) simplifies to 512 over 675.

l     e# Read input.
':/   e# Split around ':', so we get ["hh" "mm" "ss"].
60b   e# Interpret as base-60 digits, which computes hh*60^2 + mm*60 + ss,
      e# i.e. it computes the total number of seconds. Note that this implicitly
      e# converts all three strings to integers.
9m<   e# Bitwise left-shift by 9 positions, which is the same as multiplying by
      e# 2^9 = 512.
675/  e# Divide by 675, flooring the result.
2b    e# Convert to binary.
G0e[  e# Left-pad with zeros to 16 digits.


问:
Oneliner to merge lines with same first field
This is my first codegolf question, so I apologize in advance if it's not appropriate, and I welcome any feedback.

I have a file with this format:

```<code>a | rest of first line
b | rest of second line
b | rest of third line
c | rest of fourth line
d | rest of fifth line
d | rest of sixth line
</code>```

The actual contents vary, as does the delimiter. The contents are just text. The delimiter only appears once per line. For this puzzle, feel free to change the delimiter, e.g. use "%" as the delimiter.

Desired output:

```<code>a | rest of first line
b | rest of second line % rest of third line
c | rest of fourth line
d | rest of fifth line % rest of sixth line
</code>```

I already have both ruby and awk scripts to merge this, but I suspect it's possible to have a short oneliner. i.e. a one-liner that can be used along with pipes and other commands on the command line. I can't figure it out, and my own script is to long to just compress on the command line.

Shortest characters preferred. Input is not necessarily sorted, but we are only interested in merging consecutive lines with matching first fields. There are unlimited lines with matching first fields. Field 1 could be anything, e.g. names of fruits, proper names, etc.

(I run on MacOS, so I am personally most interested in implementations that run on the mac).

Here is a second example/test. Notice "|" is the delimiter. The space before the "|" is irrelevant, and if resent should be considered part of the key. I am using "%" as a delimited in the output, but again, feel free to change the delimiter (but don't used square brackets).

Input:

```<code>why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination
whom|[possessive] whose
whom|[subjective] who
whoever|[objective] whomever
whoever|[possessive] whosever
who|[possessive] whose
who|[objective] whom
</code>```

Desired output:

```<code>why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
whoever|[objective] whomever%[possessive] whosever
who|[possessive] whose%[objective] whom
</code>```

答:
Pyth - 15 bytes

Making a few assumptions about the problem, will change when OP clarifies.

```<code>jm+Khhd-sdK.ghk
</code>```

Try it online here.

Body:
Pyth - 15 bytes

Making a few assumptions about the problem, will change when OP clarifies.

jm+Khhd-sdK.ghk

Try it online here.


问:
Mean bits: an average challenge
Given an integer N >= 1, output the mean number of bits in an integer from 0 to N - 1

Specification

The output can be calculated as the sum of the number of bits in the binary representation of each integer from 0 to N-1, divided by N.

The binary representation of an integer has no leading zeroes in this context, with the exception of zero, which is represented as 0 in binary.

The output should be accurate to at least 7 significant figures.

Example

N = 6

```<code>0: 0   : 1 bit
1: 1   : 1 bit
2: 10  : 2 bits
3: 11  : 2 bits
4: 100 : 3 bits
5: 101 : 3 bits
</code>```

Mean number of bits = (1 + 1 + 2 + 2 + 3 + 3) / 6 = 2

Test cases

Input => output

```<code>1 => 1
2 => 1
3 => 1.3333333
4 => 1.5
5 => 1.8
6 => 2
7 => 2.1428571
</code>```

Leaderboard Snippet

(from here)

var QUESTION_ID=80586,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: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

```

Note that the sum (before dividing to find the mean) is a sequence on OEIS.

答:
C#, 87 bytes

```<code>double f(int n){return Enumerable.Range(0,n).Average(i=>Convert.ToString(i,2).Length);}
</code>```

I wrote a C# answer because I didn't see one. This is my first post to one of these, so please let me know if I'm doing anything wrong.

Title: Mean bits: an average challenge

Body:
C#, 87 bytes

double f(int n){return Enumerable.Range(0,n).Average(i=>Convert.ToString(i,2).Length);}

I wrote a C# answer because I didn't see one. This is my first post to one of these, so please let me know if I'm doing anything wrong.


答:
Jelly, <s>10</s> 8 bytes

```<code>ð_'Ṡ‘S‘H
</code>```

Saved 2 bytes by using the cmp trick from @xnor's answer.

Try it online! or verify all test cases.

How it works

```<code>ð_'Ṡ‘S‘H  Main link. Left argument: A (list of values)

ð         Make the chain dyadic, setting the right argument to A.
 _'       Spawned subtraction; compute the matrix of differences.
   Ṡ      Apply the sign function to each difference.
    ‘     Increment.
     S    Sum across columns.
      ‘   Increment.
       H  Halve.
</code>```

Title: Fairly rank values

Body:
Jelly, <s>10</s> 8 bytes

ð_'Ṡ‘S‘H

Saved 2 bytes by using the cmp trick from @xnor's answer.

Try it online! or verify all test cases.

How it works

ð_'Ṡ‘S‘H  Main link. Left argument: A (list of values)

ð         Make the chain dyadic, setting the right argument to A.
 _'       Spawned subtraction; compute the matrix of differences.
   Ṡ      Apply the sign function to each difference.
    ‘     Increment.
     S    Sum across columns.
      ‘   Increment.
       H  Halve.