问:
Sort this, quick!
Well... there are 59 (now 60) questions tagged sorting, but no simple quicksorts.

That must be fixed.

For those unfamiliar with quicksort, here is a breakdown, courtesy of Wikipedia-

Pick an element, called a pivot, from the array.

Reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.

Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.

Rules

The rules are simple:

Implement a numerical quicksort in the programming language of your choice.

The pivot should be chosen at random or with median of three (1st, last, and middle element).

Your program can be a complete program or function.

You can get the input using STDIN, command line args, or function parameters. If using a string input, the input is space separated.

The input may contain decimal and negative values. However, there will be no duplicates.

You may output to STDOUT or by returning from the function.

No built-in sorting (or sorting related) functions or standard loopholes.

The list may be an arbitrary length.

Bonus #1: On lists or sub-lists of length <= 5, use insertion sort to speed things up a bit. Reward: -15%.

Bonus #2: If your language supports concurrency, sort the list in parallel. If you are using an insertion sort on sub-lists, the final insertion sort doesn't need to be in parallel. Built in thread pools/ thread scheduling are allowed. Reward: -15%.

Note: Median of three was confusing some people, so here is an explanation, courtesy of (again) Wikipedia:

choosing the median of the first, middle and last element of the partition for the pivot

Scoring

This is code-golf. Base score is in bytes. If you got one bonus, take 15% off that number. If you got both, take 30% off. That really sounds like a sales pitch.

This isn't about finding the shortest answer overall, but rather the shortest in each language.

And now, a shameless copy of the leaderboard snippet.

The Leaderboard

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>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

/* Configuration */

var QUESTION_ID = 62476; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 41505; // 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 "http://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 "http://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+(?:.\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}

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

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

table thead {
  font-weight: bold;
}

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Lua, 242 Bytes

```<code>function f(t,p)if(#t>0)then local P,l,r,i=math.random(#t),{},{},table.insert p=t[P]for k,v in ipairs(t)do if(k~=P)then i(v<p and l or r,v)end end t={}for k,v in pairs(f(l))do i(t,v)end i(t,p)for k,v in pairs(f(r))do i(t,v)end end return t end
</code>```

Ungolfed & Explination

```<code>function f(t,p)                                             # Assign 'p' here, which saves two bytes, because we can't assign it to t[P] IN the local group.
    if(#t>0)then                                            # Just return 0 length lists...
        local P,l,r,i=math.random(#t),{},{},table.insert    # Using local here actually makes the a,b=1,2 method more efficient here. Which is unnormal for Lua
        p = t[P]                                            # P is the index of the pivot, p is the value of the pivot, l and r are the sub-lists around the pivot, and i is table.insert to save bytes.
        for k,v in ipairs(t) do                             # We use a completely random pivot, because it's cheaper on the bytes.
            if(k~=P)then                                    # Avoid 'sorting' the pivot.
                i(v<p and l or r,v)                         # If the value is less than the pivot value, push it to the left list, otherwise, push it to the right list.
            end                                             #
        end                                                 #
        t = {}                                              # We can re-use t here, because we don't need it anymore, and it's already a local value. Saving bytes!
        for k,v in pairs(f(l)) do                           # Quick sort the left list, then append it to the new output list.
            i(t,v)                                          #
        end                                                 #
        i(t,p)                                              # Append the pivot value.
        for k,v in pairs(f(r)) do                           # Ditto the right list.
            i(t,v)                                          #
        end                                                 #
    end                                                     #
    return t                                                # Return...
end                                                         #
</code>```

Title: Sort this, quick!

Body:
Lua, 242 Bytes

function f(t,p)if(#t>0)then local P,l,r,i=math.random(#t),{},{},table.insert p=t[P]for k,v in ipairs(t)do if(k~=P)then i(v<p and l or r,v)end end t={}for k,v in pairs(f(l))do i(t,v)end i(t,p)for k,v in pairs(f(r))do i(t,v)end end return t end

Ungolfed & Explination

function f(t,p)                                             # Assign 'p' here, which saves two bytes, because we can't assign it to t[P] IN the local group.
    if(#t>0)then                                            # Just return 0 length lists...
        local P,l,r,i=math.random(#t),{},{},table.insert    # Using local here actually makes the a,b=1,2 method more efficient here. Which is unnormal for Lua
        p = t[P]                                            # P is the index of the pivot, p is the value of the pivot, l and r are the sub-lists around the pivot, and i is table.insert to save bytes.
        for k,v in ipairs(t) do                             # We use a completely random pivot, because it's cheaper on the bytes.
            if(k~=P)then                                    # Avoid 'sorting' the pivot.
                i(v<p and l or r,v)                         # If the value is less than the pivot value, push it to the left list, otherwise, push it to the right list.
            end                                             #
        end                                                 #
        t = {}                                              # We can re-use t here, because we don't need it anymore, and it's already a local value. Saving bytes!
        for k,v in pairs(f(l)) do                           # Quick sort the left list, then append it to the new output list.
            i(t,v)                                          #
        end                                                 #
        i(t,p)                                              # Append the pivot value.
        for k,v in pairs(f(r)) do                           # Ditto the right list.
            i(t,v)                                          #
        end                                                 #
    end                                                     #
    return t                                                # Return...
end                                                         #


答:
Racket 121 bytes

```<code>(λ(l)(if(null? l)l(let((h(car l))(t(cdr l)))(append(qs (filter(λ(x)(< x h))t))(list h)(qs (filter(λ(x)(>= x h))t))))))
</code>```

Ungolfed (l=list, h=head (first element), t=tail (rest or remaining elements)):

```<code>(define qs
  (λ(l)
    (if (null? l) l
        (let ((h (first l))
              (t (rest  l)))
          (append (qs (filter (λ(x) (< x h) ) t))
                  (list h)
                  (qs (filter (λ(x) (>= x h)) t))  )))))
</code>```

Testing:

```<code>(qs (list 5 8 6 8 9 1 2 4 9 3 5 7 2 5))
</code>```

Output:

```<code>'(1 2 2 3 4 5 5 5 6 7 8 8 9 9)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sort this, quick!

Body:
Well... there are 59 (now 60) questions tagged sorting, but no simple quicksorts.

That must be fixed.

For those unfamiliar with quicksort, here is a breakdown, courtesy of Wikipedia-

Pick an element, called a pivot, from the array.

Reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.

Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.

Rules

The rules are simple:

Implement a numerical quicksort in the programming language of your choice.

The pivot should be chosen at random or with median of three (1st, last, and middle element).

Your program can be a complete program or function.

You can get the input using STDIN, command line args, or function parameters. If using a string input, the input is space separated.

The input may contain decimal and negative values. However, there will be no duplicates.

You may output to STDOUT or by returning from the function.

No built-in sorting (or sorting related) functions or standard loopholes.

The list may be an arbitrary length.

Bonus #1: On lists or sub-lists of length <= 5, use insertion sort to speed things up a bit. Reward: -15%.

Bonus #2: If your language supports concurrency, sort the list in parallel. If you are using an insertion sort on sub-lists, the final insertion sort doesn't need to be in parallel. Built in thread pools/ thread scheduling are allowed. Reward: -15%.

Note: Median of three was confusing some people, so here is an explanation, courtesy of (again) Wikipedia:

choosing the median of the first, middle and last element of the partition for the pivot

Scoring

This is code-golf. Base score is in bytes. If you got one bonus, take 15% off that number. If you got both, take 30% off. That really sounds like a sales pitch.

This isn't about finding the shortest answer overall, but rather the shortest in each language.

And now, a shameless copy of the leaderboard snippet.

The Leaderboard

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>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

/* Configuration */

var QUESTION_ID = 62476; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 41505; // 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 "http://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 "http://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+(?:.\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}

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

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

table thead {
  font-weight: bold;
}

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
Racket 121 bytes

(λ(l)(if(null? l)l(let((h(car l))(t(cdr l)))(append(qs (filter(λ(x)(< x h))t))(list h)(qs (filter(λ(x)(>= x h))t))))))

Ungolfed (l=list, h=head (first element), t=tail (rest or remaining elements)):

(define qs
  (λ(l)
    (if (null? l) l
        (let ((h (first l))
              (t (rest  l)))
          (append (qs (filter (λ(x) (< x h) ) t))
                  (list h)
                  (qs (filter (λ(x) (>= x h)) t))  )))))

Testing:

(qs (list 5 8 6 8 9 1 2 4 9 3 5 7 2 5))

Output:

'(1 2 2 3 4 5 5 5 6 7 8 8 9 9)


问:
Multiple-Key Sorting
Given a list of indices and zero or more lists of integers, output the lists of integers, sorted in ascending order, with the key priority from the first input.

Example

Let the keys input be [1, 0, 2], and the lists input be [[5, 3, 4], [6, 2, 1], [5, 2, 1]]. Those lists need to be sorted by their second element, then first element, then third element, in ascending order:

First, we sort by the values at index 1: [[6, 2, 1], [5, 2, 1], [5, 3, 4]]

Next, we break any ties from the first sort using the values at index 0: [[5, 2, 1], [6, 2, 1], [5, 3, 4]]

Finally, we break any remaining ties with the vlues at index 2 (this doesn't actually change anything, because there are no ties remaining).

Details

Sorting is stable: if two elements compare equal with respect to the given sort keys, they must remain in the same relative order in the output. For example, if A and B are equal under the given sort keys, and the input was [..., A, ..., B, ...], A must be placed before B in the output.

A sort key will never reference a non-existant element in one of the input lists.

No sort key will be repeated. Thus, [1, 2, 1] is not a valid list of sort keys.

Any elements not referenced by the sort keys do not factor into the sorting order. Only the initial relative order and the values of the elements referenced by the sort keys determine the output order.

You may choose whether the sort keys are zero-indexed or one-indexed.

There will be no negative values in the sort keys. If you choose to use one-indexing, there will be no zeroes in the sort keys either.

Integer values will not exceed your language's natively-representable range. If your chosen language is natively capable of arbitrary-precision integers (like Python), then any integer value can be present in the input, subject to memory constraints.

Reference Implementation (Python 2)

#!/usr/bin/env python

keys = input()
lists = input()

print sorted(lists, key=lambda l:[l[x] for x in keys])
```
<p>Try it online</p>
<h2>Test Cases</h2>
<p>Format: <code>keys lists -> output</code>. All sort keys are zero-indexed.</p>
```[1, 0, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[5, 2, 1], [6, 2, 1], [5, 3, 4]]
[1, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[6, 2, 1], [5, 2, 1], [5, 3, 4]]
[0, 1] [[1, 2], [2, 1]] -> [[1, 2], [2, 1]]
[1, 0] [[1, 2], [2, 1]] -> [[2, 1], [1, 2]]
[0] [[4], [10, 11, -88], [-2, 7]] -> [[-2, 7], [4], [10, 11, -88]]
[2] [[-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6]] -> [[-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2]]
[2, 1] [[9, 2, -2, -10, -6], [3, -4, -2]] -> [[3, -4, -2], [9, 2, -2, -10, -6]]
[2, 4, 8] [[5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5], [-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3]] -> [[-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3], [5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5]]
[1, 2, 3, 4, 5] [[-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [5, 3, -6, -5, -4, -4, -8, 2], [9, -4, 1, -1, -3, -2], [-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [1, -5, -3, -10, -7, 9, -8, -5, -1], [-9, 4, -1, -1, 2, 4]] -> [[-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -5, -3, -10, -7, 9, -8, -5, -1], [9, -4, 1, -1, -3, -2], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [5, 3, -6, -5, -4, -4, -8, 2], [-9, 4, -1, -1, 2, 4]]
[8, 7, 3, 2, 4, 9, 1] [[8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9]] -> [[10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5]]
```

Title: Multiple-Key Sorting

Body:
Perl 6 <s> 23 20 </s> 19 bytes

->\a,\b{b.sort:{.[|a]}}
{$^a;$^b.sort:{.[|$a]}}
{$^b.sort: *.[|$^a]}

{$^b.sort: *[|$^a]}


问:
Unlucky Numbers!

Things to know:

First, lucky numbers.

Lucky numbers are generated like so:

Take all the natural numbers:

```<code>1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20...
</code>```

Then, remove each second number.

```<code>1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39...
</code>```

Now, 3 is safe.

Remove every 3rd number:

```<code>1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 59...
</code>```

Now, 7 is safe.

Remove every 7th number.

Continue, and remove every nth number, where n is the first safe number after an elimination.

The final list of safe numbers is the lucky numbers.

The unlucky numbers is composed of separate lists of numbers, which are [U1, U2, U3... Un].

U1 is the first set of numbers removed from the lucky "candidates", so they are:

```<code>2, 4, 6, 8, 10, 12, 14, 16, 18, 20...
</code>```

U2 is the second set of numbers removed:

```<code>5, 11, 17, 23, 29, 35, 41, 47, 53, 59...
</code>```

And so on and so forth (U3 is the third list, U4 is the fourth, etc.)

Challenge:

Your task is, when given two inputs m and n, generate the mth number in the list Un.

Example inputs and outputs:

```<code>(5, 2) -> 29
(10, 1) -> 20
</code>```

Specs:

Your program must work for m up to 1e6, and n up to 100.

You are guaranteed that both m and n are positive integers.

If you're curious, U(1e6, 100) = 5,333,213,163. (Thank you @pacholik!)

Your program must compute that within 1 day on a reasonable modern computer.

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

PS: It would be nice if someone came up with a general formula for generating these. If you do have a formula, please put it in your answer!

答:
CJam, 74 bytes

```<code>ri0Lri:U{1$W%{1$\(1e>/+}/)+}/2t:A0@{@:B:(_0#):D{D(_A=tD<BD>+}&@)@DU=-}h]1=
</code>```

Try it online! Will time out for larger cases, more on time constraints below.

Explanation:

Our program shamelessly borrows for aditsu's code to generate a list of N lucky numbers, replacing 1 with a 2 gives the increment in each phase of the sieve. The remaining code decrements on every element until a zero is found (by slicing and appending an un-decremented tail) and effectively counts the steps in each of N phases of the sieve at once.

```<code>ri                               e# read M
0Lri:U{1$W%{1$\(1e>/+}/)+}/2t:A  e# list steps (also becomes B)
0@                               e# arrange stack [B I M]
{                                e# while M
   @:B                           e#   get current B
   :(                            e#   decrement every element in B
   _0#):D                        e#   find first 0
   {                             e#   if there is a 0
      D(_A=t                     e#     reset that element in B
      D<BD>+                     e#     replace tail after 0
   }&                            e#   end if
   @)                            e#   increment I
   @DU=-                         e#   decrement M if N-th phase of sieve
}h                               e# end loop
]1=                              e# return I
</code>```

Timing:

If you absolutely must run the program in browser for larger numbers you can use this interpreter and allow the script to continue if prompted, but this maybe too slow to qualify. Using (M,N)=(100,100) takes ~247s. The programs iteration is relatively linear in terms of M, so computing (1e6,100) could take ~29 days.

Using the shell interpreter on a PC the program computes (100,100) in ~6s and computes (1e4,100) in ~463s. The program should be able to compute (1e6,100) in ~13-17hrs. In this case I'll assume the program qualifies.

Note all times were rounded up in both measurements and calculations.

Title: Unlucky Numbers!

Body:
CJam, 74 bytes

ri0Lri:U{1$W%{1$\(1e>/+}/)+}/2t:A0@{@:B:(_0#):D{D(_A=tD<BD>+}&@)@DU=-}h]1=

Try it online! Will time out for larger cases, more on time constraints below.

Explanation:

Our program shamelessly borrows for aditsu's code to generate a list of N lucky numbers, replacing 1 with a 2 gives the increment in each phase of the sieve. The remaining code decrements on every element until a zero is found (by slicing and appending an un-decremented tail) and effectively counts the steps in each of N phases of the sieve at once.

ri                               e# read M
0Lri:U{1$W%{1$\(1e>/+}/)+}/2t:A  e# list steps (also becomes B)
0@                               e# arrange stack [B I M]
{                                e# while M
   @:B                           e#   get current B
   :(                            e#   decrement every element in B
   _0#):D                        e#   find first 0
   {                             e#   if there is a 0
      D(_A=t                     e#     reset that element in B
      D<BD>+                     e#     replace tail after 0
   }&                            e#   end if
   @)                            e#   increment I
   @DU=-                         e#   decrement M if N-th phase of sieve
}h                               e# end loop
]1=                              e# return I

Timing:

If you absolutely must run the program in browser for larger numbers you can use this interpreter and allow the script to continue if prompted, but this maybe too slow to qualify. Using (M,N)=(100,100) takes ~247s. The programs iteration is relatively linear in terms of M, so computing (1e6,100) could take ~29 days.

Using the shell interpreter on a PC the program computes (100,100) in ~6s and computes (1e4,100) in ~463s. The program should be able to compute (1e6,100) in ~13-17hrs. In this case I'll assume the program qualifies.

Note all times were rounded up in both measurements and calculations.


答:
Racket 218 bytes

```<code>(λ(il ll)(define qsl(λ(l i)(if(null? l)l(let*((h(first l))(t(rest l))(g(λ(ff)(filter(λ(x)(ff(list-ref x i)
(list-ref h i)))t))))(append(qsl(g <)i)(list h)(qsl(g >=)i))))))(for((i(reverse il)))(set! ll(qsl ll i)))ll)
</code>```

Ungolfed (il=index list; ll=list of lists; qsl= quicksort for list of lists; h=head (first element); t=tail (rest or remaining elements); g=modifiable filter fn):

```<code>(define qsl
  (λ(l i)
    (if (null? l)
        l
        (let* ((h (first l))
               (t (rest  l))
               (g (λ(ff) (filter (λ(x) (ff (list-ref x i) (list-ref h i))) t))))
          (append (qsl (g <) i)
                  (list h)
                  (qsl (g >=) i)
                  )))))
(define f
  (λ(il ll)
    (for ((i (reverse il)))
      (set! ll (qsl ll i)))
    ll))
</code>```

Testing:

```<code>(f (list 0 1 2) (list (list 5 3 4) (list 5 3 7) (list 6 2 1) (list 6 1 3) (list 5 2 1)))
(f [list 1 2] [list [list 5 3 4] [list 6 2 1] [list 5 2 3]])
</code>```

Output:

```<code>'((5 2 1) (5 3 4) (5 3 7) (6 1 3) (6 2 1))
'((6 2 1) (5 2 3) (5 3 4))
</code>```

Title: Multiple-Key Sorting

Body:
Given a list of indices and zero or more lists of integers, output the lists of integers, sorted in ascending order, with the key priority from the first input.

Example

Let the keys input be [1, 0, 2], and the lists input be [[5, 3, 4], [6, 2, 1], [5, 2, 1]]. Those lists need to be sorted by their second element, then first element, then third element, in ascending order:

First, we sort by the values at index 1: [[6, 2, 1], [5, 2, 1], [5, 3, 4]]

Next, we break any ties from the first sort using the values at index 0: [[5, 2, 1], [6, 2, 1], [5, 3, 4]]

Finally, we break any remaining ties with the vlues at index 2 (this doesn't actually change anything, because there are no ties remaining).

Details

Sorting is stable: if two elements compare equal with respect to the given sort keys, they must remain in the same relative order in the output. For example, if A and B are equal under the given sort keys, and the input was [..., A, ..., B, ...], A must be placed before B in the output.

A sort key will never reference a non-existant element in one of the input lists.

No sort key will be repeated. Thus, [1, 2, 1] is not a valid list of sort keys.

Any elements not referenced by the sort keys do not factor into the sorting order. Only the initial relative order and the values of the elements referenced by the sort keys determine the output order.

You may choose whether the sort keys are zero-indexed or one-indexed.

There will be no negative values in the sort keys. If you choose to use one-indexing, there will be no zeroes in the sort keys either.

Integer values will not exceed your language's natively-representable range. If your chosen language is natively capable of arbitrary-precision integers (like Python), then any integer value can be present in the input, subject to memory constraints.

Reference Implementation (Python 2)

#!/usr/bin/env python

keys = input()
lists = input()

print sorted(lists, key=lambda l:[l[x] for x in keys])
```
<p>Try it online</p>
<h2>Test Cases</h2>
<p>Format: <code>keys lists -> output</code>. All sort keys are zero-indexed.</p>
```[1, 0, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[5, 2, 1], [6, 2, 1], [5, 3, 4]]
[1, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[6, 2, 1], [5, 2, 1], [5, 3, 4]]
[0, 1] [[1, 2], [2, 1]] -> [[1, 2], [2, 1]]
[1, 0] [[1, 2], [2, 1]] -> [[2, 1], [1, 2]]
[0] [[4], [10, 11, -88], [-2, 7]] -> [[-2, 7], [4], [10, 11, -88]]
[2] [[-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6]] -> [[-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2]]
[2, 1] [[9, 2, -2, -10, -6], [3, -4, -2]] -> [[3, -4, -2], [9, 2, -2, -10, -6]]
[2, 4, 8] [[5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5], [-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3]] -> [[-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3], [5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5]]
[1, 2, 3, 4, 5] [[-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [5, 3, -6, -5, -4, -4, -8, 2], [9, -4, 1, -1, -3, -2], [-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [1, -5, -3, -10, -7, 9, -8, -5, -1], [-9, 4, -1, -1, 2, 4]] -> [[-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -5, -3, -10, -7, 9, -8, -5, -1], [9, -4, 1, -1, -3, -2], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [5, 3, -6, -5, -4, -4, -8, 2], [-9, 4, -1, -1, 2, 4]]
[8, 7, 3, 2, 4, 9, 1] [[8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9]] -> [[10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5]]
```

Body:
Racket 218 bytes

(λ(il ll)(define qsl(λ(l i)(if(null? l)l(let*((h(first l))(t(rest l))(g(λ(ff)(filter(λ(x)(ff(list-ref x i)
(list-ref h i)))t))))(append(qsl(g <)i)(list h)(qsl(g >=)i))))))(for((i(reverse il)))(set! ll(qsl ll i)))ll)

Ungolfed (il=index list; ll=list of lists; qsl= quicksort for list of lists; h=head (first element); t=tail (rest or remaining elements); g=modifiable filter fn):

(define qsl
  (λ(l i)
    (if (null? l)
        l
        (let* ((h (first l))
               (t (rest  l))
               (g (λ(ff) (filter (λ(x) (ff (list-ref x i) (list-ref h i))) t))))
          (append (qsl (g <) i)
                  (list h)
                  (qsl (g >=) i)
                  )))))
(define f
  (λ(il ll)
    (for ((i (reverse il)))
      (set! ll (qsl ll i)))
    ll))

Testing:

(f (list 0 1 2) (list (list 5 3 4) (list 5 3 7) (list 6 2 1) (list 6 1 3) (list 5 2 1)))
(f [list 1 2] [list [list 5 3 4] [list 6 2 1] [list 5 2 3]])

Output:

'((5 2 1) (5 3 4) (5 3 7) (6 1 3) (6 2 1))
'((6 2 1) (5 2 3) (5 3 4))


问:
0.0000000000000000001
Notice the pattern in the below sequence:

```<code>0.1, 0.01, 0.001, 0.0001, 0.00001 and so on, until reaching 0.{one hundred zeros}1
</code>```

Then, continued:

```<code>0.2, 0.02, 0.002, 0.0002, 0.00002 and so on, until reaching 0.{two hundred zeros}2
</code>```

Continued:

```<code>0.3, 0.03, etc, until 0.{three hundred zeros}3
</code>```

Continued:

```<code>0.4, 0.04, etc, until 0.{four hundred zeros}4
</code>```

Sped up a bit:

```<code>0.10, 0.010, etc.  until 0.{one thousand zeros}10
</code>```

Sped up some more:

0.100, 0.0100...

You get the idea.

The input your code will receive is an integer, the number of terms, and the output is that many number of terms of the sequence.

Input and output formats are unrestricted, and separators are not required.

Trailing zeros are necessary.

Standard loopholes apply.

The outputs of some nth terms are given below:

```<code>nth term -> number
-------------------
1        -> 0.1
102      -> 0.2
303      -> 0.3
604      -> 0.4
1005     -> 0.5
1506     -> 0.6
2107     -> 0.7
2808     -> 0.8
3609     -> 0.9
4510     -> 0.10
</code>```

答:
JavaScript (ES6), 69

n=>[...Array(n)].map(_=>(w=l--?z:(l=++x*100,z='0.'),z+=0,w+x),l=x=0)
```
<p>Unnamed function with desired length in input and returning an array of strings.</p>
<p><strong>Test</strong>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=
n=>[...Array(n)].map(_=>(w=l--?z:(l=++x*100,z='0.'),z+=0,w+x),l=x=0)

var tid=0
function exec()
{
    var n=+I.value;
    O.textContent=f(n).map((r,i)=>i+1+' '+r).join`\n`;
}

function update()
{
  clearTimeout(tid);
  tid=setTimeout(exec, 1000);
}

exec()</code>```

<input id=I value=305 type=number oninput='update()'>
```</code>```

Title: 0.0000000000000000001

Body:
JavaScript (ES6), 69

n=>[...Array(n)].map(_=>(w=l--?z:(l=++x*100,z='0.'),z+=0,w+x),l=x=0)

Unnamed function with desired length in input and returning an array of strings.

Test

f=
n=>[...Array(n)].map(_=>(w=l--?z:(l=++x*100,z='0.'),z+=0,w+x),l=x=0)

var tid=0
function exec()
{
    var n=+I.value;
    O.textContent=f(n).map((r,i)=>i+1+' '+r).join`\n`;
}

function update()
{
  clearTimeout(tid);
  tid=setTimeout(exec, 1000);
}

exec()

<input id=I value=305 type=number oninput='update()'><pre id=O></pre>


Title: Some ASCII art for N64's 20th B-Day

Body:
The official release of the Nintendo 64 in North America was on September 29, 1996.[1] I figured that this anniversary deserved an ASCII art challenge. There's one small twist though, you have to output a different ASCII art for each of three different inputs.

If the input is 1, output this ASCII art of an N64 Controller: (source)

```<code>                 | |
             _,.-'-'-.,_
      ______|           |______
   ,-'      |  NINTENDO |      `-.
 ,'   _                          `.
/   _| |_                     (^)   \
|  |_   _|                  (<) (>) |
\    |_|         (S)     (B)  (v)   /
|`.              ___       (A)    ,'|
|  `-.______   ,' _ `.   ______,-'  |
|      |    `. | (_) | ,'    |      |
|      |      \`.___,'/      |      |
|      |      |       |      |      |
|      /      |       |      \      |
\     /       |       |       \     /
 `._,'        \       /        `._,'
               \     /
                `._,'
</code>```

If the input is 2, output this ASCII art of the N64 logo:(source)

```<code>                  .-"-.
               .-"     "-.
              /"-.     .-|
             /    "-.-"  |
            /      /     |
   .-"-.   /      /      |       .-"-.
.-"     "-/      /       |    .-"     "-.
|-.     .-"\    /        |   /"-.     .-|
|  '-.-"    \  /         | /'    "-.-"  |
|     \      \/   .-"-.  /'        |    |
|      \      \.-"     "-.         |    |
|       \      |-.     .-"\        |    |
|        \     |  "-.-"    '\      |    |
|         \    |    |        '\    |    |
|    |\    \   |    |          '\  |    |
|    | \    \  |    |            '\|    |
|    |  \    \ |    |    :\.            |
|    |   \    \|    |    |  \.          |
|    |    \         |    |    \.        |
'-.  |  .-"\        |    |    '.\.    .-'
   "-|-"    \       |    |      "-\.-"
             \      |    |
              \     |    |
               "-.  |  .-'
                  "-|-"
</code>```

Finally, if the input is 3, outout this ASCII art of a console and TV: (source)

```<code>              o
     o       /
      \     /
       \   /
        \ /
   ______________
  |.------------.|
  ||            ||
  ||            ||
  ||            ||
  ||            ||
  ||____________||_
  |OO ....... OO | `-.
  '------_.-._---' _.'
   _____||   ||___/_
  /  _.-|| N ||-._  \      .-._
 / -'_.---------._'- \    ,'___i-i___
/_.-'_  NINTENDO _'-._\  ' /_+  o :::\
|`-i /m\/m\|\|/=,/m\i-'| | || \ O / ||
|  |_\_/\_/___\_/'./|  | | \/  \ /  \/
`-'              '-.`-'  ,      V
                    `---'
</code>```

Rules:

Input may be either as a number or a string/char.

You may have any amount of leading or trailing spaces and trailing or leading newlines. (Output must be aligned correctly though)

Your submission may be either a full program or a function.

No retrieving the ASCII art from the internet.

This is code-golf, so smallest byte count wins.

Body:
PHP, <s>2113</s> 2112 bytes

If nobody else is going to compete I'll just grab the trophy and leave..

<?php function a($n){if($n<2){?>
                 | |
             _,.-'-'-.,_
      ______|           |______
   ,-'      |  NINTENDO |      `-.
 ,'   _                          `.
/   _| |_                     (^)   \
|  |_   _|                  (<) (>) |
\    |_|         (S)     (B)  (v)   /
|`.              ___       (A)    ,'|
|  `-.______   ,' _ `.   ______,-'  |
|      |    `. | (_) | ,'    |      |
|      |      \`.___,'/      |      |
|      |      |       |      |      |
|      /      |       |      \      |
\     /       |       |       \     /
 `._,'        \       /        `._,'
               \     /
                `._,'<?php }else if($n==2){?>
                  .-"-.
               .-"     "-.
              /"-.     .-|
             /    "-.-"  |
            /      /     |
   .-"-.   /      /      |       .-"-.
.-"     "-/      /       |    .-"     "-.
|-.     .-"\    /        |   /"-.     .-|
|  '-.-"    \  /         | /'    "-.-"  |
|     \      \/   .-"-.  /'        |    |
|      \      \.-"     "-.         |    |
|       \      |-.     .-"\        |    |
|        \     |  "-.-"    '\      |    |
|         \    |    |        '\    |    |
|    |\    \   |    |          '\  |    |
|    | \    \  |    |            '\|    |
|    |  \    \ |    |    :\.            |
|    |   \    \|    |    |  \.          |
|    |    \         |    |    \.        |
'-.  |  .-"\        |    |    '.\.    .-'
   "-|-"    \       |    |      "-\.-"
             \      |    |
              \     |    |
               "-.  |  .-'
                  "-|-"<?php }else{?>
              o
     o       /
      \     /
       \   /
        \ /
   ______________
  |.------------.|
  ||            ||
  ||            ||
  ||            ||
  ||            ||
  ||____________||_
  |OO ....... OO | `-.
  '------_.-._---' _.'
   _____||   ||___/_
  /  _.-|| N ||-._  \      .-._
 / -'_.---------._'- \    ,'___i-i___
/_.-'_  NINTENDO _'-._\  ' /_+  o :::\
|`-i /m\/m\|\|/=,/m\i-'| | || \ O / ||
|  |_\_/\_/___\_/'./|  | | \/  \ /  \/
`-'              '-.`-'  ,      V
                    `---' <?php }}?>

Thanks to @KevinCruijssen for a byte!


问:
De-Snakify a String
A regular string looks like this:

```<code>Hello,IAmAStringSnake!
</code>```

And a string snake looks something like this:

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan
</code>```

Your Task

String snakes are dangerous, so you must make a program that takes a string snake as input and outputs it as a regular string.

Specifications

Input can be a multiline string or an array of strings.

Each line of the input will be padded with spaces to form a rectangular grid.

Characters in the snake can only connect to adjacent characters above, below, left or right of them (just like in the game Snake). They cannot go diagonal.

The snake characters will never be adjacent to another part of the snake, only the connected characters.

The first character of the string is the end character with the shortest Manhattan distance from the top-left corner of the input grid (i.e. the minimum number of moves it would take for a snake to go directly from the end character to the top-left corner). Both ends will never have the same distance.

The string can contain any ASCII character between code points 33 and 126 inclusive (no spaces or newlines).

The string will be between 2 and 100 characters long.

Shortest code in bytes wins.

Test Cases

(Input grid, followed by the output string)

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan

Hello,IAmAStringSnake!

----------

Python

Python

----------

P  ngPu  Code
r  i  z  d  G
o  m  z  n  o
gram  lesA  lf

ProgrammingPuzzlesAndCodeGolf

----------

   ~ zyx tsr XWVUTSR
   }|{ wvu q Y     Q
!          p Z `ab P
"#$ 6789:; o [ _ c O
  % 5    < n \]^ d N
('& 432  = m     e M
)     1  > lkjihgf L
*+,-./0  ?         K
         @ABCDEFGHIJ

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

----------

  tSyrep
  r    p
  in Sli
   g    Sile
   Snakes  n
Ser      ylt
a eh   ilS
fe w   t
   emo h
     Sre

SlipperyStringSnakesSilentlySlitherSomewhereSafe
</code>```

答:
Java 7, <s>927</s> <s>924</s> 923 bytes

```<code>import java.util.*;int l,k;char[][]z;Set p=new HashSet();String c(String[]a){int x=0,y=0,n,t,u,v,w=t=u=v=-1;l=a.length;k=a[0].length();z=new char[l][k];for(String s:a){for(char c:s.toCharArray())z[x][y++]=c;}x++;y=0;}for(x=0;x<l;x++)for(y=0;y<k;y++){n=0;if(z[x][y]>32){if(x<1|(x>0&&z[x-1][y]<33))n++;if(y<1|(y>0&&z[x][y-1]<33))n++;if(x>l-2|(x<l-1&&z[x+1][y]<33))n++;if(y>k-2|(y<k-1&&z[x][y+1]<33))n++;}if(n>2&t<0){t=x;u=y;}if(n>2&t>v){v=x;w=y;}}if(v+w>t+u){p(t,u);return n(""+z[t][u],t,u);}p(v,w);return n(""+z[v][w],v,w);}String n(String r,int x,int y){int a,b;if(x>0&&z[a=x-1][b=y]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}if(y>0&&z[a=x][b=y-1]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}if(x<l-1&&z[a=x+1][b=y]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}if(y<k-1&&z[a=x][b=y+1]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}return r;}boolean q(int x,int y){return!p.contains(x+","+y);}void p(int x,int y){p.add(x+","+y);}
</code>```

Ok, that took a while.. In some programming languages it doesn't matter if your array x and y are outside the boundaries of a 2D-array, but with Java it'll throw ArrayIndexOutOfBoundsExceptions, so everything has to be checked..

I first determine the starting point, and then use a recursive method to build the string from there. In addition, I use a list to keep track of the coordinations I've already encountered, so it won't go into a loop back-forth-back-forth (resulting in a StackOverflowException).

This is probably the longest answer I've posted so far, but although some parts can be golfed, I don't think this challenge can be that much shorter in Java. Java just isn't suitable for following a path in a grid.. It was a fun challenge to figure out nonetheless. :)

Ungolfed & test cases:

Try it here.

```<code>import java.util.*;
class M{
  static int l,
             k;
  static char[][] z;
  static Set p = new HashSet();

  static String c(String[] a){
    int x=0,
        y=0,
        n,
        t,
        u,
        v,
        w = t = u = v = -1;
    l = a.length;
    k = a[0].length();
    z = new char[l][k];
    for(String s:a){
      for(char c:s.toCharArray()){
        z[x][y++] = c;
      }
      x++;
      y = 0;
    }
    for(x=0; x<l; x++){
      for(y=0; y<k; y++){
        n = 0;
        if(z[x][y] > 32){ // [x,y] is not a space
          if(x < 1 | (x > 0 && z[x-1][y] < 33)){
            n++;
          }
          if(y < 1 | (y > 0 && z[x][y-1] < 33)){
            n++;
          }
          if(x > l-2 | (x < l-1 && z[x+1][y] < 33)){
            n++;
          }
          if(y > k-2 | (y < k-1 && z[x][y+1] < 33)){
            n++;
          }
        }
        if(n > 2 & t < 0){
          t = x;
          u = y;
        }
        if(n > 2 & t > v){
          v = x;
          w = y;
        }
      }
    }
    if(v+w > t+u){
      p(t, u);
      return n(""+z[t][u], t, u);
    }
    p(v, w);
    return n(""+z[v][w], v, w);
  }

  static String n(String r, int x, int y){
    int a,b;
    if(x > 0 && z[a=x-1][b=y] > 32 & q(a,b)){
      p(a, b);
      return n(r+z[a][b], a, b);
    }
    if(y > 0 && z[a=x][b=y-1] > 32 & q(a,b)){
      p(a, b);
      return n(r+z[a][b], a, b);
    }
    if(x < l-1 && z[a=x+1][b=y] > 32 & q(a,b)){
      p(a, b);
      return n(r+z[a][b], a, b);
    }
    if(y < k-1 && z[a=x][b=y+1] > 32 & q(a, b)){
      p(a, b);
      return n(r+z[a][b], a, b);
    }
    return r;
  }

  static boolean q(int x, int y){
    return !p.contains(x+","+y);
  }

  static void p(int x, int y){
    p.add(x+","+y);
  }

  public static void main(String[] a){
    System.out.println(c(new String[]{ "Hel         ",
      "  l      rin",
      "  o,IAmASt g",
      "           S",
      "       !ekan" }));
    p = new HashSet();
    System.out.println(c(new String[]{ "Python" }));
    p = new HashSet();
    System.out.println(c(new String[]{ "P  ngPu  Code ",
      "r  i  z  d  G",
      "o  m  z  n  o",
      "gram  lesA  lf" }));
    p = new HashSet();
    System.out.println(c(new String[]{ "   ~ zyx tsr XWVUTSR",
      "   }|{ wvu q Y     Q",
      "!          p Z `ab P",
      "\"#$ 6789:; o [ _ c O",
      "  % 5    < n \\]^ d N",
      "('& 432  = m     e M",
      ")     1  > lkjihgf L",
      "*+,-./0  ?         K",
      "         @ABCDEFGHIJ" }));
    p = new HashSet();
    System.out.println(c(new String[]{ "  tSyrep    ",
      "  r    p   ",
      "  in Sli   ",
      "   g    Sile",
      "   Snakes  n",
      "Ser      ylt",
      "a eh   ilS ",
      "fe w   t   ",
      "   emo h   ",
      "     Sre    " }));
  }
}
</code>```

Output:

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

Title: De-Snakify a String

Body:
Java 7, <s>927</s> <s>924</s> 923 bytes

import java.util.*;int l,k;char[][]z;Set p=new HashSet();String c(String[]a){int x=0,y=0,n,t,u,v,w=t=u=v=-1;l=a.length;k=a[0].length();z=new char[l][k];for(String s:a){for(char c:s.toCharArray())z[x][y++]=c;}x++;y=0;}for(x=0;x<l;x++)for(y=0;y<k;y++){n=0;if(z[x][y]>32){if(x<1|(x>0&&z[x-1][y]<33))n++;if(y<1|(y>0&&z[x][y-1]<33))n++;if(x>l-2|(x<l-1&&z[x+1][y]<33))n++;if(y>k-2|(y<k-1&&z[x][y+1]<33))n++;}if(n>2&t<0){t=x;u=y;}if(n>2&t>v){v=x;w=y;}}if(v+w>t+u){p(t,u);return n(""+z[t][u],t,u);}p(v,w);return n(""+z[v][w],v,w);}String n(String r,int x,int y){int a,b;if(x>0&&z[a=x-1][b=y]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}if(y>0&&z[a=x][b=y-1]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}if(x<l-1&&z[a=x+1][b=y]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}if(y<k-1&&z[a=x][b=y+1]>32&q(a,b)){p(a,b);return n(r+z[a][b],a,b);}return r;}boolean q(int x,int y){return!p.contains(x+","+y);}void p(int x,int y){p.add(x+","+y);}

Ok, that took a while.. In some programming languages it doesn't matter if your array x and y are outside the boundaries of a 2D-array, but with Java it'll throw ArrayIndexOutOfBoundsExceptions, so everything has to be checked..

I first determine the starting point, and then use a recursive method to build the string from there. In addition, I use a list to keep track of the coordinations I've already encountered, so it won't go into a loop back-forth-back-forth (resulting in a StackOverflowException).

This is probably the longest answer I've posted so far, but although some parts can be golfed, I don't think this challenge can be that much shorter in Java. Java just isn't suitable for following a path in a grid.. It was a fun challenge to figure out nonetheless. :)

Ungolfed & test cases:

Try it here.

import java.util.*;
class M{
  static int l,
             k;
  static char[][] z;
  static Set p = new HashSet();

  static String c(String[] a){
    int x=0,
        y=0,
        n,
        t,
        u,
        v,
        w = t = u = v = -1;
    l = a.length;
    k = a[0].length();
    z = new char[l][k];
    for(String s:a){
      for(char c:s.toCharArray()){
        z[x][y++] = c;
      }
      x++;
      y = 0;
    }
    for(x=0; x<l; x++){
      for(y=0; y<k; y++){
        n = 0;
        if(z[x][y] > 32){ // [x,y] is not a space
          if(x < 1 | (x > 0 && z[x-1][y] < 33)){
            n++;
          }
          if(y < 1 | (y > 0 && z[x][y-1] < 33)){
            n++;
          }
          if(x > l-2 | (x < l-1 && z[x+1][y] < 33)){
            n++;
          }
          if(y > k-2 | (y < k-1 && z[x][y+1] < 33)){
            n++;
          }
        }
        if(n > 2 & t < 0){
          t = x;
          u = y;
        }
        if(n > 2 & t > v){
          v = x;
          w = y;
        }
      }
    }
    if(v+w > t+u){
      p(t, u);
      return n(""+z[t][u], t, u);
    }
    p(v, w);
    return n(""+z[v][w], v, w);
  }

  static String n(String r, int x, int y){
    int a,b;
    if(x > 0 && z[a=x-1][b=y] > 32 & q(a,b)){
      p(a, b);
      return n(r+z[a][b], a, b);
    }
    if(y > 0 && z[a=x][b=y-1] > 32 & q(a,b)){
      p(a, b);
      return n(r+z[a][b], a, b);
    }
    if(x < l-1 && z[a=x+1][b=y] > 32 & q(a,b)){
      p(a, b);
      return n(r+z[a][b], a, b);
    }
    if(y < k-1 && z[a=x][b=y+1] > 32 & q(a, b)){
      p(a, b);
      return n(r+z[a][b], a, b);
    }
    return r;
  }

  static boolean q(int x, int y){
    return !p.contains(x+","+y);
  }

  static void p(int x, int y){
    p.add(x+","+y);
  }

  public static void main(String[] a){
    System.out.println(c(new String[]{ "Hel         ",
      "  l      rin",
      "  o,IAmASt g",
      "           S",
      "       !ekan" }));
    p = new HashSet();
    System.out.println(c(new String[]{ "Python" }));
    p = new HashSet();
    System.out.println(c(new String[]{ "P  ngPu  Code ",
      "r  i  z  d  G",
      "o  m  z  n  o",
      "gram  lesA  lf" }));
    p = new HashSet();
    System.out.println(c(new String[]{ "   ~ zyx tsr XWVUTSR",
      "   }|{ wvu q Y     Q",
      "!          p Z `ab P",
      "\"#$ 6789:; o [ _ c O",
      "  % 5    < n \\]^ d N",
      "('& 432  = m     e M",
      ")     1  > lkjihgf L",
      "*+,-./0  ?         K",
      "         @ABCDEFGHIJ" }));
    p = new HashSet();
    System.out.println(c(new String[]{ "  tSyrep    ",
      "  r    p   ",
      "  in Sli   ",
      "   g    Sile",
      "   Snakes  n",
      "Ser      ylt",
      "a eh   ilS ",
      "fe w   t   ",
      "   emo h   ",
      "     Sre    " }));
  }
}

Output:

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


Title: Some ASCII art for N64's 20th B-Day

Body:
Javascript ES6, 1175 bytes

Using a simple Run Length Encoding to encode just the spaces.

let F=

  z=>[(f=d=>d.replace(/\d+/g,e=>' '.repeat(e)))(`17|1|
13_,.-'-'-.,_
6______|11|______
3,-'6|2NINTENDO1|6\`-.
1,'3_26\`.
/3_|1|_21(^)3\\
|2|_3_|18(<)1(>)1|
\\4|_|9(S)5(B)2(v)3/
|\`.14___7(A)4,'|
|2\`-.______3,'1_1\`.3______,-'2|
|6|4\`.1|1(_)1|1,'4|6|
|6|6\\\`.___,'/6|6|
|6|6|7|6|6|
|6/6|7|6\\6|
\\5/7|7|7\\5/
1\`._,'8\\7/8\`._,'
15\\5/
16\`._,'`),f(`18.-"-.
15.-"5"-.
14/"-.5.-|
13/4"-.-"2|
12/6/5|
3.-"-.3/6/6|7.-"-.
.-"5"-/6/7|4.-"5"-.
|-.5.-"\\4/8|3/"-.5.-|
|2'-.-"4\\2/9|1/'4"-.-"2|
|5\\6\\/3.-"-.2/'8|4|
|6\\6\\.-"5"-.9|4|
|7\\6|-.5.-"\\8|4|
|8\\5|2"-.-"4'\\6|4|
|9\\4|4|8'\\4|4|
|4|\\4\\3|4|10'\\2|4|
|4|1\\4\\2|4|12'\\|4|
|4|2\\4\\1|4|4:\\.12|
|4|3\\4\\|4|4|2\\.10|
|4|4\\9|4|4\\.8|
'-.2|2.-"\\8|4|4'.\\.4.-'
3"-|-"4\\7|4|6"-\\.-"
13\\6|4|
14\\5|4|
15"-.2|2.-'
18"-|-"`),f(`14o
5o7/
6\\5/
7\\3/
8\\1/
3______________
2|.------------.|
2||12||
2||12||
2||12||
2||12||
2||____________||_
2|OO1.......1OO1|1\`-.
2'------_.-._---'1_.'2
3_____||3||___/_
2/2_.-||1N1||-._2\\6.-._
1/1-'_.---------._'-1\\4,'___i-i___
/_.-'_2NINTENDO1_'-._\\2'1/_+2o1:::\\
|\`-i1/m\\/m\\|\\|/=,/m\\i-'|1|1||1\\1O1/1||
|2|_\\_/\\_/___\\_/'./|2|1|1\\/2\\1/2\\/
\`-'14'-.\`-'2,6V
20\`---'`)][z-1]

G=_=>h.innerHTML = F(a.value)

h.innerHTML = F(1)

<input id=a onchange="G()" type="number" value="1"></input>
<pre id=h>


答:
Racket, 1059 bytes

(require file/gunzip net/base64)(display((λ(o)(gunzip-through-ports(open-input-bytes(base64-decode(list-ref'(#"H4sICMov7lcCAzEAdZExDsMgDEV3TuENkAhcoKrUqh2ypEM7osIpOvnwtTEkgaaOFIvvZ8efAAyBgKoTkvOTpse7VAupBO6bROK6m3QbBMu8vO7L7QGVzZNX4Lie4G9krwITtMgxZd6W3lEhCNFt0piTBXO25CXKfhtjnlbylbL58CEozL4fQG4afym808hfJAvitUjkozSKVKwXqvpnM5RNokXEd7uJniI3mcc6HTp1pBCOjisVDqnYqLiHRqpiQdHKyWno1K1Lqmq47bX351cy/AXpeU7EYwIAAA=="#"H4sICNkv7lcCAzIAbdIxDgQhCAXQfk5BbKzUfs/CUTj8qiACMo2J/xl/cADi11tp/Xs39/pGY24JIR8NObCO+mjYZUf70pgAuUq3g1fMbEPSSgUt3NIVnhu1yVE0cMpRXX/ugpziuJ3ZaY8jlZpikMtDY+1ECiUtNvtjLpmSnaNYKwkP9ZKtk3BolMt6eeiVP+z2wJVCyZa11kjAMECe75V1DZCyAe6SnW1v9dvvQfruEEdV2no3/z/7OUOSpRE/POm9Tzpr/AEE2h7HhgMAAA=="#"H4sICOIv7lcCAzMApVG7DsIwDNzzFd48UNt7JTYYWNoFMUVy1gyIH/DHc0l4tBIb1yjxXf1MiLZ4pHG8qA1Kecc6/RCwbvsOUEJlA40mxbZY/Clt64E1bV1JBwhmUBGFzKMFV1HHyeTKRJ+me/KezloSg6wCcYGIiPf41MITfgv7dzR1luEwMTJUqW16gwcjcrks1/NyWgle6nBjMj+0C57nOacoUsnuGSty2HGCUYUDnaN+phXVMCz6C89uWEiOndWahi9bfwBslgom2wE1uzYNekv0A6XfyBPSqZrcBwIAAA==")(-(read)1))))o)(get-output-string o))(open-output-string)))
```

<p>Just gzipped data encoded as base64.</p>

<h2>Ungolfed</h2>

<pre class="lang-rkt prettyprint-override"><code>(require file/gunzip net/base64)
(display ((λ (o)
            (gunzip-through-ports
             (open-input-bytes
              (base64-decode
               (list-ref
                '(#"H4sICMov7lcCAzEAdZExDsMgDEV3TuENkAhcoKrUqh2ypEM7osIpOvnwtTEkgaaOFIvvZ8efAAyBgKoTkvOTpse7VAupBO6bROK6m3QbBMu8vO7L7QGVzZNX4Lie4G9krwITtMgxZd6W3lEhCNFt0piTBXO25CXKfhtjnlbylbL58CEozL4fQG4afym808hfJAvitUjkozSKVKwXqvpnM5RNokXEd7uJniI3mcc6HTp1pBCOjisVDqnYqLiHRqpiQdHKyWno1K1Lqmq47bX351cy/AXpeU7EYwIAAA=="
                  #"H4sICNkv7lcCAzIAbdIxDgQhCAXQfk5BbKzUfs/CUTj8qiACMo2J/xl/cADi11tp/Xs39/pGY24JIR8NObCO+mjYZUf70pgAuUq3g1fMbEPSSgUt3NIVnhu1yVE0cMpRXX/ugpziuJ3ZaY8jlZpikMtDY+1ECiUtNvtjLpmSnaNYKwkP9ZKtk3BolMt6eeiVP+z2wJVCyZa11kjAMECe75V1DZCyAe6SnW1v9dvvQfruEEdV2no3/z/7OUOSpRE/POm9Tzpr/AEE2h7HhgMAAA=="
                  #"H4sICOIv7lcCAzMApVG7DsIwDNzzFd48UNt7JTYYWNoFMUVy1gyIH/DHc0l4tBIb1yjxXf1MiLZ4pHG8qA1Kecc6/RCwbvsOUEJlA40mxbZY/Clt64E1bV1JBwhmUBGFzKMFV1HHyeTKRJ+me/KezloSg6wCcYGIiPf41MITfgv7dzR1luEwMTJUqW16gwcjcrks1/NyWgle6nBjMj+0C57nOacoUsnuGSty2HGCUYUDnaN+phXVMCz6C89uWEiOndWahi9bfwBslgom2wE1uzYNekv0A6XfyBPSqZrcBwIAAA==")
                (- (read) 1))))
             o)
            (get-output-string o))
          (open-output-string)))
</code>```

Title: Some ASCII art for N64's 20th B-Day

Body:
Racket, 1059 bytes

(require file/gunzip net/base64)(display((λ(o)(gunzip-through-ports(open-input-bytes(base64-decode(list-ref'(#"H4sICMov7lcCAzEAdZExDsMgDEV3TuENkAhcoKrUqh2ypEM7osIpOvnwtTEkgaaOFIvvZ8efAAyBgKoTkvOTpse7VAupBO6bROK6m3QbBMu8vO7L7QGVzZNX4Lie4G9krwITtMgxZd6W3lEhCNFt0piTBXO25CXKfhtjnlbylbL58CEozL4fQG4afym808hfJAvitUjkozSKVKwXqvpnM5RNokXEd7uJniI3mcc6HTp1pBCOjisVDqnYqLiHRqpiQdHKyWno1K1Lqmq47bX351cy/AXpeU7EYwIAAA=="#"H4sICNkv7lcCAzIAbdIxDgQhCAXQfk5BbKzUfs/CUTj8qiACMo2J/xl/cADi11tp/Xs39/pGY24JIR8NObCO+mjYZUf70pgAuUq3g1fMbEPSSgUt3NIVnhu1yVE0cMpRXX/ugpziuJ3ZaY8jlZpikMtDY+1ECiUtNvtjLpmSnaNYKwkP9ZKtk3BolMt6eeiVP+z2wJVCyZa11kjAMECe75V1DZCyAe6SnW1v9dvvQfruEEdV2no3/z/7OUOSpRE/POm9Tzpr/AEE2h7HhgMAAA=="#"H4sICOIv7lcCAzMApVG7DsIwDNzzFd48UNt7JTYYWNoFMUVy1gyIH/DHc0l4tBIb1yjxXf1MiLZ4pHG8qA1Kecc6/RCwbvsOUEJlA40mxbZY/Clt64E1bV1JBwhmUBGFzKMFV1HHyeTKRJ+me/KezloSg6wCcYGIiPf41MITfgv7dzR1luEwMTJUqW16gwcjcrks1/NyWgle6nBjMj+0C57nOacoUsnuGSty2HGCUYUDnaN+phXVMCz6C89uWEiOndWahi9bfwBslgom2wE1uzYNekv0A6XfyBPSqZrcBwIAAA==")(-(read)1))))o)(get-output-string o))(open-output-string)))

Just gzipped data encoded as base64.

Ungolfed

(require file/gunzip net/base64)
(display ((λ (o)
            (gunzip-through-ports
             (open-input-bytes
              (base64-decode
               (list-ref
                '(#"H4sICMov7lcCAzEAdZExDsMgDEV3TuENkAhcoKrUqh2ypEM7osIpOvnwtTEkgaaOFIvvZ8efAAyBgKoTkvOTpse7VAupBO6bROK6m3QbBMu8vO7L7QGVzZNX4Lie4G9krwITtMgxZd6W3lEhCNFt0piTBXO25CXKfhtjnlbylbL58CEozL4fQG4afym808hfJAvitUjkozSKVKwXqvpnM5RNokXEd7uJniI3mcc6HTp1pBCOjisVDqnYqLiHRqpiQdHKyWno1K1Lqmq47bX351cy/AXpeU7EYwIAAA=="
                  #"H4sICNkv7lcCAzIAbdIxDgQhCAXQfk5BbKzUfs/CUTj8qiACMo2J/xl/cADi11tp/Xs39/pGY24JIR8NObCO+mjYZUf70pgAuUq3g1fMbEPSSgUt3NIVnhu1yVE0cMpRXX/ugpziuJ3ZaY8jlZpikMtDY+1ECiUtNvtjLpmSnaNYKwkP9ZKtk3BolMt6eeiVP+z2wJVCyZa11kjAMECe75V1DZCyAe6SnW1v9dvvQfruEEdV2no3/z/7OUOSpRE/POm9Tzpr/AEE2h7HhgMAAA=="
                  #"H4sICOIv7lcCAzMApVG7DsIwDNzzFd48UNt7JTYYWNoFMUVy1gyIH/DHc0l4tBIb1yjxXf1MiLZ4pHG8qA1Kecc6/RCwbvsOUEJlA40mxbZY/Clt64E1bV1JBwhmUBGFzKMFV1HHyeTKRJ+me/KezloSg6wCcYGIiPf41MITfgv7dzR1luEwMTJUqW16gwcjcrks1/NyWgle6nBjMj+0C57nOacoUsnuGSty2HGCUYUDnaN+phXVMCz6C89uWEiOndWahi9bfwBslgom2wE1uzYNekv0A6XfyBPSqZrcBwIAAA==")
                (- (read) 1))))
             o)
            (get-output-string o))
          (open-output-string)))


问:
Compute the Mertens function
Given a positive integer n, compute the value of the Mertens function \$M(n)\$ where:

$$M(n) = \Sigma_{k=1}^{n}\mu(k)$$

and \$\mu(k)\$ is the Möbius function where \$μ(k) = 1\$ if \$k\$ has an even number of distinct prime factors, \$-1\$ if \$k\$ has an odd number of distinct prime factors, and \$0\$ if the prime factors are not distinct.

This is code-golf so create the shortest code for a function or program that computes the Mertens function for an input integer n > 0.

This is the OEIS sequence A002321.

Test Cases

```<code>n M(n)
1 1
2 0
3 -1
4 -1
5 -2
6 -1
7 -2
8 -2
9 -2
10 -1
117 -5
5525 5
7044 -25
8888 4
10000 -23
</code>```

答:
Actually, <s>18</s> <s>17</s> 16 bytes

Golfing suggestions welcome. Try it online!

```<code>R`;y;l0~ⁿ)π=*`MΣ
</code>```

Ungolfing

```<code>         Implicit input n.
R        Push the range [1..n].
`...`M   Map the following function over the range. Variable k.
  ;        Duplicate k.
  y        Push the distinct prime factors of k. Call it dpf.
  ;        Duplicate dpf.
  l        Push len(dpf).
  0~       Push -1.
  ⁿ        Push (-1)**len(dpf).
  )        Move (-1)**len(dpf) to BOS. Stack: dpf, k, (-1)**len(dpf)
  π        Push product(dpf).
  =        Check if this product is equal to k.
            If so, then k is squarefree.
  *        Multiply (k is squarefree) * (-1)**(length).
            If k is NOT squarefree, then 0.
            Else if length is odd, then -1.
            Else if length is even, then 1.
           This function is equivalent to the Möbius function.
Σ        Sum the results of the map.
         Implicit return.
</code>```

ContentLicense: CC BY-SA 4.0

Title: Compute the Mertens function

Body:
Actually, <s>18</s> <s>17</s> 16 bytes

Golfing suggestions welcome. Try it online!

R`;y;l0~ⁿ)π=*`MΣ

Ungolfing

         Implicit input n.
R        Push the range [1..n].
`...`M   Map the following function over the range. Variable k.
  ;        Duplicate k.
  y        Push the distinct prime factors of k. Call it dpf.
  ;        Duplicate dpf.
  l        Push len(dpf).
  0~       Push -1.
  ⁿ        Push (-1)**len(dpf).
  )        Move (-1)**len(dpf) to BOS. Stack: dpf, k, (-1)**len(dpf)
  π        Push product(dpf).
  =        Check if this product is equal to k.
            If so, then k is squarefree.
  *        Multiply (k is squarefree) * (-1)**(length).
            If k is NOT squarefree, then 0.
            Else if length is odd, then -1.
            Else if length is even, then 1.
           This function is equivalent to the Möbius function.
Σ        Sum the results of the map.
         Implicit return.


问:
Yes, of course I'm an adult!
I think we've all done this as a kid: some websites require a minimum age of 18, so we just subtract a few years from the year of birth and voilà, we 'are' 18+.

In addition, for most rides at amusement parks the minimum height to enter is 1.40 meters (here in The Netherlands it as at least). Of course this can be cheated less easily than age, but you could wear shoes with thick heels, put your hair up, wear a hat, stand on your toes, etc.

Input:

Your program/function accepts a positive integer or decimal.

Output:

Is the input an integer >= 18? Simply print the input.

Is the input an integer 0-17? Print 18.

Is the input a decimal >= 1.4? Simply print the input.

Is the input a decimal 0.0-1.4? Print 1.4.

Challenge rules:

Assume the input will always be in the range of 0-122 (oldest woman ever was 122) or 0.0-2.72 (tallest man ever was 2.72).

You are allowed to take the input as a String, object, or anything else you prefer.

The decimal inputs will never have more than three decimal places after the decimal point.

2 or 2. both aren't valid outputs for 2.0. You are free to output 2.00 or 2.000 instead of 2.0 however.

Just like the input the output will never have more than three decimal places after the point.

General rules:

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

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

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

Default Loopholes are forbidden.

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

Also, please add an explanation if necessary.

Test cases:

```<code>0      ->  18
1      ->  18
2      ->  18
12     ->  18
18     ->  18
43     ->  43
115    ->  115
122    ->  122

0.0    ->  1.4
1.04   ->  1.4
1.225  ->  1.4
1.399  ->  1.4
1.4    ->  1.4
1.74   ->  1.74
2.0    ->  2.0
2.72   ->  2.72
</code>```

答:
C#, 71 bytes

```<code>object A(object i){return i is int?(int)i>18?i:18:(double)i>1.4?i:1.4;}
</code>```

try it here

Title: Yes, of course I'm an adult!

Body:
C#, 71 bytes

object A(object i){return i is int?(int)i>18?i:18:(double)i>1.4?i:1.4;}

try it here


答:
Ruby - 34 bytes

Very straight-forward. Could possibly save 2 bytes by transforming that ternary.

```<code>->(x){x%1>0?x<1.4?1.4:x:x<18?18:x}
</code>```

Title: Yes, of course I'm an adult!

Body:
I think we've all done this as a kid: some websites require a minimum age of 18, so we just subtract a few years from the year of birth and voilà, we 'are' 18+.

In addition, for most rides at amusement parks the minimum height to enter is 1.40 meters (here in The Netherlands it as at least). Of course this can be cheated less easily than age, but you could wear shoes with thick heels, put your hair up, wear a hat, stand on your toes, etc.

Input:

Your program/function accepts a positive integer or decimal.

Output:

Is the input an integer >= 18? Simply print the input.

Is the input an integer 0-17? Print 18.

Is the input a decimal >= 1.4? Simply print the input.

Is the input a decimal 0.0-1.4? Print 1.4.

Challenge rules:

Assume the input will always be in the range of 0-122 (oldest woman ever was 122) or 0.0-2.72 (tallest man ever was 2.72).

You are allowed to take the input as a String, object, or anything else you prefer.

The decimal inputs will never have more than three decimal places after the decimal point.

2 or 2. both aren't valid outputs for 2.0. You are free to output 2.00 or 2.000 instead of 2.0 however.

Just like the input the output will never have more than three decimal places after the point.

General rules:

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

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

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

Default Loopholes are forbidden.

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

Also, please add an explanation if necessary.

Test cases:

```<code>0      ->  18
1      ->  18
2      ->  18
12     ->  18
18     ->  18
43     ->  43
115    ->  115
122    ->  122

0.0    ->  1.4
1.04   ->  1.4
1.225  ->  1.4
1.399  ->  1.4
1.4    ->  1.4
1.74   ->  1.74
2.0    ->  2.0
2.72   ->  2.72
</code>```

Body:
Ruby - 34 bytes

Very straight-forward. Could possibly save 2 bytes by transforming that ternary.

->(x){x%1>0?x<1.4?1.4:x:x<18?18:x}


答:
TI-Basic, 31 bytes

```<code>Prompt O,Str1
Disp max(18,O
Str1
If 1.4>expr(Ans
"1.4
Ans
</code>```

Pretty self-explanatory. Only thing I would note is that in TI-Basic, whatever the last line evaluates to is implicitly displayed. If nothing is evaluated on the last line it will print Done.

Title: Yes, of course I'm an adult!

Body:
TI-Basic, 31 bytes

Prompt O,Str1
Disp max(18,O
Str1
If 1.4>expr(Ans
"1.4
Ans

Pretty self-explanatory. Only thing I would note is that in TI-Basic, whatever the last line evaluates to is implicitly displayed. If nothing is evaluated on the last line it will print Done.


答:
GameMaker Language, 74 bytes

```<code>a=argument1;if real(a)<1.4a="1.4"show_message(string(max(argument0,18))+a)
</code>```

Title: Yes, of course I'm an adult!

Body:
GameMaker Language, 74 bytes

a=argument1;if real(a)<1.4a="1.4"show_message(string(max(argument0,18))+a)


答:
SQL, 105 bytes

```<code>IF @v like'%.%'select MAX(p)from(values(@v),(1.400))as X(p)ELSE select MAX(p)from(values(@v),(18))as X(p)
</code>```

tested on MS SQL Server 2008 R2

usage:

```<code>DECLARE @v as varchar(255) = '1.405'
IF @v like'%.%'select MAX(p)from(values(@v),(1.400))as X(p)ELSE select MAX(p)from(values(@v),(18))as X(p)
</code>```

Title: Yes, of course I'm an adult!

Body:
SQL, 105 bytes

IF @v like'%.%'select MAX(p)from(values(@v),(1.400))as X(p)ELSE select MAX(p)from(values(@v),(18))as X(p)

tested on MS SQL Server 2008 R2

usage:

DECLARE @v as varchar(255) = '1.405'
IF @v like'%.%'select MAX(p)from(values(@v),(1.400))as X(p)ELSE select MAX(p)from(values(@v),(18))as X(p)


答:
Emacs Lisp, 37 bytes

```<code>(lambda(x)(max(if(floatp x)1.4 18)x))
</code>```

Guesses from the "datatype" whether the integer or float version should be used. (floatp returns t for 1.0, but not for 1.) The parameter is a number as integer or float, i.e. it should satisfy numberp.

Title: Yes, of course I'm an adult!

Body:
Emacs Lisp, 37 bytes

(lambda(x)(max(if(floatp x)1.4 18)x))

Guesses from the "datatype" whether the integer or float version should be used. (floatp returns t for 1.0, but not for 1.) The parameter is a number as integer or float, i.e. it should satisfy numberp.


答:
PHP, <s>212</s> 170 bytes

```<code>function m(&$i,$k){foreach($i as$a=>$y)for($b=-1;++$b<$a;){for($p=0;$p<count($k)&!$r=$i[$b][$x=$k[$p++]]-$i[$b+1][$x];);if($r>0){$s=$i[$b+1];$i[$b+1]=$i[$b];$i[$b]=$s;}}}
</code>```

PHP has no stable sort built in anymore; picking an older version there is no way to do a recursive callback with the required specification. But nevermind: using the recursive callback iterator would cost tons; so I didn´t even check if that could do it.

The inner loop could be replaced with another foreach; that would save some bytes on the swapping. But without a check for $b<$a (or $b<count($i)), that will result in an infinite loop. And with that check, The foreach costs as much as the swapping wins.

I first did the comparison recursively; but iteration saves tons of bytes:

breakdown

```<code>// bubble sort
function m(&$i,$k)
{
    foreach($i as$a=>$y)
        for($b=-1;++$b<$a;)
        {
            // comparison:
            for($p=0;$p<count($k)                       // loop through keys
                &
                !$r=$i[$b][$x=$k[$p++]]-$i[$b+1][$x]    // while element equals its successor
            ;);
            // if element is larger than its successor, swap them
            if($r>0)
            {
                $s=$i[$b+1];$i[$b+1]=$i[$b];$i[$b]=$s;
            }
        }
}
</code>```

Title: Multiple-Key Sorting

Body:
PHP, <s>212</s> 170 bytes

function m(&$i,$k){foreach($i as$a=>$y)for($b=-1;++$b<$a;){for($p=0;$p<count($k)&!$r=$i[$b][$x=$k[$p++]]-$i[$b+1][$x];);if($r>0){$s=$i[$b+1];$i[$b+1]=$i[$b];$i[$b]=$s;}}}

PHP has no stable sort built in anymore; picking an older version there is no way to do a recursive callback with the required specification. But nevermind: using the recursive callback iterator would cost tons; so I didn´t even check if that could do it.

The inner loop could be replaced with another foreach; that would save some bytes on the swapping. But without a check for $b<$a (or $b<count($i)), that will result in an infinite loop. And with that check, The foreach costs as much as the swapping wins.

I first did the comparison recursively; but iteration saves tons of bytes:

breakdown

// bubble sort
function m(&$i,$k)
{
    foreach($i as$a=>$y)
        for($b=-1;++$b<$a;)
        {
            // comparison:
            for($p=0;$p<count($k)                       // loop through keys
                &
                !$r=$i[$b][$x=$k[$p++]]-$i[$b+1][$x]    // while element equals its successor
            ;);
            // if element is larger than its successor, swap them
            if($r>0)
            {
                $s=$i[$b+1];$i[$b+1]=$i[$b];$i[$b]=$s;
            }
        }
}


问:
Interpret loose ranges

Interpret loose ranges

ListSharp is an interpreted programming language that has many features, one of those features is a 1 index based range creator that works like this:

You define a range as (INT) TO (INT) or just (INT) where both or the single int can go from min to max int32 value

Then you can use those ranges to extract elements of an array without fearing to overstep it's boundaries

therefore:

1 TO 5 generates: {1,2,3,4,5}

3 generates: {3}

Ranges can be added up using the AND operator

1 TO 5 AND 3 TO 6 generates: {1,2,3,4,5,3,4,5,6}

remember this works with negative numbers as well

3 TO -3 generates: {3,2,1,0,-1,-2,-3}

The challenge is the following:

Input

A character array and the previously defined range clause as a string

Output

The elements at the 1 index based locations of the range (non existing/negative indexes translate to an empty character)

How to win

As a code-golf challenge you are supposed to create the program with the shortest byte count to win

It has been pointed out empty characters do not exist, therefore you should be ignoring them (I only showed them here to make it easier to understand yet it confused people)

Test cases:

```<code>input array is:
{'H','e','l','l','o',' ','W','o','r','l','d'}

range clause:
"1 TO 3" => "Hel"
"5" => "o"
"-10 TO 10" => "Hello Worl"
"0 AND 2 AND 4" => "el"
"8 TO 3" => "oW oll"
"-300 AND 300" => ""
"1 TO 3 AND 3 TO 1" => "HelleH"
"-20 TO 0 AND 1 AND 4" => "Hl"
</code>```

答:
C#, 342 bytes

```<code>a=>r=>{var s=r.Replace(" AND","").Replace(" TO ","|").Split();int b=a.Length,i=0,n,m,j,o;var c=new List<char>();for(;i<s.Length;){var d=s[i++].Split('|');if(d.Length<2)c.Add(b<(n=int.Parse(d[0]))||n<1?' ':a[n-1]);else{o=(m=int.Parse(d[0]))<(n=int.Parse(d[1]))?1:-1;for(j=m;o>0?j<=n:j>=n;j+=o)c.Add(b<j||j<1?' ':a[j-1]);}}return c.ToArray();};
</code>```

Ungolfed method:

```<code>static char[] f(char[] a, string r)
{
    var s=r.Replace(" AND","").Replace(" TO ","|").Split();
    int b=a.Length,i=0,n,m,j,o;
    var c=new List<char>();
    for(;i<s.Length;)
    {
        var d=s[i++].Split('|');
        if(d.Length<2)
            c.Add(b<(n=int.Parse(d[0]))||n<1?' ':a[n-1]);
        else
        {
            o=(m=int.Parse(d[0]))<(n=int.Parse(d[1]))?1:-1;
            for(j=m;o>0?j<=n:j>=n;j+=o)
                c.Add(b<j||j<1?' ':a[j-1]);
        }
    }

    return c.ToArray();
}
</code>```

Full program with test cases:

```<code>using System;
using System.Collections.Generic;

namespace InterpretLooseRanges
{
    class Program
    {
        static void PrintCharArray(char[] a)
        {
            for (int i=0; i<a.Length; i++)
                Console.Write(a[i]);
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            Func<char[],Func<string,char[]>>f= a=>r=>{var s=r.Replace(" AND","").Replace(" TO ","|").Split();int b=a.Length,i=0,n,m,j,o;var c=new List<char>();for(;i<s.Length;){var d=s[i++].Split('|');if(d.Length<2)c.Add(b<(n=int.Parse(d[0]))||n<1?' ':a[n-1]);else{o=(m=int.Parse(d[0]))<(n=int.Parse(d[1]))?1:-1;for(j=m;o>0?j<=n:j>=n;j+=o)c.Add(b<j||j<1?' ':a[j-1]);}}return c.ToArray();};

            char[] ar = {'H','e','l','l','o',' ','W','o','r','l','d'};

            PrintCharArray(f(ar)("1 TO 3"));
            PrintCharArray(f(ar)("5"));
            PrintCharArray(f(ar)("-10 TO 10"));
            PrintCharArray(f(ar)("0 AND 2 AND 4"));
            PrintCharArray(f(ar)("8 TO 3"));
            PrintCharArray(f(ar)("-300 AND 300"));
        }
    }
}
</code>```

A naive solution, using a char list, which uses ' ' as an empty character and gets the job done. Hoping to improve soon.

Title: Interpret loose ranges

Body:
C#, 342 bytes

a=>r=>{var s=r.Replace(" AND","").Replace(" TO ","|").Split();int b=a.Length,i=0,n,m,j,o;var c=new List<char>();for(;i<s.Length;){var d=s[i++].Split('|');if(d.Length<2)c.Add(b<(n=int.Parse(d[0]))||n<1?' ':a[n-1]);else{o=(m=int.Parse(d[0]))<(n=int.Parse(d[1]))?1:-1;for(j=m;o>0?j<=n:j>=n;j+=o)c.Add(b<j||j<1?' ':a[j-1]);}}return c.ToArray();};

Ungolfed method:

static char[] f(char[] a, string r)
{
    var s=r.Replace(" AND","").Replace(" TO ","|").Split();
    int b=a.Length,i=0,n,m,j,o;
    var c=new List<char>();
    for(;i<s.Length;)
    {
        var d=s[i++].Split('|');
        if(d.Length<2)
            c.Add(b<(n=int.Parse(d[0]))||n<1?' ':a[n-1]);
        else
        {
            o=(m=int.Parse(d[0]))<(n=int.Parse(d[1]))?1:-1;
            for(j=m;o>0?j<=n:j>=n;j+=o)
                c.Add(b<j||j<1?' ':a[j-1]);
        }
    }

    return c.ToArray();
}

Full program with test cases:

using System;
using System.Collections.Generic;

namespace InterpretLooseRanges
{
    class Program
    {
        static void PrintCharArray(char[] a)
        {
            for (int i=0; i<a.Length; i++)
                Console.Write(a[i]);
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            Func<char[],Func<string,char[]>>f= a=>r=>{var s=r.Replace(" AND","").Replace(" TO ","|").Split();int b=a.Length,i=0,n,m,j,o;var c=new List<char>();for(;i<s.Length;){var d=s[i++].Split('|');if(d.Length<2)c.Add(b<(n=int.Parse(d[0]))||n<1?' ':a[n-1]);else{o=(m=int.Parse(d[0]))<(n=int.Parse(d[1]))?1:-1;for(j=m;o>0?j<=n:j>=n;j+=o)c.Add(b<j||j<1?' ':a[j-1]);}}return c.ToArray();};

            char[] ar = {'H','e','l','l','o',' ','W','o','r','l','d'};

            PrintCharArray(f(ar)("1 TO 3"));
            PrintCharArray(f(ar)("5"));
            PrintCharArray(f(ar)("-10 TO 10"));
            PrintCharArray(f(ar)("0 AND 2 AND 4"));
            PrintCharArray(f(ar)("8 TO 3"));
            PrintCharArray(f(ar)("-300 AND 300"));
        }
    }
}

A naive solution, using a char list, which uses ' ' as an empty character and gets the job done. Hoping to improve soon.


问:
Just repeat yourself
Write a program that outputs

```<code>Do not repeat yourself!
</code>```

Your program code must respect the following constraints :

its length must be an even number

each character that is in position 2n (where n is an integer > 0) must be equal to the character in position 2n-1. The second character of the program is equal to the first, the fourth is equal to the third, etc.

Newlines count as characters!

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

Examples

HHeellllooWWoorrlldd is a valid program

123 or AAABBB or HHeello are incorrect

Verification

You can use this CJam script to verify that your source code is valid. Simply paste your code into the "Input" box and run the script.

答:
reticular, noncompeting, 62 bytes

```<code>2200**UU""DDoo  nnoott  rreeppeeaatt  yyoouurrsseellff!!""oo;;
</code>```

Try it online!

Explanation in parts:

```<code>2200**
2200    the stack looks like [2 2 0 0]
    *   [2 2 0*0]
     *  [2 2*0*0]
        [2 0]
</code>```

U sets the pointer direction to (2, 0), that is, moving 2 x-units and 0 y-units, so it skips every other character, starting with the next U being skipped. Then, every other character is recorded, and it is equivalent to:

```<code>"Do not repeat yourself!"o;
</code>```

which is a simple output program.

Other

This is competing for WallyWest's JavaScript bounty:

I can prove that, while numbers can be constructed under this restriction, strings cannot. Since no literals can be used, as the placement of any literal-building character would create an empty string:

```<code>""
''
``
</code>```

Then, only some operator can be used; the only "paired" operators used are:

```<code>++ -- << >> ** ~~ || && !! ==
</code>```

And none of these can cast numbers/others to strings. So no strings can be outputted.

Title: Just repeat yourself

Body:
reticular, noncompeting, 62 bytes

2200**UU""DDoo  nnoott  rreeppeeaatt  yyoouurrsseellff!!""oo;;

Try it online!

Explanation in parts:

2200**
2200    the stack looks like [2 2 0 0]
    *   [2 2 0*0]
     *  [2 2*0*0]
        [2 0]

U sets the pointer direction to (2, 0), that is, moving 2 x-units and 0 y-units, so it skips every other character, starting with the next U being skipped. Then, every other character is recorded, and it is equivalent to:

"Do not repeat yourself!"o;

which is a simple output program.

Other

This is competing for WallyWest's JavaScript bounty:

I can prove that, while numbers can be constructed under this restriction, strings cannot. Since no literals can be used, as the placement of any literal-building character would create an empty string:

""
''
``

Then, only some operator can be used; the only "paired" operators used are:

++ -- << >> ** ~~ || && !! ==

And none of these can cast numbers/others to strings. So no strings can be outputted.


答:
C#, 310

(Edit: bug fix)

A function with a multiline string parameter, returning a string.

Including the requested using in the byte count.

This is a porting of my javascript answer.

```<code>using System.Linq;
string f(string s){int o=-~s.IndexOf('\n'),m=99;var r=new string(' ',o);(s=r+s+r).Select((c,i)=>{int n=2,e=0,p,w=i%o+i/o;if(c>' '&w<m&&new[]{-1,1,o,-o}.All(d=>(s[i+d]>' '?(e=d)*--n:n)>0))for(m=w,r=""+c+s[p=i+e];new[]{e,o/e,-o/e}.Any(d=>s[p+(e=d)]>' ');)r+=s[p+=e];return i;}).Max();return r;}
</code>```

Test on ideone

With spaces

```<code>    string f(string s)
    {
        int o = -~s.IndexOf('\n');
        var r = new string(' ', o);
        var m = 99;
        (s = r + s + r).Select((c, i) =>
        {
            int n = 2, e = 0, p, w = i % o + i / o;
            if (c > ' ' & w < m & new[] { -1, 1, o, -o }.All(d => (s[i + d] > ' ' ? (e = d) * --n : n) > 0))
                for (m = w, r = "" + c + s[p = i + e];
                     new[] { e, o / e, -o / e }.Any(d => s[p + (e = d)] > ' ');
                     )
                   r += s[p += e];
            return i;
        }
        ).Max();
        return r;
    }
</code>```

Title: De-Snakify a String

Body:
A regular string looks like this:

```<code>Hello,IAmAStringSnake!
</code>```

And a string snake looks something like this:

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan
</code>```

Your Task

String snakes are dangerous, so you must make a program that takes a string snake as input and outputs it as a regular string.

Specifications

Input can be a multiline string or an array of strings.

Each line of the input will be padded with spaces to form a rectangular grid.

Characters in the snake can only connect to adjacent characters above, below, left or right of them (just like in the game Snake). They cannot go diagonal.

The snake characters will never be adjacent to another part of the snake, only the connected characters.

The first character of the string is the end character with the shortest Manhattan distance from the top-left corner of the input grid (i.e. the minimum number of moves it would take for a snake to go directly from the end character to the top-left corner). Both ends will never have the same distance.

The string can contain any ASCII character between code points 33 and 126 inclusive (no spaces or newlines).

The string will be between 2 and 100 characters long.

Shortest code in bytes wins.

Test Cases

(Input grid, followed by the output string)

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan

Hello,IAmAStringSnake!

----------

Python

Python

----------

P  ngPu  Code
r  i  z  d  G
o  m  z  n  o
gram  lesA  lf

ProgrammingPuzzlesAndCodeGolf

----------

   ~ zyx tsr XWVUTSR
   }|{ wvu q Y     Q
!          p Z `ab P
"#$ 6789:; o [ _ c O
  % 5    < n \]^ d N
('& 432  = m     e M
)     1  > lkjihgf L
*+,-./0  ?         K
         @ABCDEFGHIJ

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

----------

  tSyrep
  r    p
  in Sli
   g    Sile
   Snakes  n
Ser      ylt
a eh   ilS
fe w   t
   emo h
     Sre

SlipperyStringSnakesSilentlySlitherSomewhereSafe
</code>```

Body:
C#, 310

(Edit: bug fix)

A function with a multiline string parameter, returning a string.

Including the requested using in the byte count.

This is a porting of my javascript answer.

using System.Linq;
string f(string s){int o=-~s.IndexOf('\n'),m=99;var r=new string(' ',o);(s=r+s+r).Select((c,i)=>{int n=2,e=0,p,w=i%o+i/o;if(c>' '&w<m&&new[]{-1,1,o,-o}.All(d=>(s[i+d]>' '?(e=d)*--n:n)>0))for(m=w,r=""+c+s[p=i+e];new[]{e,o/e,-o/e}.Any(d=>s[p+(e=d)]>' ');)r+=s[p+=e];return i;}).Max();return r;}

Test on ideone

With spaces

    string f(string s)
    {
        int o = -~s.IndexOf('\n');
        var r = new string(' ', o);
        var m = 99;
        (s = r + s + r).Select((c, i) =>
        {
            int n = 2, e = 0, p, w = i % o + i / o;
            if (c > ' ' & w < m & new[] { -1, 1, o, -o }.All(d => (s[i + d] > ' ' ? (e = d) * --n : n) > 0))
                for (m = w, r = "" + c + s[p = i + e];
                     new[] { e, o / e, -o / e }.Any(d => s[p + (e = d)] > ' ');
                     )
                   r += s[p += e];
            return i;
        }
        ).Max();
        return r;
    }


答:
JavaScript (ES6), <s>907</s> <s>904</s> 903 bytes

Implements a compression by successive substitutions of the most frequent sub-strings.

This can be compressed significantly more (down to about 850 bytes) by assuming Windows-125x encoding and using replacement characters in the range 0xA0 - 0xFF. But the result is just ugly. :-)

let f =

n=>[...Array(78)].map((_,i)=>s=~":<=>ABNOSV\\^_`imov|".indexOf((c=String.fromCharCode(125-i)))?s:s.split(c).join(['\\','NINTENDO',`
`][c]||"9|XsD'RE405398T08kU8K0\"-G/'0|W7/;_E/C62G5|557970..-\"6_ /|52F8@04D\"`.-','??7 25\";7|3 3|4 .-662|---. |4|43__4433  ".substr(k+=2,2)),s="c99JE_,zP;,_27fX39fe,PH3197`;2 MG_cwQ2/G_|9_cE(^)G0@F_G_Xw(<) (>)9208_X (S)E(B)3(v)n@Q57ZK(A)4M|@3`;fGM _ QGf,PF@H4Q9 (_)9 M8H@HaQZM/HH@HHbHH@jHbaH20gbbqg2 Q_M50K/5Q_MJqgJ5Q_M~c3DIJKyIJjIED|Jg4I[FJ4/j49eDInjHKDI2yp/jb4yI@;ERT/dnIED|@3';[x3/59Y'4I[F@E0a/GDI3/'dUaayI59UqH;ER0dU5T93I[4lHU5 0885l8rt3uwlFr tF854l|r3tu4:0.5rGt|8830.5F@8x5ux.d2';F3R0d84'.0.4zep|[xb87p0RJE0H8J7TuJKIF3zJwp|[~57o2EoK/2ag2qnJ0YeCCfW.LL?-;k{{{{|CCC||_WOO ]]]. OO9 `;23'L?_.h?P _.'eC_||3}Z/_23/3_D|| N}h307.h2Y P_.LLh'- TMZi-iZ2/_z_31 _'h03'Y_+3o :::0@`-iYm0/m0|0|/=,/m0iP|9} 0 OY}@F_0_/0_/Z0_/'./|F9 0/30Y30/2`P57';`P3,7VJ54`?P",k=-2)&&s.split`~`[n-1]

console.log(f(1));
console.log(f(2));
console.log(f(3));```
</div>
</div>
</p>
<h3>Making-Of</h3>
<p>The above JS was generated with the following PHP script, where <code>"n64.txt"</code> is basically the concatenation of the 3 original pictures separated with <code>~</code> characters.</p>
<pre class="lang-php prettyprint-override"><code><?php
  $str = file_get_contents("n64.txt");

  // ignore line-breaks between 2 pictures
  $str = str_replace("~\n", "~", $str);

  // replace backslashes with 0's
  $str = str_replace("\\", "0", $str);

  // replace 'NINTENDO' with 1's to have more uppercase letters
  // available as replacement characters
  $str = str_replace("NINTENDO", "1", $str);

  // replace line-breaks with 2's
  $str = str_replace("\n", "2", $str);

  // $skipped is the list of characters that can't be used as replacement
  // characters (backslash + anything existing in the original string)
  $skipped = '';

  // $dic is the replacement dictionary
  $dic = '';

  for($i = 0; $i < 75; $i++) {
    // $r = current replacement character
    $r = chr(51 + $i);

    // can we use it?
    if($r == "\\" || strpos($str, $r) !== false) {
      $skipped .= $r;
      continue;
    }

    // look for the most frequent 2-character sub-string
    $count = array();

    for($n = 0; $n < strlen($str) - 1; $n++) {
      $s = substr($str, $n, 2);
      $count[$s] = isset($count[$s]) ? $count[$s] : 0;
      $count[$s]++;
    }

    asort($count);
    $keys = array_keys($count);
    $s = array_pop($keys);

    // add it to the dictionary
    $dic = $s.$dic;

    // replace all occurences with the replacement character
    $str = str_replace($s, $r, $str);

    printf("'%s' => '%s' %d\n", $s, $r, strlen($str));
  }

  // generate JS
  file_put_contents(
    "n64.js",
    sprintf(
      "n=>[...Array(78)].map((_,i)=>".
      "s=~\"%s\".indexOf((c=String.fromCharCode(125-i)))?s:".
      "s.split(c).join(['\\\\','NINTENDO',`\n`][c]||\"%s\".substr(k+=2,2)),".
      "s=\"%s\",k=-2)".
      "&&s.split`~`[n-1]",
      str_replace("\\", "\\\\", $skipped),
      str_replace('"', '\"', $dic),
      $str
    )
  );
?>
</code>```

Title: Some ASCII art for N64's 20th B-Day

Body:
The official release of the Nintendo 64 in North America was on September 29, 1996.[1] I figured that this anniversary deserved an ASCII art challenge. There's one small twist though, you have to output a different ASCII art for each of three different inputs.

If the input is 1, output this ASCII art of an N64 Controller: (source)

```<code>                 | |
             _,.-'-'-.,_
      ______|           |______
   ,-'      |  NINTENDO |      `-.
 ,'   _                          `.
/   _| |_                     (^)   \
|  |_   _|                  (<) (>) |
\    |_|         (S)     (B)  (v)   /
|`.              ___       (A)    ,'|
|  `-.______   ,' _ `.   ______,-'  |
|      |    `. | (_) | ,'    |      |
|      |      \`.___,'/      |      |
|      |      |       |      |      |
|      /      |       |      \      |
\     /       |       |       \     /
 `._,'        \       /        `._,'
               \     /
                `._,'
</code>```

If the input is 2, output this ASCII art of the N64 logo:(source)

```<code>                  .-"-.
               .-"     "-.
              /"-.     .-|
             /    "-.-"  |
            /      /     |
   .-"-.   /      /      |       .-"-.
.-"     "-/      /       |    .-"     "-.
|-.     .-"\    /        |   /"-.     .-|
|  '-.-"    \  /         | /'    "-.-"  |
|     \      \/   .-"-.  /'        |    |
|      \      \.-"     "-.         |    |
|       \      |-.     .-"\        |    |
|        \     |  "-.-"    '\      |    |
|         \    |    |        '\    |    |
|    |\    \   |    |          '\  |    |
|    | \    \  |    |            '\|    |
|    |  \    \ |    |    :\.            |
|    |   \    \|    |    |  \.          |
|    |    \         |    |    \.        |
'-.  |  .-"\        |    |    '.\.    .-'
   "-|-"    \       |    |      "-\.-"
             \      |    |
              \     |    |
               "-.  |  .-'
                  "-|-"
</code>```

Finally, if the input is 3, outout this ASCII art of a console and TV: (source)

```<code>              o
     o       /
      \     /
       \   /
        \ /
   ______________
  |.------------.|
  ||            ||
  ||            ||
  ||            ||
  ||            ||
  ||____________||_
  |OO ....... OO | `-.
  '------_.-._---' _.'
   _____||   ||___/_
  /  _.-|| N ||-._  \      .-._
 / -'_.---------._'- \    ,'___i-i___
/_.-'_  NINTENDO _'-._\  ' /_+  o :::\
|`-i /m\/m\|\|/=,/m\i-'| | || \ O / ||
|  |_\_/\_/___\_/'./|  | | \/  \ /  \/
`-'              '-.`-'  ,      V
                    `---'
</code>```

Rules:

Input may be either as a number or a string/char.

You may have any amount of leading or trailing spaces and trailing or leading newlines. (Output must be aligned correctly though)

Your submission may be either a full program or a function.

No retrieving the ASCII art from the internet.

This is code-golf, so smallest byte count wins.

Body:
JavaScript (ES6), <s>907</s> <s>904</s> 903 bytes

Implements a compression by successive substitutions of the most frequent sub-strings.

This can be compressed significantly more (down to about 850 bytes) by assuming Windows-125x encoding and using replacement characters in the range 0xA0 - 0xFF. But the result is just ugly. :-)

let f =

n=>[...Array(78)].map((_,i)=>s=~":<=>ABNOSV\\^_`imov|".indexOf((c=String.fromCharCode(125-i)))?s:s.split(c).join(['\\','NINTENDO',`
`][c]||"9|XsD'RE405398T08kU8K0\"-G/'0|W7/;_E/C62G5|557970..-\"6_ /|52F8@04D\"`.-','??7 25\";7|3 3|4 .-662|---. |4|43__4433  ".substr(k+=2,2)),s="c99JE_,zP;,_27fX39fe,PH3197`;2 MG_cwQ2/G_|9_cE(^)G0@F_G_Xw(<) (>)9208_X (S)E(B)3(v)n@Q57ZK(A)4M|@3`;fGM _ QGf,PF@H4Q9 (_)9 M8H@HaQZM/HH@HHbHH@jHbaH20gbbqg2 Q_M50K/5Q_MJqgJ5Q_M~c3DIJKyIJjIED|Jg4I[FJ4/j49eDInjHKDI2yp/jb4yI@;ERT/dnIED|@3';[x3/59Y'4I[F@E0a/GDI3/'dUaayI59UqH;ER0dU5T93I[4lHU5 0885l8rt3uwlFr tF854l|r3tu4:0.5rGt|8830.5F@8x5ux.d2';F3R0d84'.0.4zep|[xb87p0RJE0H8J7TuJKIF3zJwp|[~57o2EoK/2ag2qnJ0YeCCfW.LL?-;k{{{{|CCC||_WOO ]]]. OO9 `;23'L?_.h?P _.'eC_||3}Z/_23/3_D|| N}h307.h2Y P_.LLh'- TMZi-iZ2/_z_31 _'h03'Y_+3o :::0@`-iYm0/m0|0|/=,/m0iP|9} 0 OY}@F_0_/0_/Z0_/'./|F9 0/30Y30/2`P57';`P3,7VJ54`?P",k=-2)&&s.split`~`[n-1]

console.log(f(1));
console.log(f(2));
console.log(f(3));

Making-Of

The above JS was generated with the following PHP script, where "n64.txt" is basically the concatenation of the 3 original pictures separated with ~ characters.

<?php
  $str = file_get_contents("n64.txt");

  // ignore line-breaks between 2 pictures
  $str = str_replace("~\n", "~", $str);

  // replace backslashes with 0's
  $str = str_replace("\\", "0", $str);

  // replace 'NINTENDO' with 1's to have more uppercase letters
  // available as replacement characters
  $str = str_replace("NINTENDO", "1", $str);

  // replace line-breaks with 2's
  $str = str_replace("\n", "2", $str);

  // $skipped is the list of characters that can't be used as replacement
  // characters (backslash + anything existing in the original string)
  $skipped = '';

  // $dic is the replacement dictionary
  $dic = '';

  for($i = 0; $i < 75; $i++) {
    // $r = current replacement character
    $r = chr(51 + $i);

    // can we use it?
    if($r == "\\" || strpos($str, $r) !== false) {
      $skipped .= $r;
      continue;
    }

    // look for the most frequent 2-character sub-string
    $count = array();

    for($n = 0; $n < strlen($str) - 1; $n++) {
      $s = substr($str, $n, 2);
      $count[$s] = isset($count[$s]) ? $count[$s] : 0;
      $count[$s]++;
    }

    asort($count);
    $keys = array_keys($count);
    $s = array_pop($keys);

    // add it to the dictionary
    $dic = $s.$dic;

    // replace all occurences with the replacement character
    $str = str_replace($s, $r, $str);

    printf("'%s' => '%s' %d\n", $s, $r, strlen($str));
  }

  // generate JS
  file_put_contents(
    "n64.js",
    sprintf(
      "n=>[...Array(78)].map((_,i)=>".
      "s=~\"%s\".indexOf((c=String.fromCharCode(125-i)))?s:".
      "s.split(c).join(['\\\\','NINTENDO',`\n`][c]||\"%s\".substr(k+=2,2)),".
      "s=\"%s\",k=-2)".
      "&&s.split`~`[n-1]",
      str_replace("\\", "\\\\", $skipped),
      str_replace('"', '\"', $dic),
      $str
    )
  );
?>