答:
PostScript, 16 bytes

```<code>(Hello, World!)=
</code>```

Title: "Hello, World!"

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

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

The Rules

Each submission must be a full program.

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

The program must not write anything to STDERR.

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

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

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

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

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

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

For inspiration, check the Hello World Collection.

The Catalogue

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

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

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

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

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

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

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

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

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
PostScript, 16 bytes

(Hello, World!)=


问:
Is it a leap year?
This challenge is quite simple. You will take an input which will be a year from 1801 to 2400, and output if it is a leap year or not.

Your input will have no newlines or trailing spaces:

```<code>1954
</code>```

You will output in any way that you like that clearly tells the user if it is or isn't a leap year (I will accept y or n for yes/no)

You can get a list of leap years here: http://kalender-365.de/leap-years.php
I would note that leap years are not ever four years always. 1896 is a leap year, but 1900 is not. The years that follow this "skip" are:

```<code>1900
2100
2200
2300
</code>```

Test cases:

```<code>1936 ->  y
1805 ->  n
1900 ->  n
2272 ->  y
2400 ->  y
</code>```

EDIT: This is based on a standard Gregorian calendar: http://www.epochconverter.com/date-and-time/daynumbers-by-year.php

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 = 50798; // 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

```

ContentLicense: CC BY-SA 4.0

Title: Is it a leap year?

Body:
Python, 37 bytes

def c(s):return s%16*(s%25<1)<(s%4<1)

ContentLicense: CC BY-SA 3.0


问:
Inverting lists of lists of indices
Inspired by this StackOverflow post.

Introduction

Bob's job is to create spreadsheets and organize them.  The way he organizes them is known to very few except for Bob, but he creates a list of each of the spreadsheets that fall under the same group.  There's a bunch of data in the spreadsheet he creates, but there's only one piece of data that we're looking at right now: The number of days between the day he started this job and the day he made the spreadsheet.  The first day he created two spreadsheets, noted them both as 0 and sorted them in to their proper locations.

Now, his boss is asking for a review of what kinds of spreadsheet happened each day, and it's your job to write some code that will figure that out for Bob; he has far too many spreadsheets to do it by hand.

Input

Bob's info that he gives you comes in the form of a (0-or-1 indexed) jagged array where each datum is of the form x = a[i][j].  a is what I'm calling the jagged array itself, i is the type of spreadsheet, and x is the date the array was created.  j is unimportant.

The task

Given a jagged array of spreadsheet creation days organized by their type, return a jagged array of spreadsheet types organized by spreadsheet creation day.

Examples

Bob isn't going to just leave you with this abstract data. He's given me a subset of some of his spreadsheets to help you out with figuring out what everything is supposed to be.

Example input (0-indexed):

```<code>a = [
[3,2,5,0], # Bob doesn't necessarily sort his lists
[1,3],
[2,1,0,4],
[4,5,3],
[6,6]
]
</code>```

Example output (with commentary, which of course is not required):

```<code>output = [
[0,2] # On day 0, Bob made one type 0 and one type 2 spreadsheet
[1,2] # On day 1, Bob made one type 1 and one type 2 spreadsheet
[0,2] # On day 2, Bob made one type 0 and one type 2 spreadsheet
[0,1,3] # On day 3, Bob made one type 0, one type 1, and one type 3 spreadsheet
[2,3] # On day 4, Bob made one type 2 and one type 3 spreadsheet
[0,3] # On day 5, Bob made one type 0 and one type 3 spreadsheet
[4,4] # On day 6, Bob made two type 4 spreadsheets
]
</code>```

Note that Bob doesn't always make two spreadsheets every day, and so the output may be jagged as well. But he always makes at least one spreadsheet every day, so the output will never need to contain empty arrays - although if your output has empty arrays at the end, you don't need to remove them.

More test cases:

```<code>[[3,5,6,2],[0,0,0],[1,0,3,4]] -> [[1,1,1,2],[2],[0],[0,2],[2],[0],[0]]
[[-1]] -> Undefined behavior, as all input numbers will be non-negative integers.
[[0],[0],[],[0]] -> [[0,1,3]]
</code>```

The output's inner lists do not need to be sorted.

As always, no standard loopholes, and of course shortest code wins.

(As this is my first question, please let me know of anything I can do to improve it.)

答:
Python 2, 82 bytes

r=[];i=0
for t in input():
 for v in t:r+=[()]*-(~v+len(r));r[v]+=i,
 i+=1
print r
```

Test it on Ideone.

Title: Inverting lists of lists of indices

Body:
Python 2, 82 bytes

r=[];i=0
for t in input():
 for v in t:r+=[()]*-(~v+len(r));r[v]+=i,
 i+=1
print r

Test it on Ideone.


问:
Tips for golfing in Haskell
What general tips do you have for golfing in Haskell? I am looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Haskell. Please post only one tip per answer.

If you are new to golfing in Haskell, please have a look at the Guide to Golfing Rules in Haskell. There is also a dedicated Haskell chat room: Of Monads and Men.

答:
Don't waste the "otherwise" guard

A final guard that's a catch-all True (shorter as 1>0) can be used to bind a variable. Compare:

... |1>0=1/(x+y)
... |z<-x+y=1/z

... |1>0=sum l-sum m
... |s<-sum=s l-s m
```

Since the guard is mandatory and is otherwise wasted, little is needed to make this worth it. It's enough to save a pair of parens or bind a length-3 expression that's used twice. Sometimes you can negate guards to make the final case be the expression that best uses a binding.

Title: Tips for golfing in Haskell

Body:
Don't waste the "otherwise" guard

A final guard that's a catch-all True (shorter as 1>0) can be used to bind a variable. Compare:

... |1>0=1/(x+y)
... |z<-x+y=1/z

... |1>0=sum l-sum m
... |s<-sum=s l-s m

Since the guard is mandatory and is otherwise wasted, little is needed to make this worth it. It's enough to save a pair of parens or bind a length-3 expression that's used twice. Sometimes you can negate guards to make the final case be the expression that best uses a binding.


答:
Python, <s>50</s> 48 bytes

```<code>import calendar as y
def a(b):print(y.isleap(b))
</code>```

Title: Is it a leap year?

Body:
This challenge is quite simple. You will take an input which will be a year from 1801 to 2400, and output if it is a leap year or not.

Your input will have no newlines or trailing spaces:

```<code>1954
</code>```

You will output in any way that you like that clearly tells the user if it is or isn't a leap year (I will accept y or n for yes/no)

You can get a list of leap years here: http://kalender-365.de/leap-years.php
I would note that leap years are not ever four years always. 1896 is a leap year, but 1900 is not. The years that follow this "skip" are:

```<code>1900
2100
2200
2300
</code>```

Test cases:

```<code>1936 ->  y
1805 ->  n
1900 ->  n
2272 ->  y
2400 ->  y
</code>```

EDIT: This is based on a standard Gregorian calendar: http://www.epochconverter.com/date-and-time/daynumbers-by-year.php

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
Python, <s>50</s> 48 bytes

import calendar as y
def a(b):print(y.isleap(b))


问:
Polar Bear, Polar Bear, what do you hear?
The text of the children's book Polar Bear, Polar Bear, What Do You Hear?  has a very simple pattern.  You might use the text to teach introductory programming concepts.

My son was quickly bored by this idea, so I decided to play some golf with it instead.

The Challenge

In your programming language of choice, write the smallest program possible which will print the following text.  Output should match exactly, including case, spacing, and punctuation.

```<code>Polar Bear, Polar Bear, what do you hear?
I hear a lion roaring in my ear.

Lion, Lion, what do you hear?
I hear a hippopotamus snorting in my ear.

Hippopotamus, Hippopotamus, what do you hear?
I hear a flamingo fluting in my ear.

Flamingo, Flamingo, what do you hear?
I hear a zebra braying in my ear.

Zebra, Zebra, what do you hear?
I hear a boa constrictor hissing in my ear.

Boa Constrictor, Boa Constrictor, what do you hear?
I hear an elephant trumpeting in my ear.

Elephant, Elephant, what do you hear?
I hear a leopard snarling in my ear.

Leopard, Leopard, what do you hear?
I hear a peacock yelping in my ear.

Peacock, Peacock, what do you hear?
I hear a walrus bellowing in my ear.

Walrus, Walrus, what do you hear?
I hear a zookeeper whistling in my ear.

Zookeeper, Zookeeper, what do you hear?
I hear children...

...growling like a polar bear,
roaring like a lion,
snorting like a hippopotamus,
fluting like a flamingo,
braying like a zebra,
hissing like a boa constrictor,
trumpeting like an elephant,
snarling like a leopard,
yelping like a peacock,
bellowing like a walrus...
that's what I hear.
</code>```

答:
Python 3, <s>442</s> 441 bytes

```<code>h=t=''
for n,s in zip('polar bear,lion,hippopotamus,flamingo,zebra,boa constrictor,elephant,leopard,peacock,walrus,zookeeper'.split(','),'...growl roar snort flut bray hiss trumpet snarl yelp bellow whistl'.split()):u='n'[:'el'in n],n,s,n.title();h+="I hear a{0} {1} {2}ing in my ear.\n\n{3}, {3} what do you hear?\n".format(*u);t+="{2}ing like a{0} {1},\n".format(*u)
print((h+'I hear children...\n\n'+t)[44:-30]+"...\nthat's what I hear.")
</code>```

ungolfed:

```<code>animals = 'polar bear,lion,hippopotamus,flamingo,zebra,boa constrictor,elephant,leopard,peacock,walrus,zookeeper'.split(',')

sounds = '...growl roar snort flut bray hiss trumpet snarl yelp bellow whistl'.split()

h=t=''
for n,s in zip(animals,sounds):
    u='n'[:'el'in n], n, s, n.title()

    h+="I hear a{0} {1} {2}ing in my ear.\n\n{3}, {3} what do you hear?\n".format(*u)

    t+="{2}ing like a{0} {1},\n".format(*u)

print((h+'I hear children...\n\n'+t)[44:-30]+"...\nthat's what I hear.")
</code>```

Basically, just a loop that builds up two strings representing the two parts of the story.  The 'n'[:'el'in n] handles the "an" for elephant.  The [44:-30] chops off the leading "I hear a polar bear growling in my ear" and the trailing "whistling like a zookeeper".

Body:
Python 3, <s>442</s> 441 bytes

h=t=''
for n,s in zip('polar bear,lion,hippopotamus,flamingo,zebra,boa constrictor,elephant,leopard,peacock,walrus,zookeeper'.split(','),'...growl roar snort flut bray hiss trumpet snarl yelp bellow whistl'.split()):u='n'[:'el'in n],n,s,n.title();h+="I hear a{0} {1} {2}ing in my ear.\n\n{3}, {3} what do you hear?\n".format(*u);t+="{2}ing like a{0} {1},\n".format(*u)
print((h+'I hear children...\n\n'+t)[44:-30]+"...\nthat's what I hear.")

ungolfed:

animals = 'polar bear,lion,hippopotamus,flamingo,zebra,boa constrictor,elephant,leopard,peacock,walrus,zookeeper'.split(',')

sounds = '...growl roar snort flut bray hiss trumpet snarl yelp bellow whistl'.split()

h=t=''
for n,s in zip(animals,sounds):
    u='n'[:'el'in n], n, s, n.title()

    h+="I hear a{0} {1} {2}ing in my ear.\n\n{3}, {3} what do you hear?\n".format(*u)

    t+="{2}ing like a{0} {1},\n".format(*u)

print((h+'I hear children...\n\n'+t)[44:-30]+"...\nthat's what I hear.")

Basically, just a loop that builds up two strings representing the two parts of the story.  The 'n'[:'el'in n] handles the "an" for elephant.  The [44:-30] chops off the leading "I hear a polar bear growling in my ear" and the trailing "whistling like a zookeeper".


答:
Lua, 114 bytes

r={}for i,t in ipairs(...)do for _,v in ipairs(t)do if r[v] then r[v][#r[v]+1]=i else r[v]={i}end end end return r
```

Ideone it!

Inspired by Dennis' answer in Python 2.

Title: Inverting lists of lists of indices

Body:
Inspired by this StackOverflow post.

Introduction

Bob's job is to create spreadsheets and organize them.  The way he organizes them is known to very few except for Bob, but he creates a list of each of the spreadsheets that fall under the same group.  There's a bunch of data in the spreadsheet he creates, but there's only one piece of data that we're looking at right now: The number of days between the day he started this job and the day he made the spreadsheet.  The first day he created two spreadsheets, noted them both as 0 and sorted them in to their proper locations.

Now, his boss is asking for a review of what kinds of spreadsheet happened each day, and it's your job to write some code that will figure that out for Bob; he has far too many spreadsheets to do it by hand.

Input

Bob's info that he gives you comes in the form of a (0-or-1 indexed) jagged array where each datum is of the form x = a[i][j].  a is what I'm calling the jagged array itself, i is the type of spreadsheet, and x is the date the array was created.  j is unimportant.

The task

Given a jagged array of spreadsheet creation days organized by their type, return a jagged array of spreadsheet types organized by spreadsheet creation day.

Examples

Bob isn't going to just leave you with this abstract data. He's given me a subset of some of his spreadsheets to help you out with figuring out what everything is supposed to be.

Example input (0-indexed):

```<code>a = [
[3,2,5,0], # Bob doesn't necessarily sort his lists
[1,3],
[2,1,0,4],
[4,5,3],
[6,6]
]
</code>```

Example output (with commentary, which of course is not required):

```<code>output = [
[0,2] # On day 0, Bob made one type 0 and one type 2 spreadsheet
[1,2] # On day 1, Bob made one type 1 and one type 2 spreadsheet
[0,2] # On day 2, Bob made one type 0 and one type 2 spreadsheet
[0,1,3] # On day 3, Bob made one type 0, one type 1, and one type 3 spreadsheet
[2,3] # On day 4, Bob made one type 2 and one type 3 spreadsheet
[0,3] # On day 5, Bob made one type 0 and one type 3 spreadsheet
[4,4] # On day 6, Bob made two type 4 spreadsheets
]
</code>```

Note that Bob doesn't always make two spreadsheets every day, and so the output may be jagged as well. But he always makes at least one spreadsheet every day, so the output will never need to contain empty arrays - although if your output has empty arrays at the end, you don't need to remove them.

More test cases:

```<code>[[3,5,6,2],[0,0,0],[1,0,3,4]] -> [[1,1,1,2],[2],[0],[0,2],[2],[0],[0]]
[[-1]] -> Undefined behavior, as all input numbers will be non-negative integers.
[[0],[0],[],[0]] -> [[0,1,3]]
</code>```

The output's inner lists do not need to be sorted.

As always, no standard loopholes, and of course shortest code wins.

(As this is my first question, please let me know of anything I can do to improve it.)

Body:
Lua, 114 bytes

r={}for i,t in ipairs(...)do for _,v in ipairs(t)do if r[v] then r[v][#r[v]+1]=i else r[v]={i}end end end return r

Ideone it!

Inspired by Dennis' answer in Python 2.


答:
Brachylog, 28 bytes

```<code>:1f.
cdo:Im:?:2f.
t:.m:Im~h?
</code>```

Explanation

Main predicate, Input (?) = a list of lists

```<code>:1f.              Find all valid outputs of predicate 1 with ? as input
</code>```

Predicate 1:

```<code>c                 Concatenate the list of lists into a single list
 do               Remove duplicates and sort
   :Im            Take the Ith element of that sorted list
      :?:2f.      Find all valid outputs of predicate 2 with [Element:?] as input
</code>```

Predicate 2:

```<code>t:.m              Take the (Output)th element of the list of lists
    :Im           Take the Ith element of that list
       ~h?        This element is the element of the input [Element:List of lists]
</code>```

Title: Inverting lists of lists of indices

Body:
Brachylog, 28 bytes

:1f.
cdo:Im:?:2f.
t:.m:Im~h?

Explanation

Main predicate, Input (?) = a list of lists

:1f.              Find all valid outputs of predicate 1 with ? as input

Predicate 1:

c                 Concatenate the list of lists into a single list
 do               Remove duplicates and sort
   :Im            Take the Ith element of that sorted list
      :?:2f.      Find all valid outputs of predicate 2 with [Element:?] as input

Predicate 2:

t:.m              Take the (Output)th element of the list of lists
    :Im           Take the Ith element of that list
       ~h?        This element is the element of the input [Element:List of lists]


答:
Mathematica, 35 bytes

```<code>Table[#&@@@#~Position~i,{i,Max@#}]&
</code>```

An unnamed function which accepts and returns a ragged list. Uses 1-based indices.

Thankfully Max automatically flattens all its inputs, so this gets us the last day index even though the input is a ragged list. We then simply compute a list of #&@@@#~Position~i for all day indices i. This expression itself finds the position of i inside the ragged list (return as an array of indices at successive depths), so the values we want are the first values of each of those lists. #&@@@ is a standard golfing trick to retrieve the first element from every sublist, by applying #& to each of those sublists, which is an unnamed function that returns its first argument.

Alternatively, we can define a unary operator for the same byte-count (assuming an ISO 8859-1 encoded source file):

```<code>±n_:=#&@@@n~Position~#&~Array~Max@n
</code>```

Title: Inverting lists of lists of indices

Body:
Mathematica, 35 bytes

Table[#&@@@#~Position~i,{i,Max@#}]&

An unnamed function which accepts and returns a ragged list. Uses 1-based indices.

Thankfully Max automatically flattens all its inputs, so this gets us the last day index even though the input is a ragged list. We then simply compute a list of #&@@@#~Position~i for all day indices i. This expression itself finds the position of i inside the ragged list (return as an array of indices at successive depths), so the values we want are the first values of each of those lists. #&@@@ is a standard golfing trick to retrieve the first element from every sublist, by applying #& to each of those sublists, which is an unnamed function that returns its first argument.

Alternatively, we can define a unary operator for the same byte-count (assuming an ISO 8859-1 encoded source file):

±n_:=#&@@@n~Position~#&~Array~Max@n


问:
Dijkstra's Challenge

Presented in honor of APL as an interactive tool turning 50 this year

Background

Ken [Iverson] presented his paper Formalism in Programming Languages in August 1963 at a Working Conference on Mechanical Language Structures, Princeton, N.J. The list of conferees is full of famous and soon-to-be famous names, and a few future Turing Award winners (Backus, Curry, Dijkstra, Floyd, Iverson, Newell, Perlis, Wilkes). The paper also records the discussion that occurred after the presentation, ending with an exchange between Ken and [Edsger] Dijkstra, in which Ken’s reply to Dijkstra’s question was a one-liner.

Challenge

How would you represent a more complex operation, for example, the sum of all elements of a matrix M which are equal to the sum of the corresponding row and column indices?

Write a snippet or expression (no need for a full program or function) to calculate the sum of each element in a given integer matrix which is equal to the sum of its indices. Or, as FryAmTheEggman puts it: given a matrix M with elements aij return the sum of each aij where aij = i + j.

You may assume the matrix already being in a variable or memory location, or you may take it as an argument or input. You may use either 0 or 1 based indices.

Test cases

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

0 for empty matrix

```<code>2
</code>```

0 for 0 based indices or 2 for 1-based

```<code>1 5 2
9 4 2
5 9 6
</code>```

2 for 0 based or 10 for 1 based

```<code> 0 3  0  4
 0 4  1  4
 4 3  1  2
-2 4 -2 -1
</code>```

11

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

6 for 0 based or 3 for 1 based

Anecdote

Iverson's answer was ++/(M = ⍳¹ ⨢ ⍳¹)//M, which is neither valid in the Iverson Notation as defined in A Programming Language, nor in what eventually became APL. In Iverson notation, it would have been +/(M = ⍳¹(μ(M)) ⨢ ⍳¹(ν(M)))/M. In the very first versions of APL it was +/(,M=(⍳1↑⍴M)∘.+⍳1↓⍴M)/,M.

Title: Dijkstra's Challenge

Body:
R, 24 bytes

sum(M[M==row(M)+col(M)])

1-based.

Test cases:

> M<-matrix(nrow=0,ncol=0)
> M
<0 x 0 matrix>
> sum(M[M==row(M)+col(M)])
[1] 0
> M<-matrix(2,nrow=1,ncol=1)
> M
     [,1]
[1,]    2
> sum(M[M==row(M)+col(M)])
[1] 2
> M<-matrix(c(1,9,5,5,4,9,2,2,6),nrow=3)
> M
     [,1] [,2] [,3]
[1,]    1    5    2
[2,]    9    4    2
[3,]    5    9    6
> sum(M[M==row(M)+col(M)])
[1] 10
> M<-matrix(c(0,0,4,-2,3,4,3,4,0,1,1,-2,4,4,2,-1),nrow=4)
> M
     [,1] [,2] [,3] [,4]
[1,]    0    3    0    4
[2,]    0    4    1    4
[3,]    4    3    1    2
[4,]   -2    4   -2   -1
> sum(M[M==row(M)+col(M)])
[1] 11
> M<-matrix(c(3,3,-1,-1,3,3,3,1),nrow=2)
> M
     [,1] [,2] [,3] [,4]
[1,]    3   -1    3    3
[2,]    3   -1    3    1
> sum(M[M==row(M)+col(M)])
[1] 3


问:
Return each number from a group of numbers

The challenge

The program must return all numbers included into a group (comma and hyphen separated sequence) of numbers.

Rules

s is the sequence string;

all numbers included in s are positive;

numbers will always increase;

numbers will never repeat

when you answer, show the output for s="1,3-5,9,16,18-23"

Examples

```<code>input(s)    outputs
-----------------
1           1
1,2         1,2
1-4         1,2,3,4
1-4,6       1,2,3,4,6
1-4,8-11    1,2,3,4,8,9,10,11
</code>```

Good luck. =)

答:
Perl 25 26 25

$_ is the sequence string

```<code>s/-/../g;$_=join",",eval
</code>```

Sample session:

```<code>[~/] $ perl -M5.010 -pe 's/-/../g;$_=join",",eval' <<< "1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23
</code>```

Added 1 character to the character count for the -n-p option (thanks Gareth, ..kinda).

Body:
Perl 25 26 25

$_ is the sequence string

s/-/../g;$_=join",",eval

Sample session:

[~/] $ perl -M5.010 -pe 's/-/../g;$_=join",",eval' <<< "1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23

Added 1 character to the character count for the -n-p option (thanks Gareth, ..kinda).


答:
Pyth, 13 bytes

```<code>eMM.ghkSs,RVU

         ,RV      vectorized right map of pair, over:
            UQ      [0, …, len(input) - 1] and
              Q     input
                  (this replaces each date with a [date, type] pair)
        s         concatenate
       S          sort
   .ghk           group by first element (date)
eMM               last element (type) of each sublist
</code>```

Try it online

Title: Inverting lists of lists of indices

Body:
Pyth, 13 bytes

eMM.ghkSs,RVU

         ,RV      vectorized right map of pair, over:
            UQ      [0, …, len(input) - 1] and
              Q     input
                  (this replaces each date with a [date, type] pair)
        s         concatenate
       S          sort
   .ghk           group by first element (date)
eMM               last element (type) of each sublist

Try it online


问:
Calculate the Super-Logarithm
This should be a simple challenge.

Given a number \$n \ge 0\$, output the super-logarithm (or the \$\log^*\$, log-star, or iterated logarithm, which are equivalent since \$n\$ is never negative for this challenge.) of \$n\$.

$$\log^*(n) = \begin{cases}
0  & \text{ if } n \le 1 \\
1 + \log^*(\log(n)) & \text{ if } n > 1
\end{cases}$$

This is one of the two inverse functions to tetration. The other is the super-root, which is in a related question.

Examples

```<code>Input       Output
0           0
1           0
2           1
3           2
4           2
...
15          2
16          3
...
3814279     3
3814280     4
</code>```

Rules

You do not need to support decimals, though you may.

You need to support input of at least \$3814280 =  \left\lceil e^{e^e} \right\rceil\$.

You may not hard-code the values like 3814280. (Your program must theoretically support higher numbers.) I want an algorithm to be implemented.

Shortest code wins.

Related OEIS

答:
CJam (16 bytes)

```<code>rd{_1>}{_ml}w],(
</code>```

Online demo

Simple while loop with pre-condition. (What I really want here is a Golfscript-style unfold operation, but CJam doesn't have one, and floating point in GolfScript is messy and not at all golfy).

Title: Calculate the Super-Logarithm

Body:
CJam (16 bytes)

rd{_1>}{_ml}w],(

Online demo

Simple while loop with pre-condition. (What I really want here is a Golfscript-style unfold operation, but CJam doesn't have one, and floating point in GolfScript is messy and not at all golfy).


问:
A simple TCP server
Write a program or function that listens for incoming TCP traffic on port N. It offers a simple service: it calculates sum of IP address fields of incoming connection and returns.

Program or function reads integer N from arguments or stdin. It listens to incoming TCP connections on port N. When someone connects to that port, the program calculates sum of its IP address fields and sends it back to the client with trailing newline and closes connection.

Port number N is a valid port, and 210 < N < 215

Trailing newline can be either \nor \r\n

You can use either IPv4 or IPv6. Since IPv6 addresses are written in hexadecimal form, you must also provide result in same format, for example 2001:0db8:0000:0042:0000:8a2e:0370:7334 => 12ecd.

This is code-golf. Standard rules and loopholes apply.

Example

You run your server with ./server 1234. The server is now running and waiting for connections on port 1234. Then a client from 127.0.0.1 connects to your server. Your server performs a simple calculation: 127+0+0+1 => 128 and sends the result to the client (with trailing newline): 128\n. Then server closes connection and waits for next client.

Leaderboard

var QUESTION_ID=76379,OVERRIDE_USER=20569;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

```

答:
Object Pascal, <s>342</s> 340 bytes

A small (well the pascal definition of small...) server with the lowest level Sockets library. Listenes to IP4, port no. on the commandline.

```<code>uses sockets;var s,c,l,i,f:integer;a,b:TInetSockAddr;g:string;begin val(ParamStr(1),f,i);s:=fpSocket(2,1,0);a.sin_family:=2;a.sin_port:=ntobe(f);l:=sizeof(a);fpBind(s,@a,l);repeat fpListen(s,1);c:=fpaccept(s,@b,@l);f:=0;for i:=1to 4do f:=f+b.sin_addr.s_bytes[i];Str(f,g);g:=g+#10;fpsend(c,@g[1],length(g),0);fpshutdown(c,2);until False;end.
</code>```

Ungolfed:

```<code>uses
  sockets;
var
  s, c, l, i, f: integer;
  a, b: TInetSockAddr;        { a=server, b=client }
  g: string;
begin
  val(ParamStr(1), f, i);     { store port no. in f }
  s := fpSocket(2, 1, 0);     { 2=AF_INET, 1=SOCK_STREAM, 0=PF_UNSPEC }
  a.sin_family := 2;          { 2=AF_INET }
  a.sin_port := ntobe(f);     { port to listen to, address initialized to localhost by default }
  l := sizeof(a);
  fpBind(s, @a, l);           { bind socket to address:port }
  repeat
    fpListen(s ,1);           { listen for one incoming connection }
    c := fpaccept(s, @b, @l); { accept connection, client address in b }
    f := 0;
    for i:=1 to 4 do
      f := f+b.sin_addr.s_bytes[i]; { add 4 bytes of client address }
    Str(f, g);                      { store f in a string }
    g := g+#10;                     { add newline }
    fpsend(c, @g[1], length(g), 0); { send the addition result }
    fpshutdown(c, 2);               { close the connection }
  until False;
end.
</code>```

Title: A simple TCP server

Body:
Object Pascal, <s>342</s> 340 bytes

A small (well the pascal definition of small...) server with the lowest level Sockets library. Listenes to IP4, port no. on the commandline.

uses sockets;var s,c,l,i,f:integer;a,b:TInetSockAddr;g:string;begin val(ParamStr(1),f,i);s:=fpSocket(2,1,0);a.sin_family:=2;a.sin_port:=ntobe(f);l:=sizeof(a);fpBind(s,@a,l);repeat fpListen(s,1);c:=fpaccept(s,@b,@l);f:=0;for i:=1to 4do f:=f+b.sin_addr.s_bytes[i];Str(f,g);g:=g+#10;fpsend(c,@g[1],length(g),0);fpshutdown(c,2);until False;end.

Ungolfed:

uses
  sockets;
var
  s, c, l, i, f: integer;
  a, b: TInetSockAddr;        { a=server, b=client }
  g: string;
begin
  val(ParamStr(1), f, i);     { store port no. in f }
  s := fpSocket(2, 1, 0);     { 2=AF_INET, 1=SOCK_STREAM, 0=PF_UNSPEC }
  a.sin_family := 2;          { 2=AF_INET }
  a.sin_port := ntobe(f);     { port to listen to, address initialized to localhost by default }
  l := sizeof(a);
  fpBind(s, @a, l);           { bind socket to address:port }
  repeat
    fpListen(s ,1);           { listen for one incoming connection }
    c := fpaccept(s, @b, @l); { accept connection, client address in b }
    f := 0;
    for i:=1 to 4 do
      f := f+b.sin_addr.s_bytes[i]; { add 4 bytes of client address }
    Str(f, g);                      { store f in a string }
    g := g+#10;                     { add newline }
    fpsend(c, @g[1], length(g), 0); { send the addition result }
    fpshutdown(c, 2);               { close the connection }
  until False;
end.


问:
Print all alphanumeric characters plus underscore
Write a program or function that prints or returns a string of the alphanumeric characters plus underscore, in any order. To be precise, the following characters need to be output, and no more:

```<code>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_
</code>```

When printing to stdout, an optional trailing newline after your output is permitted.

Built-in constants that contain 9 or more of the above characters are disallowed.

Shortest code in bytes wins.

This is a very simple challenge, which I believe will generate some interesting answers nevertheless.

Leaderboards

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

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

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

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

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

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

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

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

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

var QUESTION_ID=85666,OVERRIDE_USER=4162;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;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

```

答:
Groovy, 36 characters

print(("0".."z").grep(~/\w/).join())
```

<p>Sample run:</p>

```bash-4.3$ groovy -e 'print(("0".."z").grep(~/\w/).join())'
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz
```

Body:
Groovy, 36 characters

print(("0".."z").grep(~/\w/).join())

Sample run:

bash-4.3$ groovy -e 'print(("0".."z").grep(~/\w/).join())'
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz


Title: Inverting lists of lists of indices

Body:
JavaScript (ES6), 58 bytes

a=>a.map((b,i)=>b.map(j=>(r[j]=r[j]||[]).push(i)),r=[])&&r


答:
CJam (30 29 bytes)

```<code>Mq~{W):W;{:X)Me]_X=W+X\t}/}/`
</code>```

Online demo

Curiously it's shorter to hack around with W than to use ee, mainly because I want the index to end up in a variable anyway. e] saved two bytes over first finding the maximum element m and initialising an array of m+1 empty arrays.

Thanks to Martin for a one-byte saving by storing a value in X instead of juggling it around the stack.

NB If trailing empty arrays are permitted, there's alternative 29-byte approach by instead initialising the array of as many empty days as there are spreadsheets:

```<code>q~_e_,Ma*\{W):W;{_2$=W+t}/}/`
</code>```

Title: Inverting lists of lists of indices

Body:
CJam (30 29 bytes)

Mq~{W):W;{:X)Me]_X=W+X\t}/}/`

Online demo

Curiously it's shorter to hack around with W than to use ee, mainly because I want the index to end up in a variable anyway. e] saved two bytes over first finding the maximum element m and initialising an array of m+1 empty arrays.

Thanks to Martin for a one-byte saving by storing a value in X instead of juggling it around the stack.

NB If trailing empty arrays are permitted, there's alternative 29-byte approach by instead initialising the array of as many empty days as there are spreadsheets:

q~_e_,Ma*\{W):W;{_2$=W+t}/}/`


Title: Calculate the Super-Logarithm

Body:
This should be a simple challenge.

Given a number \$n \ge 0\$, output the super-logarithm (or the \$\log^*\$, log-star, or iterated logarithm, which are equivalent since \$n\$ is never negative for this challenge.) of \$n\$.

$$\log^*(n) = \begin{cases}
0  & \text{ if } n \le 1 \\
1 + \log^*(\log(n)) & \text{ if } n > 1
\end{cases}$$

This is one of the two inverse functions to tetration. The other is the super-root, which is in a related question.

Examples

```<code>Input       Output
0           0
1           0
2           1
3           2
4           2
...
15          2
16          3
...
3814279     3
3814280     4
</code>```

Rules

You do not need to support decimals, though you may.

You need to support input of at least \$3814280 =  \left\lceil e^{e^e} \right\rceil\$.

You may not hard-code the values like 3814280. (Your program must theoretically support higher numbers.) I want an algorithm to be implemented.

Shortest code wins.

Related OEIS

Body:
R, <s>38</s> 37 bytes

f=function(x)if(x>1)1+f(log(x))else 0

Thanks @user5957401 for the extra byte!

Test cases:

> f(0)
[1] 0
> f(1)
[1] 0
> f(2)
[1] 1
> f(3)
[1] 2
> f(4)
[1] 2
> f(3814279)
[1] 3
> f(3814280)
[1] 4


答:
Java, 314 bytes

int[][]f(int[][]n){int w=0;Map<Integer,List<Integer>>m=new TreeMap<>();for(int i=0;i<n.length;i++)for(Integer x:n[i]){if(m.get(x)==null)m.put(x,new ArrayList<>());m.get(x).add(i);w=x>w?x:w;}int[][]z=new int[w+1][];for(int i=0,j;i<w+1;i++){z[i]=new int[m.get(i).size()];j=0;for(int x:m.get(i))z[i][j++]=x;}return z;
```

<p><strong>Detailed</strong></p>

<pre class="lang-java prettyprint-override"><code>public static Integer[][] f(Integer[][]n)
{
    int w=0;
    Map<Integer,List<Integer>>m=new TreeMap<>();

    for(int i=0;i<n.length;i++)
    {
        for(Integer x : n[i])
        {
            if(m.get(x)==null) m.put(x,new ArrayList<Integer>());
            m.get(x).add(i);
            w=x>w?x:w;
        }
    }

    Integer[][]z=new Integer[w+1][];
    for(int i=0,j; i<w+1; i++)
    {
        z[i]=new Integer[m.get(i).size()];
        j=0;for(Integer x : m.get(i))z[i][j++]=x;
    }

    return z;
}
</code>```

Title: Inverting lists of lists of indices

Body:
Java, 314 bytes

int[][]f(int[][]n){int w=0;Map<Integer,List<Integer>>m=new TreeMap<>();for(int i=0;i<n.length;i++)for(Integer x:n[i]){if(m.get(x)==null)m.put(x,new ArrayList<>());m.get(x).add(i);w=x>w?x:w;}int[][]z=new int[w+1][];for(int i=0,j;i<w+1;i++){z[i]=new int[m.get(i).size()];j=0;for(int x:m.get(i))z[i][j++]=x;}return z;

Detailed

public static Integer[][] f(Integer[][]n)
{
    int w=0;
    Map<Integer,List<Integer>>m=new TreeMap<>();

    for(int i=0;i<n.length;i++)
    {
        for(Integer x : n[i])
        {
            if(m.get(x)==null) m.put(x,new ArrayList<Integer>());
            m.get(x).add(i);
            w=x>w?x:w;
        }
    }

    Integer[][]z=new Integer[w+1][];
    for(int i=0,j; i<w+1; i++)
    {
        z[i]=new Integer[m.get(i).size()];
        j=0;for(Integer x : m.get(i))z[i][j++]=x;
    }

    return z;
}


问:
What exactly was your question?

Introduction

When you are given a boring text, you just want to get it over with as quick as possible. Let's observe the following text:

```<code>Ens colligi timenda etc priorem judicem. De quascunque ii at contingere
repugnaret explicetur intellectu. Adjuvetis hoc fortassis suspicari opportune
obversari vix eam? Dei praemia prudens hominum iii constet requiri haberem. Ima
sane nemo modi fuit lus pro dem haud. Vestro age negare tactum hoc cui lor. Ne et
ut quod id soli soni deus. At constare innumera is occurret ea. Nia calebat seu
acquiro fraudem effingo dicimus.
</code>```

Note: This text has newlines for readability, while the test cases you need to handle don't have newline characters.

One way to skim text is to find questions that the writer has put into the text. For example, there is 1 question in the text above. Namely:

```<code>Adjuvetis hoc fortassis suspicari opportune obversari vix eam?
</code>```

This can be done by splitting the text into sentences. A sentence will always end with one of the following punctuation symbols: .?! (others don't have to be handled). Other symbols than these are part of the sentence.

The Task

Given a line of text consisting of only

letters (A-Za-z)

numbers (0-9)

spaces

punctuation (,.;:?!) (a sentence cannot start with one of these).

Output the questions that are in the text in any reasonable format. You may assume that the text will always have at least 1 question. Outputting trailing and leading spaces before and after a question is allowed.

Important: Next to a punctuation symbol, there will never be another punctuation symbol (e.g. ?? is invalid and will not be required to handle).

Test cases

In the format:

```<code>Input
Output(s)
</code>```

The test cases:

```<code>Huh? I haven't heard what you just said. Could you repeat that please?
Huh?
Could you repeat that please?

plz can i haz cheesburgr? i am cat pls.
plz can i haz cheesburgr?

This is a badly formatted question.Can u please help me,or my friends,with formatting this question    ?thankyou.
Can u please help me,or my friends,with formatting this question    ?

a.b.c.d?
d?

Does this question have a question mark? yes
Does this question have a question mark?

Why example.com resolves to 127.0.0.1 in 99.9 percent of cases?
9 percent of cases?

A? b? c? d!
A?
b?
c?
</code>```

This is code-golf, so the submission with the lowest number of bytes wins!

答:
Batch, 174 bytes

```<code>@echo off
set/ps=
set t=
:l
set c=%s:~0,1%
set t=%t%%c%
if "%c%"=="?" echo %t%&set t=
if "%c%"=="!" set t=
if "%c%"=="." set t=
set s=%s~1%
if not "%s%"=="" goto l
</code>```

Reading a line from STDIN is a byte shorter than using set s=%*.

Title: What exactly was your question?

Body:
Batch, 174 bytes

@echo off
set/ps=
set t=
:l
set c=%s:~0,1%
set t=%t%%c%
if "%c%"=="?" echo %t%&set t=
if "%c%"=="!" set t=
if "%c%"=="." set t=
set s=%s~1%
if not "%s%"=="" goto l

Reading a line from STDIN is a byte shorter than using set s=%*.


问:
Which ghosts are missing?
In this challenge, given a list of ghosts from Pac-Man, you must output which ghosts are missing. You must do it in as few bytes as you can

Input

Input will consist of a string or list, which will include a number ghosts, which could include:

Blinky

Inky

Pinky

Clyde

However, input may also include Pac-Man (with that punctuation). So, the maximum amount of items in a list will be five, in any order. It can be assumed that no invalid items will be in the list

Output

Output will consist of a string, or list. This will include of all the ghosts that are not in the input, in any order. However, if Pac-Man is in the input, all ghosts will be considered missing (because he eats them).

Test cases

```<code>input: Clyde
output: Blinky, Inky, Pinky
alternate output: Inky, Pinky, Blinky
or one of the other 4 permutations

input: Clyde, Blinky # or however you delimit it
output: Inky, Pinky
alt: Pinky, Inky

input: Pac-Man, Clyde
Output: Blinky, Inky, Pinky, Clyde
or you could output one of the other 23 permutations

input:[null]
Output: Blinky, Inky, Pinky, Clyde
or you could output one of the other 23 permutations
</code>```

This is codegolf, so the lower the bytecount, the better.

答:
Lotus Notes @Formula language, <s>85</s> <s>84</s> <s>75</s> 74 characters

-1 character by reversing the @If assignment

-9 Changed @Contains(i;"-") to @Like(i;"%-%") and removed @Trim (not needed if displayed using space as seperator)

-1 by removing the newline

Create a form with two fields: i (Text,Editable,Multi-value) and o (Text,Computed,Multi-value). Enter the following formula in o:

```<code>l:="Inky":"Pinky":"Blinky":"Clyde";@If(@Like(i;"%-%");l;@Replace(l;i;""))
</code>```

From Notes client, create a new document using the form, enter the name(s) in the i field and press F9 to refresh the document. Answer displayed in field o.

This takes advantage of the fact that @Like and @Replace can can both be used either on a string or on a list of strings.

Title: Which ghosts are missing?

Body:
Lotus Notes @Formula language, <s>85</s> <s>84</s> <s>75</s> 74 characters

-1 character by reversing the @If assignment

-9 Changed @Contains(i;"-") to @Like(i;"%-%") and removed @Trim (not needed if displayed using space as seperator)

-1 by removing the newline

Create a form with two fields: i (Text,Editable,Multi-value) and o (Text,Computed,Multi-value). Enter the following formula in o:

l:="Inky":"Pinky":"Blinky":"Clyde";@If(@Like(i;"%-%");l;@Replace(l;i;""))

From Notes client, create a new document using the form, enter the name(s) in the i field and press F9 to refresh the document. Answer displayed in field o.

This takes advantage of the fact that @Like and @Replace can can both be used either on a string or on a list of strings.


答:
Java, <s>571 555</s> 538 or 516 Bytes

```<code>String p(){String r="",z="...",b,x;String[]a="Polar Bear!Lion!Hippopotamus!Flamingo!Zebra!Boa Constrictor!Elephant!Leopard!Peacock!Walrus!Zookeeper!growling!roaring!snorting!fluting!braying!hissing!trumpeting!snarling!yelping!bellowing!whistling".split("!");for(int i=1;i<11;i++){b=i==6?"n ":" ";x=a[i-1];z+=a[i+10]+" like a"+b+x+(i==10?"...":"\n");r+=x+" , "+x+", what do you hear?\n I hear a"+b+a[i].toLowerCase()+" "+a[i+11]+" in my ear.\n\n";}r+=a[10]+" what do you hear?\n\tI hear children...\n"+z+"\nthat's what I hear.";return r;}
</code>```

But only 516 bytes is required to get result in JShell

```<code>String r="",z="...",b,x;String[]a="Polar Bear!Lion!Hippopotamus!Flamingo!Zebra!Boa Constrictor!Elephant!Leopard!Peacock!Walrus!Zookeeper!growling!roaring!snorting!fluting!braying!hissing!trumpeting!snarling!yelping!bellowing!whistling".split("!");for(int i=1;i<11;i++){b=i==6?"n ":" ";x=a[i-1];z+=a[i+10]+" like a"+b+x+(i==10?"...":"\n");r+=x+" , "+x+", what do you hear?\n I hear a"+b+a[i].toLowerCase()+" "+a[i+11]+" in my ear.\n\n";}r+=a[10]+" what do you hear?\n\tI hear children...\n"+z+"\nthat's what I hear."
</code>```

Body:
The text of the children's book Polar Bear, Polar Bear, What Do You Hear?  has a very simple pattern.  You might use the text to teach introductory programming concepts.

My son was quickly bored by this idea, so I decided to play some golf with it instead.

The Challenge

In your programming language of choice, write the smallest program possible which will print the following text.  Output should match exactly, including case, spacing, and punctuation.

```<code>Polar Bear, Polar Bear, what do you hear?
I hear a lion roaring in my ear.

Lion, Lion, what do you hear?
I hear a hippopotamus snorting in my ear.

Hippopotamus, Hippopotamus, what do you hear?
I hear a flamingo fluting in my ear.

Flamingo, Flamingo, what do you hear?
I hear a zebra braying in my ear.

Zebra, Zebra, what do you hear?
I hear a boa constrictor hissing in my ear.

Boa Constrictor, Boa Constrictor, what do you hear?
I hear an elephant trumpeting in my ear.

Elephant, Elephant, what do you hear?
I hear a leopard snarling in my ear.

Leopard, Leopard, what do you hear?
I hear a peacock yelping in my ear.

Peacock, Peacock, what do you hear?
I hear a walrus bellowing in my ear.

Walrus, Walrus, what do you hear?
I hear a zookeeper whistling in my ear.

Zookeeper, Zookeeper, what do you hear?
I hear children...

...growling like a polar bear,
roaring like a lion,
snorting like a hippopotamus,
fluting like a flamingo,
braying like a zebra,
hissing like a boa constrictor,
trumpeting like an elephant,
snarling like a leopard,
yelping like a peacock,
bellowing like a walrus...
that's what I hear.
</code>```

Body:
Java, <s>571 555</s> 538 or 516 Bytes

String p(){String r="",z="...",b,x;String[]a="Polar Bear!Lion!Hippopotamus!Flamingo!Zebra!Boa Constrictor!Elephant!Leopard!Peacock!Walrus!Zookeeper!growling!roaring!snorting!fluting!braying!hissing!trumpeting!snarling!yelping!bellowing!whistling".split("!");for(int i=1;i<11;i++){b=i==6?"n ":" ";x=a[i-1];z+=a[i+10]+" like a"+b+x+(i==10?"...":"\n");r+=x+" , "+x+", what do you hear?\n I hear a"+b+a[i].toLowerCase()+" "+a[i+11]+" in my ear.\n\n";}r+=a[10]+" what do you hear?\n\tI hear children...\n"+z+"\nthat's what I hear.";return r;}

But only 516 bytes is required to get result in JShell

String r="",z="...",b,x;String[]a="Polar Bear!Lion!Hippopotamus!Flamingo!Zebra!Boa Constrictor!Elephant!Leopard!Peacock!Walrus!Zookeeper!growling!roaring!snorting!fluting!braying!hissing!trumpeting!snarling!yelping!bellowing!whistling".split("!");for(int i=1;i<11;i++){b=i==6?"n ":" ";x=a[i-1];z+=a[i+10]+" like a"+b+x+(i==10?"...":"\n");r+=x+" , "+x+", what do you hear?\n I hear a"+b+a[i].toLowerCase()+" "+a[i+11]+" in my ear.\n\n";}r+=a[10]+" what do you hear?\n\tI hear children...\n"+z+"\nthat's what I hear."


答:
Actually, 21 bytes

```<code>ñ`i╗ñ"i╜+@;(=*"£Mi`MΣ
</code>```

Try it online!

Thanks to Leaky Nun for making me stop being lazy and finally write this.

This uses 0-indexed matrices, and takes input as a nested list.

Explanation:

```<code>ñ`i╗ñ"i╜+@;(=*"£Mi`MΣ
ñ                      enumerate input
 `i╗ñ"i╜+@;(=*"£Mi`M   for each (i, row) pair:
  i╗                     flatten, store i in register 0
    ñ                    enumerate the row
     "i╜+@;(=*"£M        for each (j, val) pair:
      i╜+                  flatten, add i to j
         @;(               make an extra copy of val, bring i+j back to top
            =              compare equality of i+j and val
             *             multiply (0 if not equal, val if they are)
                 i       flatten the resulting list
                    Σ  sum the values
</code>```

Title: Dijkstra's Challenge

Body:
Presented in honor of APL as an interactive tool turning 50 this year

Background

Ken [Iverson] presented his paper Formalism in Programming Languages in August 1963 at a Working Conference on Mechanical Language Structures, Princeton, N.J. The list of conferees is full of famous and soon-to-be famous names, and a few future Turing Award winners (Backus, Curry, Dijkstra, Floyd, Iverson, Newell, Perlis, Wilkes). The paper also records the discussion that occurred after the presentation, ending with an exchange between Ken and [Edsger] Dijkstra, in which Ken’s reply to Dijkstra’s question was a one-liner.

Challenge

How would you represent a more complex operation, for example, the sum of all elements of a matrix M which are equal to the sum of the corresponding row and column indices?

Write a snippet or expression (no need for a full program or function) to calculate the sum of each element in a given integer matrix which is equal to the sum of its indices. Or, as FryAmTheEggman puts it: given a matrix M with elements aij return the sum of each aij where aij = i + j.

You may assume the matrix already being in a variable or memory location, or you may take it as an argument or input. You may use either 0 or 1 based indices.

Test cases

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

0 for empty matrix

```<code>2
</code>```

0 for 0 based indices or 2 for 1-based

```<code>1 5 2
9 4 2
5 9 6
</code>```

2 for 0 based or 10 for 1 based

```<code> 0 3  0  4
 0 4  1  4
 4 3  1  2
-2 4 -2 -1
</code>```

11

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

6 for 0 based or 3 for 1 based

Anecdote

Iverson's answer was ++/(M = ⍳¹ ⨢ ⍳¹)//M, which is neither valid in the Iverson Notation as defined in A Programming Language, nor in what eventually became APL. In Iverson notation, it would have been +/(M = ⍳¹(μ(M)) ⨢ ⍳¹(ν(M)))/M. In the very first versions of APL it was +/(,M=(⍳1↑⍴M)∘.+⍳1↓⍴M)/,M.

Body:
Actually, 21 bytes

ñ`i╗ñ"i╜+@;(=*"£Mi`MΣ

Try it online!

Thanks to Leaky Nun for making me stop being lazy and finally write this.

This uses 0-indexed matrices, and takes input as a nested list.

Explanation:

ñ`i╗ñ"i╜+@;(=*"£Mi`MΣ
ñ                      enumerate input
 `i╗ñ"i╜+@;(=*"£Mi`M   for each (i, row) pair:
  i╗                     flatten, store i in register 0
    ñ                    enumerate the row
     "i╜+@;(=*"£M        for each (j, val) pair:
      i╜+                  flatten, add i to j
         @;(               make an extra copy of val, bring i+j back to top
            =              compare equality of i+j and val
             *             multiply (0 if not equal, val if they are)
                 i       flatten the resulting list
                    Σ  sum the values


问:
Print a bunch of uninteresting numbers!
An uninteresting number (which I totally didn't make up only for this challenge) is created like this:

Take a positive integer N

Create a new number O by adding the digits of N at the end of N

The final uninteresting number is O*N

For example for N=12:

O = 1212

O*N = 1212 * 12

Final number is 14544

Input

A positive integer N (N > 0) or your language's equivalent. You don't have to catch incorrect input.

Output

The corresponding uninteresting number.

Test cases

```<code>  1 -> 11
  2 -> 44
  3 -> 99
 10 -> 10100
174 -> 30306276
</code>```

Scoring

Shortest Code in Bytes wins.

答:
Hexagony, 23 bytes

```<code>?'=1*'\|@}*\=+=':<\}0.!
</code>```

Embiggened:

```<code>    ? ' = 1
   * ' \ | @
  } * \ = + =
 ' : < \ } 0 .
  ! . . . . .
   . . . . .
    . . . .
</code>```

Try it online!

As Hexagony doesn't have a concatenation function, it has to be done through multiplying the input by the appropriate factor of 10, then adding the input to it again. For example, CONCAT(12,12) can be implemented as (12 * 100) + 12.

Title: Print a bunch of uninteresting numbers!

Body:
Hexagony, 23 bytes

?'=1*'\|@}*\=+=':<\}0.!

Embiggened:

    ? ' = 1
   * ' \ | @
  } * \ = + =
 ' : < \ } 0 .
  ! . . . . .
   . . . . .
    . . . .

Try it online!

As Hexagony doesn't have a concatenation function, it has to be done through multiplying the input by the appropriate factor of 10, then adding the input to it again. For example, CONCAT(12,12) can be implemented as (12 * 100) + 12.


答:
Python, 46 Bytes

```<code>import re
f=lambda s:re.findall("[^!?.]*\?",s)
</code>```

Call with:

```<code>f("your string here")
</code>```

output on tests:

```<code>['Can u please help me,or my friends,with formatting this question    ?', 'Can u please help me,or my friends,with formatting this question    ?', ' Huh?', ' Could you repeat that please?', ' plz can i haz cheesburgr?', 'd?', 'Does this question have a question mark?', '9 percent of cases?', 'A?', ' b?', ' c?']
</code>```

another idea, 77 bytes (in python3 you'd need a list around filter):

```<code>import re
f=lambda s:filter(lambda x:x[-1]=="?",re.split("(?<=[\.\?!]).",s)))
</code>```

I'm new to this so this, so this could probably be much shorter.

-17 (!) bytes thanks to Martin

-2 bytes by matching anything that is not "!","?" or "." (Getting close to the shell solutions, but I doubt I could save much more)

Title: What exactly was your question?

Body:
Introduction

When you are given a boring text, you just want to get it over with as quick as possible. Let's observe the following text:

```<code>Ens colligi timenda etc priorem judicem. De quascunque ii at contingere
repugnaret explicetur intellectu. Adjuvetis hoc fortassis suspicari opportune
obversari vix eam? Dei praemia prudens hominum iii constet requiri haberem. Ima
sane nemo modi fuit lus pro dem haud. Vestro age negare tactum hoc cui lor. Ne et
ut quod id soli soni deus. At constare innumera is occurret ea. Nia calebat seu
acquiro fraudem effingo dicimus.
</code>```

Note: This text has newlines for readability, while the test cases you need to handle don't have newline characters.

One way to skim text is to find questions that the writer has put into the text. For example, there is 1 question in the text above. Namely:

```<code>Adjuvetis hoc fortassis suspicari opportune obversari vix eam?
</code>```

This can be done by splitting the text into sentences. A sentence will always end with one of the following punctuation symbols: .?! (others don't have to be handled). Other symbols than these are part of the sentence.

The Task

Given a line of text consisting of only

letters (A-Za-z)

numbers (0-9)

spaces

punctuation (,.;:?!) (a sentence cannot start with one of these).

Output the questions that are in the text in any reasonable format. You may assume that the text will always have at least 1 question. Outputting trailing and leading spaces before and after a question is allowed.

Important: Next to a punctuation symbol, there will never be another punctuation symbol (e.g. ?? is invalid and will not be required to handle).

Test cases

In the format:

```<code>Input
Output(s)
</code>```

The test cases:

```<code>Huh? I haven't heard what you just said. Could you repeat that please?
Huh?
Could you repeat that please?

plz can i haz cheesburgr? i am cat pls.
plz can i haz cheesburgr?

This is a badly formatted question.Can u please help me,or my friends,with formatting this question    ?thankyou.
Can u please help me,or my friends,with formatting this question    ?

a.b.c.d?
d?

Does this question have a question mark? yes
Does this question have a question mark?

Why example.com resolves to 127.0.0.1 in 99.9 percent of cases?
9 percent of cases?

A? b? c? d!
A?
b?
c?
</code>```

This is code-golf, so the submission with the lowest number of bytes wins!

Body:
Python, 46 Bytes

import re
f=lambda s:re.findall("[^!?.]*\?",s)

Call with:

f("your string here")

output on tests:

['Can u please help me,or my friends,with formatting this question    ?', 'Can u please help me,or my friends,with formatting this question    ?', ' Huh?', ' Could you repeat that please?', ' plz can i haz cheesburgr?', 'd?', 'Does this question have a question mark?', '9 percent of cases?', 'A?', ' b?', ' c?']

another idea, 77 bytes (in python3 you'd need a list around filter):

import re
f=lambda s:filter(lambda x:x[-1]=="?",re.split("(?<=[\.\?!]).",s)))

I'm new to this so this, so this could probably be much shorter.

-17 (!) bytes thanks to Martin

-2 bytes by matching anything that is not "!","?" or "." (Getting close to the shell solutions, but I doubt I could save much more)


问:
Compute the maximum number of runs possible for as large a string as possible
[This question is a follow up to Compute the runs of a string ]

A period p of a string w is any positive integer p such that w[i]=w[i+p]
  whenever both sides of this equation are defined. Let per(w) denote
  the size of the smallest period of w . We say that a string w is
  periodic iff per(w) <= |w|/2.

So informally a periodic string is just a string that is made up from another string repeated at least once.  The only complication is that at the end of the string we don't require a full copy of the repeated string as long as it is repeated in its entirety at least once.

For, example consider the string x = abcab. per(abcab) = 3 as x[1] = x[1+3] = a, x[2]=x[2+3] = b and there is no smaller period. The string abcab is therefore not periodic.  However, the string ababa is periodic as per(ababa) = 2.

As more examples, abcabca, ababababa and abcabcabc are also periodic.

For those who like regexes, this one detects if a string is periodic or not:

```<code>\b(\w*)(\w+\1)\2+\b
</code>```

The task is to find all maximal periodic substrings in a longer string.  These are sometimes called runs in the literature.

A substring w is a maximal periodic substring (run) if it is periodic and neither w[i-1] = w[i-1+p] nor w[j+1] = w[j+1-p].  Informally, the "run" cannot be contained in a larger "run"
  with the same period.

Because two runs can represent the same string of characters occurring in different places in the overall string, we will represent runs by intervals. Here is the above definition repeated in terms of intervals.

A run (or maximal periodic substring) in a string T is an interval
  [i...j] with j>=i, such that

T[i...j] is a periodic word with the period p = per(T[i...j])

It is maximal. Formally, neither T[i-1] = T[i-1+p] nor T[j+1] = T[j+1-p].  Informally, the run cannot be contained in a larger run
  with the same period.

Denote by RUNS(T) the set of runs in string T.

Examples of runs

The four maximal periodic substrings (runs) in string T = atattatt are T[4,5] = tt, T[7,8] = tt, T[1,4] = atat, T[2,8] = tattatt.

The string T = aabaabaaaacaacac contains the following 7 maximal periodic substrings (runs):
T[1,2] = aa, T[4,5] = aa, T[7,10] = aaaa, T[12,13] = aa, T[13,16] = acac, T[1,8] = aabaabaa, T[9,15] = aacaaca.

The string T = atatbatatb contains the following three runs. They are:
T[1, 4] = atat, T[6, 9] = atat and  T[1, 10] = atatbatatb.

Here I am using 1-indexing.

The task

Write code so that for each integer n starting at 2, you output the largest numbers of runs contained in any binary string of length n.

Score

Your score is the highest n you reach in 120 seconds such that for all k <= n, no one else has posted a higher correct answer than you.  Clearly if you have all optimum answers then you will get the score for the highest n you post. However, even if your answer is not the optimum, you can still get the score if no one else can beat it.

Languages and libraries

You can use any available language and libraries you like. Where feasible, it would be good to be able to run your code so please include a full explanation for how to run/compile your code in Linux if at all possible.

Example optima

In the following: n, optimum number of runs, example string.

```<code>2 1 00
3 1 000
4 2 0011
5 2 00011
6 3 001001
7 4 0010011
8 5 00110011
9 5 000110011
10 6 0010011001
11 7 00100110011
12 8 001001100100
13 8 0001001100100
14 10 00100110010011
15 10 000100110010011
16 11 0010011001001100
17 12 00100101101001011
18 13 001001100100110011
19 14 0010011001001100100
20 15 00101001011010010100
21 15 000101001011010010100
22 16 0010010100101101001011
</code>```

What exactly should my code output?

For each n your code should output a single string and the number of runs it contains.

My Machine The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor.  This also means I need to be able to run your code.

Leading answers

49 by Anders Kaseorg in C. Single threaded and run with L = 12 (2GB of RAM).

27 by cdlane in C.

答:
C

This does a recursive search for optimal solutions, heavily pruned using an upper bound on the number of runs that could be finished by the unknown remainder of the string.  The upper bound computation uses a gigantic lookup table whose size is controlled by the constant L (L=11: 0.5 GiB, L=12: 2 GiB, L=13: 8 GiB).

On my laptop, this goes up through n = 50 in 100 seconds; the next line comes at 142 seconds.

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#define N (8*sizeof(unsigned long long))
#define L 13
static bool a[N], best_a[N];
static int start[N/2 + 1], best_runs;
static uint8_t end_runs[2 << 2*L][2], small[N + 1][2 << 2*L];

static inline unsigned next_state(unsigned state, int b)
{
    state *= 2;
    state += b;
    if (state >= 2 << 2*L) {
        state &= ~(2 << 2*L);
        state |= 1 << 2*L;
    }
    return state;
}

static void search(int n, int i, int runs, unsigned state)
{
    if (i == n) {
        int r = runs;
        unsigned long long m = 0;
        for (int p = n / 2; p > 0; p--) {
            if (i - start[p] >= 2*p && !(m & 1ULL << start[p])) {
                m |= 1ULL << start[p];
                r++;
            }
        }
        if (r > best_runs) {
            best_runs = r;
            memcpy(best_a, a, n*sizeof(a[0]));
        }
    } else {
        a[i] = false;
        do {
            int r = runs, bound = 0, saved = 0, save_p[N/2], save_start[N/2], p, s = next_state(state, a[i]);
            unsigned long long m = 0;
            for (p = n/2; p > i; p--)
                if (p > L)
                    bound += (n - p + 1)/(p + 1);
            for (; p > 0; p--) {
                if (a[i] != a[i - p]) {
                    if (i - start[p] >= 2*p && !(m & 1ULL << start[p])) {
                        m |= 1ULL << start[p];
                        r++;
                    }
                    save_p[saved] = p;
                    save_start[saved] = start[p];
                    saved++;
                    start[p] = i + 1 - p;
                    if (p > L)
                        bound += (n - i)/(p + 1);
                } else {
                    if (p > L)
                        bound += (n - (start[p] + p - 1 > i - p ? start[p] + p - 1 : i - p))/(p + 1);
                }
            }
            bound += small[n - i - 1][s];

            if (r + bound > best_runs)
                search(n, i + 1, r, s);
            while (saved--)
                start[save_p[saved]] = save_start[saved];
        } while ((a[i] = !a[i]));
    }
}

int main()
{
    for (int n = 0; n <= N; n++) {
        if (n <= 2*L) {
            for (unsigned state = 1U << n; state < 2U << n; state++) {
                for (int b = 0; b < 2; b++) {
                    int r = 0;
                    unsigned long long m = 0;
                    for (int p = n / 2; p > 0; p--) {
                        if ((b ^ state >> (p - 1)) & 1) {
                            unsigned k = state ^ state >> p;
                            k &= -k;
                            k <<= p;
                            if (!(k & ~(~0U << n)))
                                k = 1U << n;
                            if (!((m | ~(~0U << 2*p)) & k)) {
                                m |= k;
                                r++;
                            }
                        }
                    }
                    end_runs[state][b] = r;
                }
                small[0][state] = end_runs[state][0] + end_runs[state][1];
            }
        }

        for (int l = 2*L < n - 1 ? 2*L : n - 1; l >= 0; l--) {
            for (unsigned state = 1U << l; state < 2U << l; state++) {
                int r0 = small[n - l - 1][next_state(state, 0)] + end_runs[state][0],
                    r1 = small[n - l - 1][next_state(state, 1)] + end_runs[state][1];
                small[n - l][state] = r0 > r1 ? r0 : r1;
            }
        }

        if (n >= 2) {
            search(n, 1, 0, 2U);
            printf("%d %d ", n, best_runs);
            for (int i = 0; i < n; i++)
                printf("%d", best_a[i]);
            printf("\n");
            fflush(stdout);
            best_runs--;
        }
    }
    return 0;
}
```

<p>Output:</p>

```$ gcc -mcmodel=medium -O2 runs.c -o runs
$ ./runs
2 1 00
3 1 000
4 2 0011
5 2 00011
6 3 001001
7 4 0010011
8 5 00110011
9 5 000110011
10 6 0010011001
11 7 00100110011
12 8 001001100100
13 8 0001001100100
14 10 00100110010011
15 10 000100110010011
16 11 0010011001001100
17 12 00100101101001011
18 13 001001100100110011
19 14 0010011001001100100
20 15 00101001011010010100
21 15 000101001011010010100
22 16 0010010100101101001011
23 17 00100101001011010010100
24 18 001001100100110110011011
25 19 0010011001000100110010011
26 20 00101001011010010100101101
27 21 001001010010110100101001011
28 22 0010100101101001010010110100
29 23 00101001011010010100101101011
30 24 001011010010110101101001011010
31 25 0010100101101001010010110100101
32 26 00101001011010010100101101001011
33 27 001010010110100101001011010010100
34 27 0001010010110100101001011010010100
35 28 00100101001011010010100101101001011
36 29 001001010010110100101001011010010100
37 30 0010011001001100100010011001001100100
38 30 00010011001001100100010011001001100100
39 31 001001010010110100101001011010010100100
40 32 0010010100101101001010010110100101001011
41 33 00100110010001001100100110010001001100100
42 35 001010010110100101001011010110100101101011
43 35 0001010010110100101001011010110100101101011
44 36 00101001011001010010110100101001011010010100
45 37 001001010010110100101001011010110100101101011
46 38 0010100101101001010010110100101001011010010100
47 39 00101101001010010110100101101001010010110100101
48 40 001010010110100101001011010010110101101001011010
49 41 0010100101101001010010110100101101001010010110100
50 42 00101001011010010100101101001011010110100101101011
51 43 001010010110100101001011010110100101001011010010100
```

<p>Here are <em>all</em> optimal sequences for <em>n</em> ≤ 64 (not just the lexicographically first), generated by a modified version of this program and many hours of computation.</p>

<h1>A remarkable nearly-optimal sequence</h1>

<p>The prefixes of the infinite fractal sequence</p>

```1010010110100101001011010010110100101001011010010100101…
```

<p>that is invariant under the transformation 101 ↦ 10100, 00 ↦ 101:</p>

```  101   00  101   101   00  101   00  101   101   00  101   101   00  …
= 10100 101 10100 10100 101 10100 101 10100 10100 101 10100 10100 101 …
```

seem to have very nearly optimal numbers of runs—always within 2 of optimal for n ≤ 64. The number of runs in the first n characters divided by n approaches (13 − 5√5)/2 ≈ 0.90983. But it turns out this is not the optimal ratio—see comments.

Body:
C

This does a recursive search for optimal solutions, heavily pruned using an upper bound on the number of runs that could be finished by the unknown remainder of the string.  The upper bound computation uses a gigantic lookup table whose size is controlled by the constant L (L=11: 0.5 GiB, L=12: 2 GiB, L=13: 8 GiB).

On my laptop, this goes up through n = 50 in 100 seconds; the next line comes at 142 seconds.

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#define N (8*sizeof(unsigned long long))
#define L 13
static bool a[N], best_a[N];
static int start[N/2 + 1], best_runs;
static uint8_t end_runs[2 << 2*L][2], small[N + 1][2 << 2*L];

static inline unsigned next_state(unsigned state, int b)
{
    state *= 2;
    state += b;
    if (state >= 2 << 2*L) {
        state &= ~(2 << 2*L);
        state |= 1 << 2*L;
    }
    return state;
}

static void search(int n, int i, int runs, unsigned state)
{
    if (i == n) {
        int r = runs;
        unsigned long long m = 0;
        for (int p = n / 2; p > 0; p--) {
            if (i - start[p] >= 2*p && !(m & 1ULL << start[p])) {
                m |= 1ULL << start[p];
                r++;
            }
        }
        if (r > best_runs) {
            best_runs = r;
            memcpy(best_a, a, n*sizeof(a[0]));
        }
    } else {
        a[i] = false;
        do {
            int r = runs, bound = 0, saved = 0, save_p[N/2], save_start[N/2], p, s = next_state(state, a[i]);
            unsigned long long m = 0;
            for (p = n/2; p > i; p--)
                if (p > L)
                    bound += (n - p + 1)/(p + 1);
            for (; p > 0; p--) {
                if (a[i] != a[i - p]) {
                    if (i - start[p] >= 2*p && !(m & 1ULL << start[p])) {
                        m |= 1ULL << start[p];
                        r++;
                    }
                    save_p[saved] = p;
                    save_start[saved] = start[p];
                    saved++;
                    start[p] = i + 1 - p;
                    if (p > L)
                        bound += (n - i)/(p + 1);
                } else {
                    if (p > L)
                        bound += (n - (start[p] + p - 1 > i - p ? start[p] + p - 1 : i - p))/(p + 1);
                }
            }
            bound += small[n - i - 1][s];

            if (r + bound > best_runs)
                search(n, i + 1, r, s);
            while (saved--)
                start[save_p[saved]] = save_start[saved];
        } while ((a[i] = !a[i]));
    }
}

int main()
{
    for (int n = 0; n <= N; n++) {
        if (n <= 2*L) {
            for (unsigned state = 1U << n; state < 2U << n; state++) {
                for (int b = 0; b < 2; b++) {
                    int r = 0;
                    unsigned long long m = 0;
                    for (int p = n / 2; p > 0; p--) {
                        if ((b ^ state >> (p - 1)) & 1) {
                            unsigned k = state ^ state >> p;
                            k &= -k;
                            k <<= p;
                            if (!(k & ~(~0U << n)))
                                k = 1U << n;
                            if (!((m | ~(~0U << 2*p)) & k)) {
                                m |= k;
                                r++;
                            }
                        }
                    }
                    end_runs[state][b] = r;
                }
                small[0][state] = end_runs[state][0] + end_runs[state][1];
            }
        }

        for (int l = 2*L < n - 1 ? 2*L : n - 1; l >= 0; l--) {
            for (unsigned state = 1U << l; state < 2U << l; state++) {
                int r0 = small[n - l - 1][next_state(state, 0)] + end_runs[state][0],
                    r1 = small[n - l - 1][next_state(state, 1)] + end_runs[state][1];
                small[n - l][state] = r0 > r1 ? r0 : r1;
            }
        }

        if (n >= 2) {
            search(n, 1, 0, 2U);
            printf("%d %d ", n, best_runs);
            for (int i = 0; i < n; i++)
                printf("%d", best_a[i]);
            printf("\n");
            fflush(stdout);
            best_runs--;
        }
    }
    return 0;
}

Output:

$ gcc -mcmodel=medium -O2 runs.c -o runs
$ ./runs
2 1 00
3 1 000
4 2 0011
5 2 00011
6 3 001001
7 4 0010011
8 5 00110011
9 5 000110011
10 6 0010011001
11 7 00100110011
12 8 001001100100
13 8 0001001100100
14 10 00100110010011
15 10 000100110010011
16 11 0010011001001100
17 12 00100101101001011
18 13 001001100100110011
19 14 0010011001001100100
20 15 00101001011010010100
21 15 000101001011010010100
22 16 0010010100101101001011
23 17 00100101001011010010100
24 18 001001100100110110011011
25 19 0010011001000100110010011
26 20 00101001011010010100101101
27 21 001001010010110100101001011
28 22 0010100101101001010010110100
29 23 00101001011010010100101101011
30 24 001011010010110101101001011010
31 25 0010100101101001010010110100101
32 26 00101001011010010100101101001011
33 27 001010010110100101001011010010100
34 27 0001010010110100101001011010010100
35 28 00100101001011010010100101101001011
36 29 001001010010110100101001011010010100
37 30 0010011001001100100010011001001100100
38 30 00010011001001100100010011001001100100
39 31 001001010010110100101001011010010100100
40 32 0010010100101101001010010110100101001011
41 33 00100110010001001100100110010001001100100
42 35 001010010110100101001011010110100101101011
43 35 0001010010110100101001011010110100101101011
44 36 00101001011001010010110100101001011010010100
45 37 001001010010110100101001011010110100101101011
46 38 0010100101101001010010110100101001011010010100
47 39 00101101001010010110100101101001010010110100101
48 40 001010010110100101001011010010110101101001011010
49 41 0010100101101001010010110100101101001010010110100
50 42 00101001011010010100101101001011010110100101101011
51 43 001010010110100101001011010110100101001011010010100

Here are all optimal sequences for n ≤ 64 (not just the lexicographically first), generated by a modified version of this program and many hours of computation.

A remarkable nearly-optimal sequence

The prefixes of the infinite fractal sequence

1010010110100101001011010010110100101001011010010100101…

that is invariant under the transformation 101 ↦ 10100, 00 ↦ 101:

  101   00  101   101   00  101   00  101   101   00  101   101   00  …
= 10100 101 10100 10100 101 10100 101 10100 10100 101 10100 10100 101 …

seem to have very nearly optimal numbers of runs—always within 2 of optimal for n ≤ 64. The number of runs in the first n characters divided by n approaches (13 − 5√5)/2 ≈ 0.90983. But it turns out this is not the optimal ratio—see comments.