答:
GAP, 30 bytes

Straightforward, the second argument to Cycles gives the set on which the permutation should act:

```<code>l->Size(Cycles(PermList(l),l))
</code>```

Title: Number of cycles of a permutation

Body:
Consider a permutation of the integers 1, ..., n, such as this one for n = 6:

```<code>[5,2,4,3,6,1]
</code>```

If you view the permutation as a mapping from [1,2,3,4,5,6] to [5,2,4,3,6,1], the permutation can be decomponsed into disjoint cycles. A cycle is a subset of elements that map to each other. For example, 1 gets mapped to 5, which gets mapped to 6, which gets mapped back to 1. So one cycle is [1,5,6]. The other cycles are [2] and [3,4]. Thus the number of cycles for this permutation is 3.

In general, the cycles of a permutation are unique (up to order), and the number of cycles for a permutation of size n varies from 1 to n.

The challenge

Given a non-empty permutation, output its number of cycles.

Input is an array formed by the n integers 1, 2, ..., n, where n > 0. Each integer occurs exactly once. The order in which they appear defines the permutation, as in the example above.

Instead of an array you can use a list, a string with a separator between the numbers, a separate input for each number, or anything that's reasonable.

For a permutation of size n, instead of the 1-based set of integers 1, ..., n you can consistently use the 0-based set 0, ..., n-1. If so, please indicate it in your answer.

The code should work for n up to 20 in a reasonable time, say less than one minute.

Code golf. All builtins allowed.

Test cases

This assumes 1-based, array input.

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

Related

This related challenge asks for the actual cycles of the permutation, not the number of them. Requiring only the number of cycles can lead to shorter algorithms that sidestep generating the actual cycles.

Body:
GAP, 30 bytes

Straightforward, the second argument to Cycles gives the set on which the permutation should act:

l->Size(Cycles(PermList(l),l))


问:
Create and write to a file

Challenge

Create a new file and write the string Hello World to it.

Restrictions

Your challenge must write to a file on disk, in the file system.

The file may not be a log file generated during normal operation of the interpreter.

The file must contain only the string Hello World. It is allowed to contain a trailing newline or minimal whitespace. No other content.

No command-line flags/pipes (etc) allowed, except when necessary to run the program. (e.g. perl -p)

Notes

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

Follow the spirit, not the letter, of the rules.

答:
JavaScript, 89 bytes

This code was tested in Chrome.  In other browsers, the element must be in the document for the click method to work.

a=document.createElement("a");a.href="data:text/plain,Hello World";a.download=1;a.click()
```

ContentLicense: CC BY-SA 4.0

Title: Create and write to a file

ContentLicense: CC BY-SA 3.0


答:
HTML, 83 bytes

This code was tested in Chrome.  It relies on the image failing to load, then it clicks itself, triggering the anchor tag which is a download link.

```

Title: Create and write to a file

Body:
Challenge

Create a new file and write the string Hello World to it.

Restrictions

Your challenge must write to a file on disk, in the file system.

The file may not be a log file generated during normal operation of the interpreter.

The file must contain only the string Hello World. It is allowed to contain a trailing newline or minimal whitespace. No other content.

No command-line flags/pipes (etc) allowed, except when necessary to run the program. (e.g. perl -p)

Notes

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

Follow the spirit, not the letter, of the rules.

Body:
HTML, 83 bytes

This code was tested in Chrome.  It relies on the image failing to load, then it clicks itself, triggering the anchor tag which is a download link.

<a href="data:text/plain,Hello World" download><img src onerror="this.click()"></a>


问:
Simulate a sock drawer

Background

I have a collection of "weekday socks", which are seven pairs of socks labeled by the days of the week.
When I wash my socks, they end up in a pile, and I must arrange them into the correct pairs before putting them into the closet.
My strategy is to pull one random sock from the pile at a time and put it on a drawer.
Whenever there's a matching pair of socks on the drawer, I tie them together and put them in the closet.
Your task is to simulate this random process and return the number of draws required to find the first matching pair.

Input

Your input is an integer N ≥ 1.
It represents the "number of days in a week": there are N pairs of socks in the pile, and each pair has a distinct label.
If necessary, you may also take a PRNG seed as input.

Output

Your output is the number of socks I have to draw before the first matching pair is found.
For example, if the first two socks already form a matching pair, the output is 2.

Of course, the output is random, and depends on the drawing order.
We assume that all drawing orders are equally likely, so that each time a sock is drawn, the choice is uniform and independent from all other choices.

Example

Let N = 3, so that we have 6 socks in total, labeled A A B B C C.
One possible run of the "sock-drawing protocol" is as follows:

```<code>       | Pile   | Drawer | Pairs
Begin  | AABBCC | -      | -
Draw B | AABCC  | B      | -
Draw C | AABC   | BC     | -
Draw B | AAC    | C      | BB
Draw A | AC     | AC     | BB
Draw A | C      | C      | AA BB
Draw C | -      | -      | AA BB CC
</code>```

The first matching pair was found after drawing the second B, which was the third sock to be drawn, so the correct output is 3.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Input and output can be in any reasonable format, including unary (string of 1s).

You may assume that your language's built-in RNG is perfect.
You don't have to actually simulate the sock-drawing protocol, as long as your outputs have the correct probability distribution.

"Test cases"

Here are the approximate probabilities of all outputs for the input N = 7:

```<code>Output       2     3     4     5     6     7     8
Probability  0.077 0.154 0.210 0.224 0.186 0.112 0.037
</code>```

To test your solution, you can run it for, say, 40 000 times and see whether the output distribution is reasonably close to this.

答:
Python, 66 bytes

```<code>from random import*
f=lambda n,k=1:k>randint(1,n*2)or-~f(n-.5,k+1)
</code>```

Dennis thought up a clever way to rearrange things, saving 5 bytes.

Title: Simulate a sock drawer

Body:
Python, 66 bytes

from random import*
f=lambda n,k=1:k>randint(1,n*2)or-~f(n-.5,k+1)

Dennis thought up a clever way to rearrange things, saving 5 bytes.


问:
Print/Output the L-phabet
Inspired by George Gibson's Print a Tabula Recta.

You are to print/output this exact text:

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
BBCDEFGHIJKLMNOPQRSTUVWXYZ
CCCDEFGHIJKLMNOPQRSTUVWXYZ
DDDDEFGHIJKLMNOPQRSTUVWXYZ
EEEEEFGHIJKLMNOPQRSTUVWXYZ
FFFFFFGHIJKLMNOPQRSTUVWXYZ
GGGGGGGHIJKLMNOPQRSTUVWXYZ
HHHHHHHHIJKLMNOPQRSTUVWXYZ
IIIIIIIIIJKLMNOPQRSTUVWXYZ
JJJJJJJJJJKLMNOPQRSTUVWXYZ
KKKKKKKKKKKLMNOPQRSTUVWXYZ
LLLLLLLLLLLLMNOPQRSTUVWXYZ
MMMMMMMMMMMMMNOPQRSTUVWXYZ
NNNNNNNNNNNNNNOPQRSTUVWXYZ
OOOOOOOOOOOOOOOPQRSTUVWXYZ
PPPPPPPPPPPPPPPPQRSTUVWXYZ
QQQQQQQQQQQQQQQQQRSTUVWXYZ
RRRRRRRRRRRRRRRRRRSTUVWXYZ
SSSSSSSSSSSSSSSSSSSTUVWXYZ
TTTTTTTTTTTTTTTTTTTTUVWXYZ
UUUUUUUUUUUUUUUUUUUUUVWXYZ
VVVVVVVVVVVVVVVVVVVVVVWXYZ
WWWWWWWWWWWWWWWWWWWWWWWXYZ
XXXXXXXXXXXXXXXXXXXXXXXXYZ
YYYYYYYYYYYYYYYYYYYYYYYYYZ
ZZZZZZZZZZZZZZZZZZZZZZZZZZ
</code>```

(Yes, I typed that by hand)

You are allowed to use all lowercase instead of all uppercase.

However, your choice of case must be consistent throughout the whole text.

Rules/Requirements

Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.

If it is possible, provide a link to a site where your program can be tested.

Your program must not write anything to STDERR.

Standard Loopholes are forbidden.

Your program can output in any case, but it must be printed (not an array or similar).

Scoring

Programs are scored according to bytes, in UTF-8 by default or a different character set of your choice.

Eventually, the answer with the least bytes will win.

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Python 2.7, 79 bytes

```<code>x=[chr(y) for y in range(65,91)]
for y in range(26):print x[y]*y+''.join(x[y:])
</code>```

Generate a list of the characters.

Loop through each showing the
beginning character a certain amount of times.

Then show the rest
after that.

Title: Print/Output the L-phabet

Body:
Python 2.7, 79 bytes

x=[chr(y) for y in range(65,91)]
for y in range(26):print x[y]*y+''.join(x[y:])

Generate a list of the characters.

Loop through each showing the
beginning character a certain amount of times.

Then show the rest
after that.


问:
Balance chemical equations!
Bernd is a high school student who has some problems in chemistry. In class he has to design chemical equations for some experiments they are doing, such as the combustion of heptane C7H16:

C7H16 + 11O2 → 7CO2 + 8H2O

Since mathematics isn't exactly Bernd's strongest subject, he often has a hard time finding the exact ratios between the pro- and educts of the reaction. Since you are Bernd's tutor, it is your job to help him! Write a program, that calculates the amount of each substance needed to get a valid chemical equation.

Input

The input is a chemical equation without amounts. In order to make this possible in pure ASCII, we write any subscriptions as ordinary numbers. Element names always start with a capital letter and may be followed by a minuscule. The molecules are separated with + signs, an ASCII-art arrow -> is inserted between both sides of the equation:

```<code>Al+Fe2O4->Fe+Al2O3
</code>```

The input is terminated with a newline and won't contain any spaces. If the input is invalid, your program may do whatever you like.

You may assume, that the input is never longer than 1024 characters. Your program may either read the input from standard input, from the first argument or in an implementation defined way at runtime if neither is possible.

Output

The output of your program is the input equation augmented with extra numbers. The number of atoms for each element must be the same on both sides of the arrow. For the example above, a valid output is:

```<code>2Al+Fe2O3->2Fe+Al2O3
</code>```

If the number for a molecule is 1, drop it. A number must always be a positive integer. Your program must yield numbers such that their sum is minimal. For instance, the following is illegal:

```<code>40Al+20Fe2O3->40Fe+20Al2O3
</code>```

If there is no solution, print

```<code>Nope!
</code>```

instead. A sample input that has no solution is

```<code>Pb->Au
</code>```

Testcases

Input->Output

```<code>C7H16+O2->CO2+H2O
C7H16+11O2->7CO2+8H2O

Al+Fe2O3->Fe+Al2O3
2Al+Fe2O3->2Fe+Al2O3

Pb->Au
Nope!
</code>```

This is code-golf, so shortest code wins!

Your program must terminate in reasonable time for all reasonable inputs

答:
Wolfram Language (Mathematica), 510 bytes

I employed the augmented chemical composition matrix approach described in

L.R.Thorne, An innovative approach to balancing chemical - reaction equations : a simplified matrix - inverse technique for determining the matrix null space. Chem.Educator, 2010, 15, 304 - 308.

One slight tweak was added:  I divided the transpose of the null-space vector by the greatest common divisor of the elements to ensure integer values in any solutions.  My implementation does not yet handle cases where there is more than one solution to balancing the equation.

b@t_ :=Quiet@Check[Module[{s = StringSplit[t, "+" | "->"], g = StringCases, k = Length,
  e, v, f, z, r},
e = Union@Flatten[g[#, _?UpperCaseQ ~~ ___?LowerCaseQ] & /@ s];v = k@e;
s_~f~e_ := If[g[s, e] == {}, 0, If[(r = g[s, e ~~ p__?DigitQ :> p]) == {}, 1,
   r /. {{x_} :> ToExpression@x}]];z = k@s - v;
r = #/(GCD @@ #) &[Inverse[Join[SparseArray[{{i_, j_} :> f[s[[j]], e[[i]]]}, k /@ {e, s}],
Table[Join[ConstantArray[0, {z, v}][[i]], #[[i]]], {i, k[#]}]]][[All, -1]] &
   [IdentityMatrix@z]];
Row@Flatten[ReplacePart[Riffle[Partition[Riffle[Abs@r, s], 2], " + "],2 Count[r,_?Negative]->" -> "]]],"Nope!"]
```

Try it online!

Analysis

It works by setting up the following chemical composition table, consisting of chemical species by elements, to which an addition nullity vector is added (becoming the augmented chemical composition table:

The inner cells are removed as a matrix and inverted, yielding.

The right-most column is extracted, yielding:

{-(1/8), -(11/8), 7/8, 1}

Each element in the vector is divided by the gcd of the elements (1/8), giving:

{-1, -11, 7, 8}

where the negative values will be placed on the left side of the arrow.
The absolute values of these are the numbers needed to balance the original equation:

Title: Balance chemical equations!

Body:
Wolfram Language (Mathematica), 510 bytes

I employed the augmented chemical composition matrix approach described in

L.R.Thorne, An innovative approach to balancing chemical - reaction equations : a simplified matrix - inverse technique for determining the matrix null space. Chem.Educator, 2010, 15, 304 - 308.

One slight tweak was added:  I divided the transpose of the null-space vector by the greatest common divisor of the elements to ensure integer values in any solutions.  My implementation does not yet handle cases where there is more than one solution to balancing the equation.

b@t_ :=Quiet@Check[Module[{s = StringSplit[t, "+" | "->"], g = StringCases, k = Length,
  e, v, f, z, r},
e = Union@Flatten[g[#, _?UpperCaseQ ~~ ___?LowerCaseQ] & /@ s];v = k@e;
s_~f~e_ := If[g[s, e] == {}, 0, If[(r = g[s, e ~~ p__?DigitQ :> p]) == {}, 1,
   r /. {{x_} :> ToExpression@x}]];z = k@s - v;
r = #/(GCD @@ #) &[Inverse[Join[SparseArray[{{i_, j_} :> f[s[[j]], e[[i]]]}, k /@ {e, s}],
Table[Join[ConstantArray[0, {z, v}][[i]], #[[i]]], {i, k[#]}]]][[All, -1]] &
   [IdentityMatrix@z]];
Row@Flatten[ReplacePart[Riffle[Partition[Riffle[Abs@r, s], 2], " + "],2 Count[r,_?Negative]->" -> "]]],"Nope!"]

<a href="https://tio.run/##PVJdb@IwEHzPr9gLUtUKcxw83ElFQFB6d6VqS4H2ybIiQzfBJXUi26SUXPjr3AbaPlhazaxnZz9epVvhq3RqKQ@HReAiuOxPNwpdEK5wueZ32fMmRV5a6MPcGaWTeZ4qxx0Dv@nDP/BbA18wSL74UFq0DNYE3KJO3IqBB4AMCgYxgx0DUzEPiX7SKtPBn1Q6h5onvMEgGj7lOZpaYwr7PURRNLzN3j4QAWfQDsCKXkHf1wH2PBvt4z3WrmEckwZVRgH9PpQVgx@sBs8NJZ@YWjInySuVKDeFywHk4uIzu3M0Cgba36Est1FV84/Z721u0Nra6rYSorc7lrbQgqLn1dKN9vnf8AqCABoXcMbHukBjkd9kSvN5LikeGSPfeVmqiMHLSTfmlvMXQZNDzpUQoqpHRs2VNClbEe49ykX6IRNm2jqp3UmI2ippjEUljl8ZNE4SBCtS4Q1BPokbpSmDVkfQ2OrG@PgZtVPu/U7SorbBjprxZtnb1wZmmKdyiQ/SOD5TcUzV61g56v0TGC1sYMghFevS86EJtP4uhNlGO25YNLzHhM6pQEGHAa0B0eTMv89y/OaLwwOdiOML7oe/rjs/m5NuaxBOus3r7oTyDof/" rel="nofollow noreferrer" title="Wolfram Language (Mathematica) – Try It Online">Try it online!

Analysis

It works by setting up the following chemical composition table, consisting of chemical species by elements, to which an addition nullity vector is added (becoming the augmented chemical composition table:

The inner cells are removed as a matrix and inverted, yielding.

The right-most column is extracted, yielding:

{-(1/8), -(11/8), 7/8, 1}

Each element in the vector is divided by the gcd of the elements (1/8), giving:

{-1, -11, 7, 8}

where the negative values will be placed on the left side of the arrow.
The absolute values of these are the numbers needed to balance the original equation:


答:
Jelly, 8 bytes

```<code>ḤX€Ṛ<RTḢ
</code>```

Try it online! or verify the distribution for N = 7.

Background

Let n be the number of pairs; there are 2n individual socks.

For the first draw, there are 2n socks and 0 of them would result in a matching pair. Therefore, the probability of success is 0 / 2n = 0.

Since the first draw wasn't successful, there are 2n - 1 socks on the pile and 1 of them would result in a matching pair. Therefore, the probability of success is 1 / (2n - 1).

If the second draw wasn't successful, there are 2n - 2 socks on the pile and 2 of them would result in a matching pair. Therefore, the probability of success is 2 / (2n - 2).

In general, if the first k draws were unsuccessful, there are 2n - k socks on the pile and 2 of them would result in a matching pair. Therefore, the probability of success is k / (2n - k).

Finally, if none of the first n draws was successful, there are 2n - k socks on the pile and all of them would result in a matching pair. Therefore, the probability of success is n / (2n - n) = 1.

How it works

```<code>ḤX€Ṛ<RTḢ  Main link. Argument: n

Ḥ         Unhalve; yield 2n.
 X€       Map `random draw' over [1, ..., 2n], pseudo-randomly choosing an integer
          from [1, ..., k] for each k in [1, ..., 2n].
   Ṛ      Reverse the resulting array.
     R    Range; yield [1, ..., n].
    <     Perform vectorized comparison.
          Comparing k with the integer chosen from [1, ..., 2n - (k - 1)] yields 1
          with probability (k - 1) / (2n - (k - 1)), as desired.
          The latter half of elements of the left argument do not have a counter-
          part in the right argument, so they are left untouched and thus truthy.
      T   Truth; yield all indices of non-zero integers.
       Ḣ  Head; extract the first one.
</code>```

Title: Simulate a sock drawer

Body:
Background

I have a collection of "weekday socks", which are seven pairs of socks labeled by the days of the week.
When I wash my socks, they end up in a pile, and I must arrange them into the correct pairs before putting them into the closet.
My strategy is to pull one random sock from the pile at a time and put it on a drawer.
Whenever there's a matching pair of socks on the drawer, I tie them together and put them in the closet.
Your task is to simulate this random process and return the number of draws required to find the first matching pair.

Input

Your input is an integer N ≥ 1.
It represents the "number of days in a week": there are N pairs of socks in the pile, and each pair has a distinct label.
If necessary, you may also take a PRNG seed as input.

Output

Your output is the number of socks I have to draw before the first matching pair is found.
For example, if the first two socks already form a matching pair, the output is 2.

Of course, the output is random, and depends on the drawing order.
We assume that all drawing orders are equally likely, so that each time a sock is drawn, the choice is uniform and independent from all other choices.

Example

Let N = 3, so that we have 6 socks in total, labeled A A B B C C.
One possible run of the "sock-drawing protocol" is as follows:

```<code>       | Pile   | Drawer | Pairs
Begin  | AABBCC | -      | -
Draw B | AABCC  | B      | -
Draw C | AABC   | BC     | -
Draw B | AAC    | C      | BB
Draw A | AC     | AC     | BB
Draw A | C      | C      | AA BB
Draw C | -      | -      | AA BB CC
</code>```

The first matching pair was found after drawing the second B, which was the third sock to be drawn, so the correct output is 3.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Input and output can be in any reasonable format, including unary (string of 1s).

You may assume that your language's built-in RNG is perfect.
You don't have to actually simulate the sock-drawing protocol, as long as your outputs have the correct probability distribution.

"Test cases"

Here are the approximate probabilities of all outputs for the input N = 7:

```<code>Output       2     3     4     5     6     7     8
Probability  0.077 0.154 0.210 0.224 0.186 0.112 0.037
</code>```

To test your solution, you can run it for, say, 40 000 times and see whether the output distribution is reasonably close to this.

Body:
Jelly, 8 bytes

ḤX€Ṛ<RTḢ

Try it online! or verify the distribution for N = 7.

Background

Let n be the number of pairs; there are 2n individual socks.

For the first draw, there are 2n socks and 0 of them would result in a matching pair. Therefore, the probability of success is 0 / 2n = 0.

Since the first draw wasn't successful, there are 2n - 1 socks on the pile and 1 of them would result in a matching pair. Therefore, the probability of success is 1 / (2n - 1).

If the second draw wasn't successful, there are 2n - 2 socks on the pile and 2 of them would result in a matching pair. Therefore, the probability of success is 2 / (2n - 2).

In general, if the first k draws were unsuccessful, there are 2n - k socks on the pile and 2 of them would result in a matching pair. Therefore, the probability of success is k / (2n - k).

Finally, if none of the first n draws was successful, there are 2n - k socks on the pile and all of them would result in a matching pair. Therefore, the probability of success is n / (2n - n) = 1.

How it works

ḤX€Ṛ<RTḢ  Main link. Argument: n

Ḥ         Unhalve; yield 2n.
 X€       Map `random draw' over [1, ..., 2n], pseudo-randomly choosing an integer
          from [1, ..., k] for each k in [1, ..., 2n].
   Ṛ      Reverse the resulting array.
     R    Range; yield [1, ..., n].
    <     Perform vectorized comparison.
          Comparing k with the integer chosen from [1, ..., 2n - (k - 1)] yields 1
          with probability (k - 1) / (2n - (k - 1)), as desired.
          The latter half of elements of the left argument do not have a counter-
          part in the right argument, so they are left untouched and thus truthy.
      T   Truth; yield all indices of non-zero integers.
       Ḣ  Head; extract the first one.


问:
Szekeres's sequence

Definition

\$a(1) = 1\$

\$a(2) = 2\$

\$a(n)\$ is smallest number \$k>a(n-1)\$ which avoids any 3-term arithmetic progression in \$a(1), a(2), ..., a(n-1), k\$.

In other words, \$a(n)\$ is the smallest number \$k>a(n-1)\$ such that there does not exist \$x, y\$ where \$0<x<y<n\$ and \$a(y)-a(x) = k-a(y)\$.

Worked out example

For \$n=5\$:

We have \$a(1), a(2), a(3), a(4) = 1, 2, 4, 5\$

If \$a(5)=6\$, then \$2, 4, 6\$ form an arithmetic progression.

If \$a(5)=7\$, then \$1, 4, 7\$ form an arithmetic progression.

If \$a(5)=8\$, then \$2, 5, 8\$ form an arithmetic progression.

If \$a(5)=9\$, then \$1, 5, 9\$ form an arithmetic progression.

If \$a(5)=10\$, no arithmetic progression can be found.

Therefore \$a(5)=10\$.

Task

Given \$n\$, output \$a(n)\$.

Specs

\$n\$ will be a positive integer.

You can use 0-indexed instead of 1-indexed, in which case \$n\$ can be \$0\$. Please state it in your answer if you are using 0-indexed.

Scoring

Since we are trying to avoid 3-term arithmetic progression, and 3 is a small number, your code should be as small (i.e. short) as possible, in terms of byte-count.

Testcases

The testcases are 1-indexed. You can use 0-indexed, but please specify it in your answer if you do so.

```<code>1     1
2     2
3     4
4     5
5     10
6     11
7     13
8     14
9     28
10    29
11    31
12    32
13    37
14    38
15    40
16    41
17    82
18    83
19    85
20    86
10000 1679657
</code>```

References

WolframMathWorld

OEIS A003278

答:
Ruby, 28 24 bytes

Using the same method as Dennis, with 0-based indexes:

->n{n.to_s(2).to_i(3)+1}
```

Run the test cases on repl.it: https://repl.it/Cif8/1

Title: Szekeres's sequence

Body:
Ruby, 28 24 bytes

Using the same method as Dennis, with 0-based indexes:

->n{n.to_s(2).to_i(3)+1}

Run the test cases on repl.it: https://repl.it/Cif8/1


答:
MATL, <s>16</s> 15 bytes

```<code>Q:"r@qGEy-/<?@.
</code>```

Try it online! Or observe the empirical distribution for 1000 samples in the N=7 case (it takes a while).

This directly generates the random variable representing the result, based on its probability distribution. Let N be the number of sock pairs, and let p(k) denote the probability that the k-th draw is successful, conditioned on the fact that the k-1-th draw was not succesful. Then (see also here):

p(1) is obviously 0. You can't have a pair with a single sock.

p(2) is 1/(2*N−1). At the second draw there is one winning sock that may be chosen out of 2*N−1 remaining socks.

p(3) is 2/(2*N−2). At the third draw there are 2 winning socks out of 2*N−2. The number of winning socks is 2 because the two socks you got after the second draw were different.

In general, by the same reasoning, p(k) is (k−1)/(2*N−k+1)

By the above formula, p(N+1) is 1. If you get to the N+1-th draw you are guaranteed to succeed then.

So the code iterates for a maximum of N+1 draws. At the k-th draw a random variable is generated that equals 1 with probability (k-1)/(2*N-k), or 0 otherwise. Whenever the random variable equals 1 (the draw has been succesful) the process stops and the current k is output.

```<code>Q:      % Input N implicitly. Generate [1 2 ... N+1] (values of draw index, k)
"       % For each
  r     %   Random variable uniformly distributed on the interval (0,1)
  @q    %   Push iteration index, k-1
  GE    %   Push 2*N
  y     %   Duplicate: push k-1 again
  -     %   Subtract: gives 2*N-k+1
  /     %   Divide: gives (k-1)/(2*N-k+1)
  <     %   Push 1 if random value is less than (k-1)/(2*N-k+1), 0 otherwise
  ?     %   If we got a 1
    @   %     Push k
    .   %     Break loop
        %   End if implicitly
        % End loop implicitly
        % Display implicitly
</code>```

Title: Simulate a sock drawer

Body:
MATL, <s>16</s> 15 bytes

Q:"r@qGEy-/<?@.

Try it online! Or observe the empirical distribution for 1000 samples in the N=7 case (it takes a while).

This directly generates the random variable representing the result, based on its probability distribution. Let N be the number of sock pairs, and let p(k) denote the probability that the k-th draw is successful, conditioned on the fact that the k-1-th draw was not succesful. Then (see also here):

p(1) is obviously 0. You can't have a pair with a single sock.

p(2) is 1/(2*N−1). At the second draw there is one winning sock that may be chosen out of 2*N−1 remaining socks.

p(3) is 2/(2*N−2). At the third draw there are 2 winning socks out of 2*N−2. The number of winning socks is 2 because the two socks you got after the second draw were different.

In general, by the same reasoning, p(k) is (k−1)/(2*N−k+1)

By the above formula, p(N+1) is 1. If you get to the N+1-th draw you are guaranteed to succeed then.

So the code iterates for a maximum of N+1 draws. At the k-th draw a random variable is generated that equals 1 with probability (k-1)/(2*N-k), or 0 otherwise. Whenever the random variable equals 1 (the draw has been succesful) the process stops and the current k is output.

Q:      % Input N implicitly. Generate [1 2 ... N+1] (values of draw index, k)
"       % For each
  r     %   Random variable uniformly distributed on the interval (0,1)
  @q    %   Push iteration index, k-1
  GE    %   Push 2*N
  y     %   Duplicate: push k-1 again
  -     %   Subtract: gives 2*N-k+1
  /     %   Divide: gives (k-1)/(2*N-k+1)
  <     %   Push 1 if random value is less than (k-1)/(2*N-k+1), 0 otherwise
  ?     %   If we got a 1
    @   %     Push k
    .   %     Break loop
        %   End if implicitly
        % End loop implicitly
        % Display implicitly


答:
CJam, 17 bytes

```<code>ri,2*mr{L+:L(&}#)
</code>```

Test it here.

Title: Simulate a sock drawer

Body:
CJam, 17 bytes

ri,2*mr{L+:L(&}#)

Test it here.


问:
Integers, Assemble!
Your task is to assemble the integers from 1 to N (given as input) into a rectangle of width W and height H (also given as input). Individual numbers may be rotated by any multiple of 90 degrees, but they must appear as contiguous blocks in the rectangle. That is, you cannot break one of the numbers into multiple digits and place the digits in the rectangle individually, neither can you bend three digits of a number around a corner. You could consider each number a brick from which you're building a wall.

Here is an example. Say your input is (N, W, H) = (12, 5, 3). One possible solution is:

```<code>18627
21901
53114
</code>```

For clarity, here are two copies of this grid, one with the one-digit numbers hidden and one with the two-digit numbers hidden:

```<code>1####    #8627
2##01    #19##
##11#    53##4
</code>```

It's fine if the rectangle cannot be disassembled again in a unique way. For instance, in the above example, the 12 could also have been placed like this:

```<code>#####    18627
21#01    ##9##
##11#    53##4
</code>```

Rules

You may assume that N is positive and that W*H matches the number of digits in the integers from 1 to N inclusive, and that a tiling of the rectangle into the given numbers exists. I don't currently have a proof whether this is always possible, but I'd be interested in one if you do.

Output may either be a single linefeed-separated string or a list of strings (one for each line) or a list of lists of single-digit integers (one for each cell).

The results of your submission must be determinstic and you should be able to handle all test cases in less than a minute on reasonable desktop machine.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

Except for the first one, none of these are unique. Each test case is N W H followed by a possible output. Make sure that your answer works when the rectangle is too narrow to write the larger numbers horizontally.

```<code>1 1 1
1

6 6 1
536142

6 2 3
16
25
34

10 1 11
1
0
8
9
2
6
7
3
1
5
4

11 13 1
1234567891011

27 9 5
213112117
192422581
144136119
082512671
205263272

183 21 21
183116214112099785736
182516114011998775635
181116013911897765534
180415913811796755433
179115813711695745332
178315713611594735231
177115613511493725130
176215513411392715029
175115413311291704928
174115313211190694827
173115213111089684726
172015113010988674625
171915012910887664524
170814912810786654423
169714812710685644322
168614712610584634221
167514612510483624120
166414512410382614019
165314412310281603918
164214312210180593817
163114212110079583716

200 41 12
81711132917193661114105533118936111184136
50592924448815915414562967609909953662491
89529721161671582389717813151113658811817
41418184511110119010183423720433017331118
35171183614003547461181197275184300111711
41874381132041861871718311415915921116264
11914245014112711011594492626831219331845
17125112629222085166344707736090956375181
94507611291431121128817413566319161275711
11011540021119913511011169939551729880780
92725141607727665632702567369893534277304
78118311405621148296417218591118562161856
</code>```

答:
Python 2, <s>210</s> 200 bytes

Edit: Works now!

Fills from top to bottom, left to right, starting with the largest numbers. Then, transpose and do it again. Then transpose and print. I had to pad with spaces for the transposition to work, since the lines aren't to their full length yet.

I had trouble getting a nested exec working (to do exec'exec"..."*w\n;...'*2. If someone can figure it out, let me know.

n,w,h=input()
s=[""]*h
for x in 1,2:
    exec"for i in range(h):l=len(s[i]+`n`)<=w;s[i]+=`n`*l;n-=l\n"*w;s=[r.replace(" ","")for r in map(lambda x:`x`[2::5],zip(*[r.ljust(w)for r in s]))];w,h=h,w
print s
```
<p><strong>Try it online</strong> - Uses a modified function so it can run multiple test cases more easily (and it couldn't use <code>exec</code>). Uncomment the other version and modify stdin to see it run.</p>
<p><strong>Less golfed:</strong></p>
<pre class="lang-python prettyprint-override"><code>def f(n,w,h):
    s=[""]*h
    for x in 1,2:
        for j in[0]*w:
            for i in range(h):
                l=len(s[i]+`n`)<=w
                s[i]+=`n`*l
                n-=l
        s=[r.ljust(w)for r in s]
        s=map(lambda x:`x`[2::5],zip(*s))
        s=[r.replace(' ','')for r in s]
        w,h=h,w
    print"\n".join(s)
</code>```

Title: Integers, Assemble!

Body:
Python 2, <s>210</s> 200 bytes

Edit: Works now!

Fills from top to bottom, left to right, starting with the largest numbers. Then, transpose and do it again. Then transpose and print. I had to pad with spaces for the transposition to work, since the lines aren't to their full length yet.

I had trouble getting a nested exec working (to do exec'exec"..."*w\n;...'*2. If someone can figure it out, let me know.

n,w,h=input()
s=[""]*h
for x in 1,2:
    exec"for i in range(h):l=len(s[i]+`n`)<=w;s[i]+=`n`*l;n-=l\n"*w;s=[r.replace(" ","")for r in map(lambda x:`x`[2::5],zip(*[r.ljust(w)for r in s]))];w,h=h,w
print s

Try it online - Uses a modified function so it can run multiple test cases more easily (and it couldn't use exec). Uncomment the other version and modify stdin to see it run.

Less golfed:

def f(n,w,h):
    s=[""]*h
    for x in 1,2:
        for j in[0]*w:
            for i in range(h):
                l=len(s[i]+`n`)<=w
                s[i]+=`n`*l
                n-=l
        s=[r.ljust(w)for r in s]
        s=map(lambda x:`x`[2::5],zip(*s))
        s=[r.replace(' ','')for r in s]
        w,h=h,w
    print"\n".join(s)


答:
JavaScript, <s>77</s> 73 bytes

n=>{p={};for(i=n;i--;p[i]=2);while(--p[n*Math.random()|0])i++;return i+2}
```
<p><strong>Explanation</strong></p>
<pre class="lang-js prettyprint-override"><code>var f = (n) => {
    var index;      // used first to initialize pile, then as counter
    var pile = {};  // sock pile

    // start with index = n
    // check that index > 0, then decrement
    // put 2 socks in pile at index
    for(index = n; index--; pile[index] = 2);
    // index is now -1, reuse for counter

    // pick random sock out of pile and decrement its count
    // continue loop if removed sock was not the last
    while(--pile[n * Math.random() | 0]) {
        index++;    // increment counter
    }
    // loop finishes before incrementing counter when first matching pair is removed
    // add 1 to counter to account for initial value of -1
    // add 1 to counter to account for drawing of first matching pair
    return index + 2;
};
</code>```

Title: Simulate a sock drawer

Body:
JavaScript, <s>77</s> 73 bytes

n=>{p={};for(i=n;i--;p[i]=2);while(--p[n*Math.random()|0])i++;return i+2}

Explanation

var f = (n) => {
    var index;      // used first to initialize pile, then as counter
    var pile = {};  // sock pile

    // start with index = n
    // check that index > 0, then decrement
    // put 2 socks in pile at index
    for(index = n; index--; pile[index] = 2);
    // index is now -1, reuse for counter

    // pick random sock out of pile and decrement its count
    // continue loop if removed sock was not the last
    while(--pile[n * Math.random() | 0]) {
        index++;    // increment counter
    }
    // loop finishes before incrementing counter when first matching pair is removed
    // add 1 to counter to account for initial value of -1
    // add 1 to counter to account for drawing of first matching pair
    return index + 2;
};


问:
Print a Tabula Recta!
The Tabula Recta (sometimes called a 'Vigenere Table'), was created by Johannes Trithemius, and has been used in several ciphers, including all variants of Bellaso's Vigenere cipher and the Trithemius cipher. It looks like this:

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
BCDEFGHIJKLMNOPQRSTUVWXYZA
CDEFGHIJKLMNOPQRSTUVWXYZAB
DEFGHIJKLMNOPQRSTUVWXYZABC
EFGHIJKLMNOPQRSTUVWXYZABCD
FGHIJKLMNOPQRSTUVWXYZABCDE
GHIJKLMNOPQRSTUVWXYZABCDEF
HIJKLMNOPQRSTUVWXYZABCDEFG
IJKLMNOPQRSTUVWXYZABCDEFGH
JKLMNOPQRSTUVWXYZABCDEFGHI
KLMNOPQRSTUVWXYZABCDEFGHIJ
LMNOPQRSTUVWXYZABCDEFGHIJK
MNOPQRSTUVWXYZABCDEFGHIJKL
NOPQRSTUVWXYZABCDEFGHIJKLM
OPQRSTUVWXYZABCDEFGHIJKLMN
PQRSTUVWXYZABCDEFGHIJKLMNO
QRSTUVWXYZABCDEFGHIJKLMNOP
RSTUVWXYZABCDEFGHIJKLMNOPQ
STUVWXYZABCDEFGHIJKLMNOPQR
TUVWXYZABCDEFGHIJKLMNOPQRS
UVWXYZABCDEFGHIJKLMNOPQRST
VWXYZABCDEFGHIJKLMNOPQRSTU
WXYZABCDEFGHIJKLMNOPQRSTUV
XYZABCDEFGHIJKLMNOPQRSTUVW
YZABCDEFGHIJKLMNOPQRSTUVWX
ZABCDEFGHIJKLMNOPQRSTUVWXY
</code>```

I frequently need this, but can't find it anywhere on the internet to copy and paste from. Because the square table is so long, and takes frigging ages to type, your code must be as short as possible.

Rules/Requirements

Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.

If it is possible, provide a link to a site where your program can be tested.

Your program must not write anything to STDERR.

Standard Loopholes are forbidden.

Your program can output in any case, but it must be printed (not an array or similar).

Scoring

Programs are scored according to bytes, in UTF-8 by default or a different character set of your choice.

Eventually, the answer with the least bytes will win.

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
PHP, <s>241</s> <s>68</s> 64 bytes

@Jörg Hülsermann kindly offered me this solution. The last one was pretty ridiculous.

```<code>for($r=range(A,Z);$i++<26;$r[]=array_shift($r))echo"
",join($r);
</code>```

Thanks to @Titus for saving me 4 bytes!

@Jörg Hülsermann also provided the following (and longer, with 74 bytes) version:

```<code>foreach($a=range(A,Z)as$r)echo strstr($j=join($a),$r),strstr($j,$r,1),"
";
</code>```

Thank you a lot!

You can try both solutions on http://sandbox.onlinephpfunctions.com/code/1a6a890887d8e817d5e9abbf521885b9306e2186

Title: Print a Tabula Recta!

Body:
PHP, <s>241</s> <s>68</s> 64 bytes

@Jörg Hülsermann kindly offered me this solution. The last one was pretty ridiculous.

for($r=range(A,Z);$i++<26;$r[]=array_shift($r))echo"
",join($r);

Thanks to @Titus for saving me 4 bytes!

@Jörg Hülsermann also provided the following (and longer, with 74 bytes) version:

foreach($a=range(A,Z)as$r)echo strstr($j=join($a),$r),strstr($j,$r,1),"
";

Thank you a lot!

You can try both solutions on http://sandbox.onlinephpfunctions.com/code/1a6a890887d8e817d5e9abbf521885b9306e2186


问:
Print this diamond
This question has been spreading like a virus in my office. There are quite a variety of approaches:

Print the following:

```<code>        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321
 123456787654321
  1234567654321
   12345654321
    123454321
     1234321
      12321
       121
        1
</code>```

Answers are scored in characters with fewer characters being better.

Title: Print this diamond

Body:
Groovy <s>77</s> 75

i=(-8..9);i.each{a->i.each{c=a.abs()+it.abs();print c>8?' ':9-c};println""}

old version:

(-8..9).each{a->(-8..9).each{c=a.abs()+it.abs();print c>8?' ':9-c};println""}


答:
Pyke, <s>14</s> <s>11</s> 10 bytes

```<code>GFoj*Gj>ns
</code>```

Try it here!

Title: Print/Output the L-phabet

Body:
Inspired by George Gibson's Print a Tabula Recta.

You are to print/output this exact text:

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
BBCDEFGHIJKLMNOPQRSTUVWXYZ
CCCDEFGHIJKLMNOPQRSTUVWXYZ
DDDDEFGHIJKLMNOPQRSTUVWXYZ
EEEEEFGHIJKLMNOPQRSTUVWXYZ
FFFFFFGHIJKLMNOPQRSTUVWXYZ
GGGGGGGHIJKLMNOPQRSTUVWXYZ
HHHHHHHHIJKLMNOPQRSTUVWXYZ
IIIIIIIIIJKLMNOPQRSTUVWXYZ
JJJJJJJJJJKLMNOPQRSTUVWXYZ
KKKKKKKKKKKLMNOPQRSTUVWXYZ
LLLLLLLLLLLLMNOPQRSTUVWXYZ
MMMMMMMMMMMMMNOPQRSTUVWXYZ
NNNNNNNNNNNNNNOPQRSTUVWXYZ
OOOOOOOOOOOOOOOPQRSTUVWXYZ
PPPPPPPPPPPPPPPPQRSTUVWXYZ
QQQQQQQQQQQQQQQQQRSTUVWXYZ
RRRRRRRRRRRRRRRRRRSTUVWXYZ
SSSSSSSSSSSSSSSSSSSTUVWXYZ
TTTTTTTTTTTTTTTTTTTTUVWXYZ
UUUUUUUUUUUUUUUUUUUUUVWXYZ
VVVVVVVVVVVVVVVVVVVVVVWXYZ
WWWWWWWWWWWWWWWWWWWWWWWXYZ
XXXXXXXXXXXXXXXXXXXXXXXXYZ
YYYYYYYYYYYYYYYYYYYYYYYYYZ
ZZZZZZZZZZZZZZZZZZZZZZZZZZ
</code>```

(Yes, I typed that by hand)

You are allowed to use all lowercase instead of all uppercase.

However, your choice of case must be consistent throughout the whole text.

Rules/Requirements

Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.

If it is possible, provide a link to a site where your program can be tested.

Your program must not write anything to STDERR.

Standard Loopholes are forbidden.

Your program can output in any case, but it must be printed (not an array or similar).

Scoring

Programs are scored according to bytes, in UTF-8 by default or a different character set of your choice.

Eventually, the answer with the least bytes will win.

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Pyke, <s>14</s> <s>11</s> 10 bytes

GFoj*Gj>ns

Try it here!


答:
C#, 157 Chars

```<code>class P{static void Main(){string x="ABCDEFGHIJKLMNOPQRSTUVWXYZ";for(int i=0;i<x.Length;i++)Console.WriteLine(x.Substring(i,x.Length-i)+x.Substring(0,i));}}
</code>```

Title: Print a Tabula Recta!

Body:
The Tabula Recta (sometimes called a 'Vigenere Table'), was created by Johannes Trithemius, and has been used in several ciphers, including all variants of Bellaso's Vigenere cipher and the Trithemius cipher. It looks like this:

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
BCDEFGHIJKLMNOPQRSTUVWXYZA
CDEFGHIJKLMNOPQRSTUVWXYZAB
DEFGHIJKLMNOPQRSTUVWXYZABC
EFGHIJKLMNOPQRSTUVWXYZABCD
FGHIJKLMNOPQRSTUVWXYZABCDE
GHIJKLMNOPQRSTUVWXYZABCDEF
HIJKLMNOPQRSTUVWXYZABCDEFG
IJKLMNOPQRSTUVWXYZABCDEFGH
JKLMNOPQRSTUVWXYZABCDEFGHI
KLMNOPQRSTUVWXYZABCDEFGHIJ
LMNOPQRSTUVWXYZABCDEFGHIJK
MNOPQRSTUVWXYZABCDEFGHIJKL
NOPQRSTUVWXYZABCDEFGHIJKLM
OPQRSTUVWXYZABCDEFGHIJKLMN
PQRSTUVWXYZABCDEFGHIJKLMNO
QRSTUVWXYZABCDEFGHIJKLMNOP
RSTUVWXYZABCDEFGHIJKLMNOPQ
STUVWXYZABCDEFGHIJKLMNOPQR
TUVWXYZABCDEFGHIJKLMNOPQRS
UVWXYZABCDEFGHIJKLMNOPQRST
VWXYZABCDEFGHIJKLMNOPQRSTU
WXYZABCDEFGHIJKLMNOPQRSTUV
XYZABCDEFGHIJKLMNOPQRSTUVW
YZABCDEFGHIJKLMNOPQRSTUVWX
ZABCDEFGHIJKLMNOPQRSTUVWXY
</code>```

I frequently need this, but can't find it anywhere on the internet to copy and paste from. Because the square table is so long, and takes frigging ages to type, your code must be as short as possible.

Rules/Requirements

Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.

If it is possible, provide a link to a site where your program can be tested.

Your program must not write anything to STDERR.

Standard Loopholes are forbidden.

Your program can output in any case, but it must be printed (not an array or similar).

Scoring

Programs are scored according to bytes, in UTF-8 by default or a different character set of your choice.

Eventually, the answer with the least bytes will win.

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
C#, 157 Chars

class P{static void Main(){string x="ABCDEFGHIJKLMNOPQRSTUVWXYZ";for(int i=0;i<x.Length;i++)Console.WriteLine(x.Substring(i,x.Length-i)+x.Substring(0,i));}}


问:
Hofstadter H-sequence

Definition

\$a(0) = 0\$

\$a(n) = n-a(a(a(n-1)))\$ for integer \$n > 0\$

Task

Given non-negative integer \$n\$, output \$a(n)\$.

Testcases

```<code>n     a(n)
0     0
1     1
2     1
3     2
4     3
5     4
6     4
7     5
8     5
9     6
10    7
11    7
12    8
13    9
14    10
15    10
16    11
17    12
18    13
19    13
20    14
10000 6823
</code>```

References

WolframMathWorld

OEIS A005374

Title: Hofstadter H-sequence

Body:
Maple, <s>28</s> 26 bytes

`if`(n=0,0,n-a(a(a(n-1))))

Usage:

> a:=n->ifelse(n=0,0,n-a(a(a(n-1))));
> seq(a(i),i=0..10);
0, 1, 1, 2, 3, 4, 4, 5, 5, 6, 7


答:
R, <s>42</s> 41 bytes

```<code>a=function(n)ifelse(n<1,0,n-a(a(a(n-1))))
</code>```

Usage:

```<code>> a(1)
1
> a(10)
7
</code>```

This recursive approach doesn't scale well for larger values of n though.

Title: Hofstadter H-sequence

Body:
Definition

\$a(0) = 0\$

\$a(n) = n-a(a(a(n-1)))\$ for integer \$n > 0\$

Task

Given non-negative integer \$n\$, output \$a(n)\$.

Testcases

```<code>n     a(n)
0     0
1     1
2     1
3     2
4     3
5     4
6     4
7     5
8     5
9     6
10    7
11    7
12    8
13    9
14    10
15    10
16    11
17    12
18    13
19    13
20    14
10000 6823
</code>```

References

WolframMathWorld

OEIS A005374

Body:
R, <s>42</s> 41 bytes

a=function(n)ifelse(n<1,0,n-a(a(a(n-1))))

Usage:

> a(1)
1
> a(10)
7

This recursive approach doesn't scale well for larger values of n though.


答:
Pyke, 5 bytes

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

Try it here!

0-based indexing

Same formula as jelly answer

Title: Szekeres's sequence

Body:
Definition

\$a(1) = 1\$

\$a(2) = 2\$

\$a(n)\$ is smallest number \$k>a(n-1)\$ which avoids any 3-term arithmetic progression in \$a(1), a(2), ..., a(n-1), k\$.

In other words, \$a(n)\$ is the smallest number \$k>a(n-1)\$ such that there does not exist \$x, y\$ where \$0<x<y<n\$ and \$a(y)-a(x) = k-a(y)\$.

Worked out example

For \$n=5\$:

We have \$a(1), a(2), a(3), a(4) = 1, 2, 4, 5\$

If \$a(5)=6\$, then \$2, 4, 6\$ form an arithmetic progression.

If \$a(5)=7\$, then \$1, 4, 7\$ form an arithmetic progression.

If \$a(5)=8\$, then \$2, 5, 8\$ form an arithmetic progression.

If \$a(5)=9\$, then \$1, 5, 9\$ form an arithmetic progression.

If \$a(5)=10\$, no arithmetic progression can be found.

Therefore \$a(5)=10\$.

Task

Given \$n\$, output \$a(n)\$.

Specs

\$n\$ will be a positive integer.

You can use 0-indexed instead of 1-indexed, in which case \$n\$ can be \$0\$. Please state it in your answer if you are using 0-indexed.

Scoring

Since we are trying to avoid 3-term arithmetic progression, and 3 is a small number, your code should be as small (i.e. short) as possible, in terms of byte-count.

Testcases

The testcases are 1-indexed. You can use 0-indexed, but please specify it in your answer if you do so.

```<code>1     1
2     2
3     4
4     5
5     10
6     11
7     13
8     14
9     28
10    29
11    31
12    32
13    37
14    38
15    40
16    41
17    82
18    83
19    85
20    86
10000 1679657
</code>```

References

WolframMathWorld

OEIS A003278

Body:
Pyke, 5 bytes

b2b3h

Try it here!

0-based indexing

Same formula as jelly answer


问:
Sort band names

Challenge description

You have a music library with many tracks recorded by many bands, each of which has a name, like Queen, Aerosmith, Sunny Day Real Estate, The Strokes . When an audio player displays your library alphabetically by band name, it usually skips the The part, as many band names start with The, making it easier to navigate through your media collection. In this challenge, given a list (array) of strings, you need to sort it that way (that is, omitting the The word at the beginning of the name). You can either write a method or a full working program.

Sample inputs / outputs

```<code>[Queen, Aerosmith, Sunny Day Real Estate, The Strokes] -> [Aerosmith, Queen, The Strokes, Sunny Day Real Estate]
[The Ramones, The Cure, The Pixies, The Roots, The Animals, Enrique Iglesias] -> [The Animals, The Cure, Enrique Iglesias, The Pixies, The Ramones, The Roots]
[The The, The They, Thermodynamics] -> [The The, Thermodynamics, The They]
</code>```

Notes / Edge cases

Sorting lexicographically is case insensitive, so The Police, The police and the police are all equivalent,

Your algorithm should only omit the first the word, so bands named The The or The The Band are sorted normally by the second the,

A band named The (a three letter word) is sorted normally (no skipping),

Order of two bands having the same name, one of which starts with the (like The Police and Police) is undefined,

You can assume that if a band's name consists of more than one word, they are separated by a single space character. You don't need to handle leading or trailing whitespaces,

All input strings match [A-Za-z0-9 ]*, that is they will consist only of lower- and uppercase letters of English alphabet, digits and space characters,

Remember that this is a code-golf challenge, so make your code as short as possible!

答:
Python, <s>66</s> <s>72</s> 69 bytes

lambda x:sorted(x,key=lambda a:a[4*(a.lower()[:4]=='the '):].lower())
```

Uses Python's sorted method with the key keyword argument to sort by the name minus "The". This is a lambda; to call it, give it a name by putting f= in front.

Now with extra case insensitivity!

Title: Sort band names

Body:
Python, <s>66</s> <s>72</s> 69 bytes

lambda x:sorted(x,key=lambda a:a[4*(a.lower()[:4]=='the '):].lower())

Uses Python's sorted method with the key keyword argument to sort by the name minus "The". This is a lambda; to call it, give it a name by putting f= in front.

Now with extra case insensitivity!


答:
Retina, 34 bytes

The trailing linefeed is significant.

```<code>%`^
$';
T`L`l`.+;
m`^the

O`
.+;

</code>```

I/O is one band per line.

Try it online!

Explanation

```<code>%`^
$';
</code>```

Duplicate each line, using ; as a separator.

```<code>T`L`l`.+;
</code>```

Turn everything in front of a ; to lower case.

```<code>m`^the

</code>```

Remove any thes that appear at the beginning of a line.

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

Sort the lines.

```<code>.+;

</code>```

Remove the beginnings of the lines which we used for sorting.

Title: Sort band names

Body:
Challenge description

You have a music library with many tracks recorded by many bands, each of which has a name, like Queen, Aerosmith, Sunny Day Real Estate, The Strokes . When an audio player displays your library alphabetically by band name, it usually skips the The part, as many band names start with The, making it easier to navigate through your media collection. In this challenge, given a list (array) of strings, you need to sort it that way (that is, omitting the The word at the beginning of the name). You can either write a method or a full working program.

Sample inputs / outputs

```<code>[Queen, Aerosmith, Sunny Day Real Estate, The Strokes] -> [Aerosmith, Queen, The Strokes, Sunny Day Real Estate]
[The Ramones, The Cure, The Pixies, The Roots, The Animals, Enrique Iglesias] -> [The Animals, The Cure, Enrique Iglesias, The Pixies, The Ramones, The Roots]
[The The, The They, Thermodynamics] -> [The The, Thermodynamics, The They]
</code>```

Notes / Edge cases

Sorting lexicographically is case insensitive, so The Police, The police and the police are all equivalent,

Your algorithm should only omit the first the word, so bands named The The or The The Band are sorted normally by the second the,

A band named The (a three letter word) is sorted normally (no skipping),

Order of two bands having the same name, one of which starts with the (like The Police and Police) is undefined,

You can assume that if a band's name consists of more than one word, they are separated by a single space character. You don't need to handle leading or trailing whitespaces,

All input strings match [A-Za-z0-9 ]*, that is they will consist only of lower- and uppercase letters of English alphabet, digits and space characters,

Remember that this is a code-golf challenge, so make your code as short as possible!

Body:
Retina, 34 bytes

The trailing linefeed is significant.

%`^
$';
T`L`l`.+;
m`^the

O`
.+;

I/O is one band per line.

Try it online!

Explanation

%`^
$';

Duplicate each line, using ; as a separator.

T`L`l`.+;

Turn everything in front of a ; to lower case.

m`^the

Remove any thes that appear at the beginning of a line.

O`

Sort the lines.

.+;

Remove the beginnings of the lines which we used for sorting.


答:
PowerShell v2+, <s>33</s> <s>32</s> 29 bytes

```<code>$args|sort{$_-replace'^the '}
</code>```

Saved 3 bytes thanks to @MathiasRJessen

Input is via command-line arguments. Sorts the original names based on the results of the script block {...} that performs a regex -replace to strip out the leading (case-insensitive) "the ".

Examples

```<code>PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'the Ramones' 'The cure' 'The Pixies' 'The Roots' 'the Animals' 'Enrique Iglesias'
the Animals
The cure
Enrique Iglesias
The Pixies
the Ramones
The Roots

PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'The The' 'The They' 'Thermodynamics'
The The
Thermodynamics
The They

PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'THE STOOGES' 'The Strokes' 'The The' 'the they' 'the band' 'STP'
the band
THE STOOGES
STP
The Strokes
The The
the they
</code>```

Title: Sort band names

Body:
PowerShell v2+, <s>33</s> <s>32</s> 29 bytes

$args|sort{$_-replace'^the '}

Saved 3 bytes thanks to @MathiasRJessen

Input is via command-line arguments. Sorts the original names based on the results of the script block {...} that performs a regex -replace to strip out the leading (case-insensitive) "the ".

Examples

PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'the Ramones' 'The cure' 'The Pixies' 'The Roots' 'the Animals' 'Enrique Iglesias'
the Animals
The cure
Enrique Iglesias
The Pixies
the Ramones
The Roots

PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'The The' 'The They' 'Thermodynamics'
The The
Thermodynamics
The They

PS C:\Tools\Scripts\golfing> .\sort-band-names.ps1 'THE STOOGES' 'The Strokes' 'The The' 'the they' 'the band' 'STP'
the band
THE STOOGES
STP
The Strokes
The The
the they


问:
Generate the names of the keys on a piano
On a standard 88 key piano, each key has a scientific name.

The first three keys are A0, B♭0, and B0. The keys then proceed through C1, D♭1, D1, E♭1, E1, F1, G♭1, G1, A♭1, A1, B♭1, B1, and start over again at C2. This continues up through B7, and the final key is C8.

Any flat can instead be written as a sharp of the preceding note, e.g. D♭4 can also be written C♯4. If necessary, you can write "D♭4" as "Db4".

Your program should build an ordered sequence (array, list, vector, etc.) containing the key names (as strings, symbols, or some similar data structure) in order.

Program length should be measured in characters, to avoid penalizing people who properly generate ♯ or ♭ rather than # or b. However, Unicode recoding is forbidden.

答:
Perl, 57+1

Just dug this up, a nice golfing exercise.  Requires -E for say -- counted in score.

say+(CDbDEbEFGbGAbABbB=~/(.b?)/g)[$_%12],$_/12%9for 9..96


答:
VBA, 61 bytes

```<code>Function K(D):While 2*D-K>K/Rnd:K=K+1:Wend:K=K+1:End Function
</code>```

- models the shifting probability of sock match given previous failure to match. At the point of evaluation, K is "socks in hand", so draw number is one more.

Title: Simulate a sock drawer

Body:
Background

I have a collection of "weekday socks", which are seven pairs of socks labeled by the days of the week.
When I wash my socks, they end up in a pile, and I must arrange them into the correct pairs before putting them into the closet.
My strategy is to pull one random sock from the pile at a time and put it on a drawer.
Whenever there's a matching pair of socks on the drawer, I tie them together and put them in the closet.
Your task is to simulate this random process and return the number of draws required to find the first matching pair.

Input

Your input is an integer N ≥ 1.
It represents the "number of days in a week": there are N pairs of socks in the pile, and each pair has a distinct label.
If necessary, you may also take a PRNG seed as input.

Output

Your output is the number of socks I have to draw before the first matching pair is found.
For example, if the first two socks already form a matching pair, the output is 2.

Of course, the output is random, and depends on the drawing order.
We assume that all drawing orders are equally likely, so that each time a sock is drawn, the choice is uniform and independent from all other choices.

Example

Let N = 3, so that we have 6 socks in total, labeled A A B B C C.
One possible run of the "sock-drawing protocol" is as follows:

```<code>       | Pile   | Drawer | Pairs
Begin  | AABBCC | -      | -
Draw B | AABCC  | B      | -
Draw C | AABC   | BC     | -
Draw B | AAC    | C      | BB
Draw A | AC     | AC     | BB
Draw A | C      | C      | AA BB
Draw C | -      | -      | AA BB CC
</code>```

The first matching pair was found after drawing the second B, which was the third sock to be drawn, so the correct output is 3.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Input and output can be in any reasonable format, including unary (string of 1s).

You may assume that your language's built-in RNG is perfect.
You don't have to actually simulate the sock-drawing protocol, as long as your outputs have the correct probability distribution.

"Test cases"

Here are the approximate probabilities of all outputs for the input N = 7:

```<code>Output       2     3     4     5     6     7     8
Probability  0.077 0.154 0.210 0.224 0.186 0.112 0.037
</code>```

To test your solution, you can run it for, say, 40 000 times and see whether the output distribution is reasonably close to this.

Body:
VBA, 61 bytes

Function K(D):While 2*D-K>K/Rnd:K=K+1:Wend:K=K+1:End Function

- models the shifting probability of sock match given previous failure to match. At the point of evaluation, K is "socks in hand", so draw number is one more.


答:
Pyke, 16 bytes

```<code>.#l1D"the ".^4*>
</code>```

Try it here!

```<code>.#                - sort_by(V, input)
  l1              -  i = i.lower()
      "the ".^    -   i.startswith("the ")
              I   -  if ^:
               4> -   i[4:]
</code>```

Title: Sort band names

Body:
Pyke, 16 bytes

.#l1D"the ".^4*>

Try it here!

.#                - sort_by(V, input)
  l1              -  i = i.lower()
      "the ".^    -   i.startswith("the ")
              I   -  if ^:
               4> -   i[4:]


答:
Java <s>176</s> 158 bytes

```<code>public String[]sort(String[]names){
  for(int i=-1;++i<names.length;)
    if(names[i].startsWith("(The |the )"))
      names[i]=names[i].substring(4);
  return Arrays.sort(names,String.CASE_INSENSITIVE_ORDER);
  }
</code>```

Main Function

```<code>public static void main(String[]args){
  Scanner s = new Scanner(System.in);
  List<String> list= new ArrayList<>();
  while(!(String h = s.nextLine).equalsIgnoreCase("~")){
    list.add(h);
  }
System.out.println(sort(list.toArray(newString[0]))
</code>```

);
    }

Golfed sort function:

```<code>String[]s(String[]n){for(int i=-1;++i<n.length;)if(n[i].startsWith("(The |the )"))n[i]=n[i].substring(4);return Arrays.sort(n,String.CASE_INSENSITIVE_ORDER);}
</code>```

Thanks to @raznagul for saving 18 bytes

Title: Sort band names

Body:
Java <s>176</s> 158 bytes

public String[]sort(String[]names){
  for(int i=-1;++i<names.length;)
    if(names[i].startsWith("(The |the )"))
      names[i]=names[i].substring(4);
  return Arrays.sort(names,String.CASE_INSENSITIVE_ORDER);
  }

Main Function

public static void main(String[]args){
  Scanner s = new Scanner(System.in);
  List<String> list= new ArrayList<>();
  while(!(String h = s.nextLine).equalsIgnoreCase("~")){
    list.add(h);
  }
System.out.println(sort(list.toArray(newString[0]))

);
    }

Golfed sort function:

String[]s(String[]n){for(int i=-1;++i<n.length;)if(n[i].startsWith("(The |the )"))n[i]=n[i].substring(4);return Arrays.sort(n,String.CASE_INSENSITIVE_ORDER);}

Thanks to @raznagul for saving 18 bytes


问:
Why was 6 afraid of 7?

Why was 6 afraid of 7? Because 7 8 9!

Given a string apply the following transformations:

If there is a 6 next to a 7 remove the 6 (6 is afraid of 7)

If the sequence "789" appears remove the 8 and the 9 (7 ate 9)

(If I'm not mistaken it doesn't matter what order you do the transformations in)

Keep applying these transformations until you can no longer.

Example:

78966

First we see "789", so the string becomes "766". Then we see "76", so we take out the 6, and the string becomes "76". Then we see "76" again, so we are left with "7".

Test Cases:

987 => 987 (Not in the right order. Does nothing.)

6 7 => 6 7 (The whitespace acts as a buffer between 6 and 7. Nothing happens)

676 => 7

7896789 => 77

7689 => 7

abcd => abcd

答:
Python 3, 46 bytes

import re
lambda s:re.sub(r'6*7(6|89)*','7',s)
```

Title: Why was 6 afraid of 7?


答:
JavaScript/ECMAScript 6 <s>93</s> 70 bytes

70 Thanks to Neil and Downgoat for advice

```<code>B=>B.sort((a,b)=>R(a).localeCompare(R(b)),R=s=>s.replace(/^the /i,''))
</code>```

Readable Version for the 70-byte variant

```<code>let sortBandNames = (bandNames) => {
    let stripThe = (name) => name.replace(/^the /i, '');
    let compareFunc = (a, b) => stripThe(a).localeCompare(stripThe(b));
    return bandNames.sort(compareFunc)
};
</code>```

93

```<code>f=B=>{R=s=>s.toLowerCase().replace(/the /,'');return B.sort((a,b)=>R(a).localeCompare(R(b)))}
</code>```

Readable Version for the 93-byte variant

```<code>let sortBandNames = (bandNames) => {
    let stripThe = (name) => name.toLowerCase().replace(/the /, '');
    let compareFunc = (a, b) => stripThe(a).localeCompare(stripThe(b));
    return bandNames.sort(compareFunc)
};
</code>```

Title: Sort band names

Body:
JavaScript/ECMAScript 6 <s>93</s> 70 bytes

70 Thanks to Neil and Downgoat for advice

B=>B.sort((a,b)=>R(a).localeCompare(R(b)),R=s=>s.replace(/^the /i,''))

Readable Version for the 70-byte variant

let sortBandNames = (bandNames) => {
    let stripThe = (name) => name.replace(/^the /i, '');
    let compareFunc = (a, b) => stripThe(a).localeCompare(stripThe(b));
    return bandNames.sort(compareFunc)
};

93

f=B=>{R=s=>s.toLowerCase().replace(/the /,'');return B.sort((a,b)=>R(a).localeCompare(R(b)))}

Readable Version for the 93-byte variant

let sortBandNames = (bandNames) => {
    let stripThe = (name) => name.toLowerCase().replace(/the /, '');
    let compareFunc = (a, b) => stripThe(a).localeCompare(stripThe(b));
    return bandNames.sort(compareFunc)
};


问:
How Many Rectangles in the Grid?

Well, although this challenge turned out to be a huge success, it also turned out to be very trivial to solve. Therefore, for those of looking for more of a challenge, I created a sequel to this challenge in which you must now count the number of unique rectangles. Check it out!

Now, for those of you looking to solve this challenge, here it comes.

Well, we don't really have a challenge like this yet, so here we go.

Consider this 3 x 3 grid of rectangles:

How many rectangles are there? Well, counting visually, we can see that there are actually 36 rectangles, including the entire plane itself, which are all shown in the animated GIF below:

The Task

The counting of rectangles as shown above is the task. In other words, given 2 integers greater than or equal to 0, m and n, where m represents the width and n represents the height, output the total number of rectangles in that m x n grid of rectangles.

Rules

The use of any built-ins that directly solve this problem is explicitly disallowed.

This challenge is not about finding the shortest answer, but finding the shortest answer in every language. Therefore, no answer will be accepted.

Standard loopholes are prohibited.

Test Cases

Presented in the format Array of Integers Input -> Integer Output:

```<code>[0,0] -> 0
[1,1] -> 1
[3,3] -> 36 (Visualized above)
[4,4] -> 100
[6,7] -> 588
</code>```

References

http://oeis.org/A096948

Remember, this is code-golf, so shortest code wins!

答:
Pyke, 6 bytes

```<code>mh+Bee
</code>```

Try it here!

```<code>mh     -    map(increment, input)
  +    -   ^ + input
   B   -  product(^)
    ee - ^ \ 4
</code>```

Title: How Many Rectangles in the Grid?

Body:
Pyke, 6 bytes

mh+Bee

Try it here!

mh     -    map(increment, input)
  +    -   ^ + input
   B   -  product(^)
    ee - ^ \ 4


问:
Polynomial Interpolation
Write a program that performs Polynomial Interpolation  using true arbitrary precision rational numbers. The input looks like this:

```
f(1) = 2/3
f(2) = 4/5
f(3) = 6/7
...
```

You may assume that there's exactly one whitespace before and after the = sign, all the numbers are either fractions or integers. You may also assume, that all fraction in the input are already irreducible.

No error checking is needed, you may assume, that the input is valid and no x is doubled in the f(x).

The output should be in a LaTeX compatible form, the emitted LaTeX code should yield the same graphical representation as the output given here.

```
f(x) = 123x^2 + \frac{45}{2}x + \frac{7}{4}
```

The fraction must be reduced as much as possible, eg. something like \frac{2}{4}  is not allowed. If the number is integer, don't use a fraction.

Special rules:

Your program should...

work for polynomials up to degree 12

complete in less then 1 minute for reasonable input

not use any functions that do the whole calculation for you

output the polynomial of smallest possible degree

Testcases:

The given testcases are just for clarification. Your program should yield correct result for all correct inputs.

Input

```
f(1) = 2/3
f(2) = 4/5
f(3) = 6/7
```

Output

```
f(x) = - \frac{4}{105}x^2
       + \frac{26}{105}x
       + \frac{16}{35}
```

Input

```
f(-12) = 13/2
f(5/3) = 3/5
f(13) = -6
f(1/5) = -3/4
```

Output

```
f(x) = - \frac{2186133}{239455744}x^3
       + \frac{2741731}{149659840}x^2
       + \frac{26720517}{29201920}x
       - \frac{279464297}{299319680}
```

Input

```
f(4/3) = 617/81
f(2) = 20/3
f(-8/3) = 6749/81
f(-5) = 7367/12
f(0) = 23/3
```

Output

```
f(x) = \frac{1}{2}x^4
     - 2x^3
     + \frac{7}{4}x^2
     + \frac{23}{3}
```

Input

```
f(0) = 5
f(1) = 7
f(2) = 9
f(3) = 11
f(4) = 13
```

Output

```
f(x) = 2x
     + 5
```

Input

```
f(1/2) = -1/2
f(-25) = -1/2
f(-54/12) = -1/2
```

Output

```
f(x) = -\frac{1}{2}
```

答:
Lagrange Method, Python, 199 236 202 bytes

A little late, but...

def lagrange(dp):
    l = lambda i: lambda x: (prod([(x - dp[j][0]) / (dp[i][0] - dp[j][0]) for j in range(len(dp)) if i != j]))
    return lambda x: sum([l(i)(x) * dp[i][1] for i in range(len(dp))])
```
<p>Edit: To adhere to general rules, we have to remove references to non-builtin functions (at least without importing them). I have rewritten it to only use standard library modules and also included the imports (thanks to @TheFifthMarshal & @Tech-Freak), while deleting extraneous whitespace, bumping it up to 208 bytes. To elaborate, the input <code>d</code> takes the form of a 2D iterable (an <code>nx2</code> matrix), where each row is a measurement, the first column is <span class="math-container">\$t\$</span> and the second column is <span class="math-container">\$x\$</span>. The output is an anonymous function which can take any floating point or integer number and give the approximate result.</p>
<pre class="lang-python prettyprint-override"><code>from functools import*
mul=lambda a,b:a*b
def l(d):
 l=lambda i,x:reduce(mul,[(x-d[j][0])/(d[i][0]-d[j][0])for j in range(len(d))if i!=j],1)
 return lambda x:sum([l(i,x)*d[i][1]for i in range(len(d))])
</code>```

Usage Example:

>>> t = np.arange(0, 5, 0.5)
>>> t2 = np.arange(0, 5, 0.01)
>>> x = t**3
>>> dp = np.vstack((t, x)).T
>>> poly = l(dp)
>>> plt.plot(t2, np.vectorize(poly)(t2), label="output")
>>> plt.scatter(t, x, label="input")
>>> plt.legend()

```

Title: Polynomial Interpolation

Body:
Lagrange Method, Python, 199 236 202 bytes

A little late, but...

def lagrange(dp):
    l = lambda i: lambda x: (prod([(x - dp[j][0]) / (dp[i][0] - dp[j][0]) for j in range(len(dp)) if i != j]))
    return lambda x: sum([l(i)(x) * dp[i][1] for i in range(len(dp))])

Edit: To adhere to general rules, we have to remove references to non-builtin functions (at least without importing them). I have rewritten it to only use standard library modules and also included the imports (thanks to @TheFifthMarshal & @Tech-Freak), while deleting extraneous whitespace, bumping it up to 208 bytes. To elaborate, the input d takes the form of a 2D iterable (an nx2 matrix), where each row is a measurement, the first column is \$t\$ and the second column is \$x\$. The output is an anonymous function which can take any floating point or integer number and give the approximate result.

from functools import*
mul=lambda a,b:a*b
def l(d):
 l=lambda i,x:reduce(mul,[(x-d[j][0])/(d[i][0]-d[j][0])for j in range(len(d))if i!=j],1)
 return lambda x:sum([l(i,x)*d[i][1]for i in range(len(d))])

Usage Example:

>>> t = np.arange(0, 5, 0.5)
>>> t2 = np.arange(0, 5, 0.01)
>>> x = t**3
>>> dp = np.vstack((t, x)).T
>>> poly = l(dp)
>>> plt.plot(t2, np.vectorize(poly)(t2), label="output")
>>> plt.scatter(t, x, label="input")
>>> plt.legend()


答:
JavaScript, <s>284</s> <s>259</s> <s>245</s> <s>241</s> <s>240</s> <s>223</s> <s>209</s> 205 bytes

// Golfed
let f = (N,W,H)=>eval('a=Array(H).fill("");while(N)g:{s=""+N--;d=s[L="length"];for(i in a)if(a[i][L]+d<=W){a[i]+=s;break g}for(p=0;d;++p){l=a[p][L];for(k=p+d;k>p;)l=a[--k][L]-l?W:l;while(l<W&&d)a[p+--d]+=s[d]}}a');

// Ungolfed
(N,W,H) => {
    a = Array(H).fill(""); // Create `H` empty rows.

    while (N) g : {
        s = "" + N--; // Convert the number to a string.
        d = s[L="length"]; // Count the digits in the number.

        // Loop through the rows trying to fit the number in horizontally.
        for (i in a) {
            if (a[i][L] + d <= W) { // If it fits.
                a[i] += s; // Append the number to the row.
                break g; // This is what a goto statement looks like in JavaScript.
            }
        }

        // Loop through the rows trying to fit the number in vertically.
        for (p = 0; d; ++p) {
            l = a[p][L]; // Get the length of the row.

            // Find `d` adjacent rows of the same length.
            for (k = p + d; k > p; ) {
                // If `a[--k][L] == l`, continue.
                // Else set `l` to `W` so the next loop doesn't run.
                l = a[--k][L] - l ? W : l;
            }

            // Put the characters in position.
            while (l < W && d)
                a[p+--d] += s[d];
        }
    }

    return a;
}

let test_data = [[1,1,1],
                 [6,6,1],
                 [6,2,3],
                 [10,1,11],
                 [10,11,1],
                 [11,13,1],
                 [27,9,5],
                 [183,21,21],
                 [184,2,222],
                 [200,41,12],
                 [1003,83,35]];

for (let test of test_data)
    console.log(f(test[0],test[1],test[2]));```

Title: Integers, Assemble!

Body:
Your task is to assemble the integers from 1 to N (given as input) into a rectangle of width W and height H (also given as input). Individual numbers may be rotated by any multiple of 90 degrees, but they must appear as contiguous blocks in the rectangle. That is, you cannot break one of the numbers into multiple digits and place the digits in the rectangle individually, neither can you bend three digits of a number around a corner. You could consider each number a brick from which you're building a wall.

Here is an example. Say your input is (N, W, H) = (12, 5, 3). One possible solution is:

```<code>18627
21901
53114
</code>```

For clarity, here are two copies of this grid, one with the one-digit numbers hidden and one with the two-digit numbers hidden:

```<code>1####    #8627
2##01    #19##
##11#    53##4
</code>```

It's fine if the rectangle cannot be disassembled again in a unique way. For instance, in the above example, the 12 could also have been placed like this:

```<code>#####    18627
21#01    ##9##
##11#    53##4
</code>```

Rules

You may assume that N is positive and that W*H matches the number of digits in the integers from 1 to N inclusive, and that a tiling of the rectangle into the given numbers exists. I don't currently have a proof whether this is always possible, but I'd be interested in one if you do.

Output may either be a single linefeed-separated string or a list of strings (one for each line) or a list of lists of single-digit integers (one for each cell).

The results of your submission must be determinstic and you should be able to handle all test cases in less than a minute on reasonable desktop machine.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

Except for the first one, none of these are unique. Each test case is N W H followed by a possible output. Make sure that your answer works when the rectangle is too narrow to write the larger numbers horizontally.

```<code>1 1 1
1

6 6 1
536142

6 2 3
16
25
34

10 1 11
1
0
8
9
2
6
7
3
1
5
4

11 13 1
1234567891011

27 9 5
213112117
192422581
144136119
082512671
205263272

183 21 21
183116214112099785736
182516114011998775635
181116013911897765534
180415913811796755433
179115813711695745332
178315713611594735231
177115613511493725130
176215513411392715029
175115413311291704928
174115313211190694827
173115213111089684726
172015113010988674625
171915012910887664524
170814912810786654423
169714812710685644322
168614712610584634221
167514612510483624120
166414512410382614019
165314412310281603918
164214312210180593817
163114212110079583716

200 41 12
81711132917193661114105533118936111184136
50592924448815915414562967609909953662491
89529721161671582389717813151113658811817
41418184511110119010183423720433017331118
35171183614003547461181197275184300111711
41874381132041861871718311415915921116264
11914245014112711011594492626831219331845
17125112629222085166344707736090956375181
94507611291431121128817413566319161275711
11011540021119913511011169939551729880780
92725141607727665632702567369893534277304
78118311405621148296417218591118562161856
</code>```


答:
Nim, 96 bytes

import algorithm,strutils,future
x=>x.sortedByIt toLower it[4*int(it.toLower[0..3]=="the ")..^0]
```

<p><sup>Those <code>import</code>s take up so many bytes <code>:|</code></sup></p>

<p>A translation of my Python answer.</p>

<p>This is an anonymous procedure; to use it, it must be passed into a testing procedure. Here's a full program you can use for testing:</p>

<pre class="lang-nim prettyprint-override"><code>import algorithm,strutils,future
proc test(x: seq[string] -> seq[string]) =
 echo x(@["The The", "The They", "Thermodynamics"]) # Substitute your input here
test(x=>x.sortedByIt toLower it[4*int(it.toLower[0..3]=="the ")..^0])
</code>```

Title: Sort band names

Body:
Nim, 96 bytes

import algorithm,strutils,future
x=>x.sortedByIt toLower it[4*int(it.toLower[0..3]=="the ")..^0]

Those imports take up so many bytes :|

A translation of my Python answer.

This is an anonymous procedure; to use it, it must be passed into a testing procedure. Here's a full program you can use for testing:

import algorithm,strutils,future
proc test(x: seq[string] -> seq[string]) =
 echo x(@["The The", "The They", "Thermodynamics"]) # Substitute your input here
test(x=>x.sortedByIt toLower it[4*int(it.toLower[0..3]=="the ")..^0])


答:
Perl, 52 bytes

-13 byte thanks to @manatwork

-1  byte thanks to @msh210

```<code>sub f{lc pop=~s/^the //ri}print sort{f($a)cmp f$b}<>
</code>```

One band per line as input, and so is the output.

The implementation is quite straight forward : the program prints the list of bands, sorted with the help of a custom function (f) which returns the lower case band name without the eventual leading the .

Title: Sort band names

Body:
Perl, 52 bytes

-13 byte thanks to @manatwork

-1  byte thanks to @msh210

sub f{lc pop=~s/^the //ri}print sort{f($a)cmp f$b}<>

One band per line as input, and so is the output.

The implementation is quite straight forward : the program prints the list of bands, sorted with the help of a custom function (f) which returns the lower case band name without the eventual leading the .


问:
Basic Calculator
You must write a program to evaluate a string that would be entered into a calculator.

The program must accept input and output the correct answer.  For languages that do not have standard input/output functions, you may assume the functions readLine and print.

Requirements

Does not use any kind of "eval" functions

Can handle floating point and negative numbers

Supports at least the +, -, *, and / operators

Can handle input containing one or more spaces between the operators and numbers

Evaluates the expression from left to right

The program that is the shortest wins.  In the event of a tie, the program that was submitted first wins.

You can assume that the input is valid and follows the correct format

Test Cases

Input

```<code>-4 + 5
</code>```

Output

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

Input

```<code>-7.5 / 2.5
</code>```

Output

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

Input

```<code>-2 + 6 / 2 * 8 - 1 / 2.5 - 18
</code>```

Output

```<code>-12
</code>```

答:
Python 3, 105 bytes

Manages the four basic operations, but it only costs 5 characters each to add ^ or %.

f=float
x,*l=input().split()
while l:o,y,*l=l;x,y=f(x),f(y);x=[x+y,x-y,x*y,x/y]['+-*/'.find(o)]
print(x)
```

Precedence of operations is left to right.

ContentLicense: CC BY-SA 2.5

Title: Basic Calculator

Body:
Python 3, 105 bytes

Manages the four basic operations, but it only costs 5 characters each to add ^ or %.

f=float
x,*l=input().split()
while l:o,y,*l=l;x,y=f(x),f(y);x=[x+y,x-y,x*y,x/y]['+-*/'.find(o)]
print(x)

Precedence of operations is left to right.