答:
k4, 15 bytes

```<code>*1?a|-26?a:.Q.A
</code>```

A port of @Dennis's Jelly answer.

Body:
About the Series

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

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

Input

No input is taken.

Output

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

Scoring

This is code golf. Shortest code in bytes wins.

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

Alphabet

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

Either

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

or

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

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

Explanation

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

Leaderboard

(from here)

var QUESTION_ID=89621,OVERRIDE_USER=20283;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

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

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

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

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

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

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

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

Body:
k4, 15 bytes

*1?a|-26?a:.Q.A

A port of @Dennis's Jelly answer.


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

About the Series

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

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

Input

No input is taken.

Output

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

Scoring

This is code golf. Shortest code in bytes wins.

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

Alphabet

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

Either

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

or

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

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

Explanation

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

Leaderboard

(from here)

var QUESTION_ID=89621,OVERRIDE_USER=20283;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

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

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

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

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

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

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

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

答:
Julia, 24 bytes

!c='a':c|>rand;c()=!!'z'
```

<p>Try it online!</p>

<h3>How it works</h3>

<p>The function <code>c()</code> simply calls <code>!</code> twice, with initial argument <strong>z</strong>. In turn <code>!c</code> creates a character range from <strong>a</strong> to its argument <code>c</code> and pseudo-randomly selects a character from this range. The distribution of probabilities is as follows.</p>

<p>Let <strong>x<sub>1</sub>, …, x<sub>26</sub></strong> denote the letters of the alphabet in their natural order. Select a letter <strong>Y</strong> among these, uniformly at random, then select a letter <strong>X</strong> from <strong>L<sub>1</sub>, … Y</strong>, also uniformly at random.</p>

<p>Fix <strong>n</strong> and <strong>k</strong> in <strong>1, …, 26</strong>.</p>

<p>If <strong>n ≤ k</strong>, then <strong>p(X = x<sub>n</sub> | Y = x<sub>k</sub>) = 1/k</strong>. On the other hand, if <strong>n > k</strong>, then <strong>p(X = x<sub>n</sub> | Y = x<sub>k</sub>) = 0</strong>.</p>

<p>Therefore, <strong>p(X = x<sub>n</sub>) = Σ p(Y = x<sub>k</sub>) * p(X = x<sub>n</sub> | Y = x<sub>k</sub>) = 1/26 · (1/n + ⋯ + 1/26)</strong>, giving the following probability distribution.</p>

<pre class="lang-julia prettyprint-override"><code>p(X = a) = 103187226801/696049754400 ≈ 0.148247
p(X = b) =  76416082401/696049754400 ≈ 0.109785
p(X = c) =  63030510201/696049754400 ≈ 0.090555
p(X = d) =  54106795401/696049754400 ≈ 0.077734
p(X = e) =  47414009301/696049754400 ≈ 0.068119
p(X = f) =  42059780421/696049754400 ≈ 0.060426
p(X = g) =  37597923021/696049754400 ≈ 0.054016
p(X = h) =  33773473821/696049754400 ≈ 0.048522
p(X = i) =  30427080771/696049754400 ≈ 0.043714
p(X = j) =  27452509171/696049754400 ≈ 0.039440
p(X = k) =  24775394731/696049754400 ≈ 0.035594
p(X = l) =  22341654331/696049754400 ≈ 0.032098
p(X = m) =  20110725631/696049754400 ≈ 0.028893
p(X = n) =  18051406831/696049754400 ≈ 0.025934
p(X = o) =  16139182231/696049754400 ≈ 0.023187
p(X = p) =  14354439271/696049754400 ≈ 0.020623
p(X = q) =  12681242746/696049754400 ≈ 0.018219
p(X = r) =  11106469546/696049754400 ≈ 0.015956
p(X = s) =   9619183746/696049754400 ≈ 0.013820
p(X = t) =   8210176146/696049754400 ≈ 0.011795
p(X = u) =   6871618926/696049754400 ≈ 0.009872
p(X = v) =   5596802526/696049754400 ≈ 0.008041
p(X = w) =   4379932326/696049754400 ≈ 0.006293
p(X = x) =   3215969526/696049754400 ≈ 0.004620
p(X = y) =   2100505176/696049754400 ≈ 0.003018
p(X = z) =   1029659400/696049754400 ≈ 0.001479
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Julia, 24 bytes

!c='a':c|>rand;c()=!!'z'

Try it online!

How it works

The function c() simply calls ! twice, with initial argument z. In turn !c creates a character range from a to its argument c and pseudo-randomly selects a character from this range. The distribution of probabilities is as follows.

Let x1, …, x26 denote the letters of the alphabet in their natural order. Select a letter Y among these, uniformly at random, then select a letter X from L1, … Y, also uniformly at random.

Fix n and k in 1, …, 26.

If n ≤ k, then p(X = xn | Y = xk) = 1/k. On the other hand, if n > k, then p(X = xn | Y = xk) = 0.

Therefore, p(X = xn) = Σ p(Y = xk) * p(X = xn | Y = xk) = 1/26 · (1/n + ⋯ + 1/26), giving the following probability distribution.

p(X = a) = 103187226801/696049754400 ≈ 0.148247
p(X = b) =  76416082401/696049754400 ≈ 0.109785
p(X = c) =  63030510201/696049754400 ≈ 0.090555
p(X = d) =  54106795401/696049754400 ≈ 0.077734
p(X = e) =  47414009301/696049754400 ≈ 0.068119
p(X = f) =  42059780421/696049754400 ≈ 0.060426
p(X = g) =  37597923021/696049754400 ≈ 0.054016
p(X = h) =  33773473821/696049754400 ≈ 0.048522
p(X = i) =  30427080771/696049754400 ≈ 0.043714
p(X = j) =  27452509171/696049754400 ≈ 0.039440
p(X = k) =  24775394731/696049754400 ≈ 0.035594
p(X = l) =  22341654331/696049754400 ≈ 0.032098
p(X = m) =  20110725631/696049754400 ≈ 0.028893
p(X = n) =  18051406831/696049754400 ≈ 0.025934
p(X = o) =  16139182231/696049754400 ≈ 0.023187
p(X = p) =  14354439271/696049754400 ≈ 0.020623
p(X = q) =  12681242746/696049754400 ≈ 0.018219
p(X = r) =  11106469546/696049754400 ≈ 0.015956
p(X = s) =   9619183746/696049754400 ≈ 0.013820
p(X = t) =   8210176146/696049754400 ≈ 0.011795
p(X = u) =   6871618926/696049754400 ≈ 0.009872
p(X = v) =   5596802526/696049754400 ≈ 0.008041
p(X = w) =   4379932326/696049754400 ≈ 0.006293
p(X = x) =   3215969526/696049754400 ≈ 0.004620
p(X = y) =   2100505176/696049754400 ≈ 0.003018
p(X = z) =   1029659400/696049754400 ≈ 0.001479


问:
Numbers of purity
Today we'll look at a sequence \$a\$, related to the Collatz function \$f\$:

$$f = \begin{cases}
n/2  & \text{if } n \equiv 0 \text{ (mod }2) \\
3n+1 & \text{if } n \equiv 1 \text{ (mod }2) \\
\end{cases}$$

We call a sequence of the form \$z, f(z), f(f(z)), …\$ a Collatz sequence.

The first number in our sequence, \$a(1)\$, is \$0\$. Under repeated application of \$f\$, it falls into a cycle \$0\to0\to0\to\:\cdots\$

The smallest number we haven't seen yet is 1, making \$a(2)=1\$. Under repeated application of \$f\$, it falls into a cycle \$1\to4\to2\to1\to\cdots\$

Now we have seen the number \$2\$ in the cycle above, so the next smallest number is \$a(3) = 3\$, falling into the cycle \$3\to10\to5\to16\to8\to4\to2\to1\to4\to\cdots\$

In all above cycles we've seen \$4\$ and \$5\$ already, so the next number is \$a(4) = 6\$.

By now you should get the idea. \$a(n)\$ is the smallest number that was not part of any Collatz sequences for all \$a(1), ..., a(n-1)\$

Write a program or function that, given an positive integer \$n\$, returns \$a(n)\$. Shortest code in bytes wins.

Testcases:

```<code>1  -> 0
2  -> 1
3  -> 3
4  -> 6
5  -> 7
6  -> 9
7  -> 12
8  -> 15
9  -> 18
10 -> 19
50 -> 114
</code>```

(This is OEIS sequence A061641.)

答:
Pyth, 32 bytes

```<code>VtQ=+Y.u?%N2h*3N/N2Z)=Zf!}TYhZ)Z
</code>```

Test suite.

ContentLicense: CC BY-SA 4.0

Title: Numbers of purity

Body:
Pyth, 32 bytes

VtQ=+Y.u?%N2h*3N/N2Z)=Zf!}TYhZ)Z

Test suite.


问:
Automatic box expander

Introduction

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

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

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

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

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

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

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

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

We expand this by one, so we get:

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

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

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

Becomes:

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

Now we reassemble the box, which results into:

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

The task

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

Test cases

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

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

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

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

答:
Pyth, 10 bytes

```<code>L+<b2tbyMy
</code>```

Try it online!

Title: Automatic box expander

Body:
Pyth, 10 bytes

L+<b2tbyMy

Try it online!


答:
Brachylog, <s>28</s> 26 bytes

2 bytes thanks to Fatalize.

```<code>{bB,?~c[A:C]hl2,A:Bc.}:1a.
</code>```

Try it online!

Title: Automatic box expander

Body:
Introduction

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

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

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

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

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

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

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

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

We expand this by one, so we get:

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

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

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

Becomes:

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

Now we reassemble the box, which results into:

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

The task

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

Test cases

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

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

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

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

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

2 bytes thanks to Fatalize.

{bB,?~c[A:C]hl2,A:Bc.}:1a.

Try it online!


问:
Code-Golf: Permutations
Write a function that takes as input a set of integers (can be a list, array or any other container with distinct numbers), and outputs the list of all its permutations.

Python (95 chars):

```<code>p=lambda s:s and sum(map(lambda e:map(lambda p:[e]+p,p(filter(lambda x:x!=e,s))),s),[]) or [[]]</code>```

It'd be nice to be beaten in the same language, but implementations in other languages are more than welcome!

答:
C, 270 243 239 characters

```<code>#define S t=*a;*a=a[i];a[i]=t;
#define R o=p(n,r-1,a+1,o,r-2,0)
int*p(n,r,a,o,i,t)int*a,*o;{if(!r)for(;n;--n)*o++=*--a;else{R;for(;i;--i){S R;S}}return o;}
P(n,a)int*a;{int N=1,i=n;for(;i;N*=i--);return p(n,n,a,malloc(N*n*8),n-1,0)-N*n;}
</code>```

The function P(n,a) returns a pointer to the n! permutations of a, packed one after another in one giant array.

Title: Code-Golf: Permutations

Body:
C, 270 243 239 characters

#define S t=*a;*a=a[i];a[i]=t;
#define R o=p(n,r-1,a+1,o,r-2,0)
int*p(n,r,a,o,i,t)int*a,*o;{if(!r)for(;n;--n)*o++=*--a;else{R;for(;i;--i){S R;S}}return o;}
P(n,a)int*a;{int N=1,i=n;for(;i;N*=i--);return p(n,n,a,malloc(N*n*8),n-1,0)-N*n;}

The function P(n,a) returns a pointer to the n! permutations of a, packed one after another in one giant array.


答:
Jelly, <s>20</s> 19 bytes

```<code>ḟ@JḢ×3‘$HḂ?ÐĿ;Ṛ
Ç¡Ṫ
</code>```

Try it online! or verify all test cases.

How it works

```<code>Ç¡Ṫ              Main link. No explicit arguments. Default argument: 0
 ¡               Read an integer n from STDIN and do the following n times.
Ç                  Call the helper link.
  Ṫ              Tail; extract the last element of the resulting array.

ḟ@JḢ×3‘$HḂ?ÐĿ;Ṛ  Helper link. Argument: A (array)

  J              Yield all 1-based indices of A, i.e., [1, ..., len(A)]. Since 0
                 belongs to A, there is at least one index that does belong to A.
ḟ@               Filter-false swapped; remove all indices that belong to A.
   Ḣ             Head; extract the first index (i) that hasn't been removed.
           ÐĿ    Call the quicklink to the left on i, then until the results are no
                 longer unique. Collect all unique results in an array.
         Ḃ?      If the last bit of the return value (r) is 1:
       $           Apply the monadic 3-link chain to the left to r.
    ×3‘              Yield 3r + 1.
        H        Else, halve r.
              Ṛ  Yield A, reversed.
             ;   Concatenate the results array with reversed A.
</code>```

After n iterations, the value of a(n + 1) will be at the beginning of the array. Since we concatenate the new array with a reversed copy of the old one, this means that a(n) will be at the end.

Title: Numbers of purity

Body:
Today we'll look at a sequence \$a\$, related to the Collatz function \$f\$:

$$f = \begin{cases}
n/2  & \text{if } n \equiv 0 \text{ (mod }2) \\
3n+1 & \text{if } n \equiv 1 \text{ (mod }2) \\
\end{cases}$$

We call a sequence of the form \$z, f(z), f(f(z)), …\$ a Collatz sequence.

The first number in our sequence, \$a(1)\$, is \$0\$. Under repeated application of \$f\$, it falls into a cycle \$0\to0\to0\to\:\cdots\$

The smallest number we haven't seen yet is 1, making \$a(2)=1\$. Under repeated application of \$f\$, it falls into a cycle \$1\to4\to2\to1\to\cdots\$

Now we have seen the number \$2\$ in the cycle above, so the next smallest number is \$a(3) = 3\$, falling into the cycle \$3\to10\to5\to16\to8\to4\to2\to1\to4\to\cdots\$

In all above cycles we've seen \$4\$ and \$5\$ already, so the next number is \$a(4) = 6\$.

By now you should get the idea. \$a(n)\$ is the smallest number that was not part of any Collatz sequences for all \$a(1), ..., a(n-1)\$

Write a program or function that, given an positive integer \$n\$, returns \$a(n)\$. Shortest code in bytes wins.

Testcases:

```<code>1  -> 0
2  -> 1
3  -> 3
4  -> 6
5  -> 7
6  -> 9
7  -> 12
8  -> 15
9  -> 18
10 -> 19
50 -> 114
</code>```

(This is OEIS sequence A061641.)

Body:
Jelly, <s>20</s> 19 bytes

ḟ@JḢ×3‘$HḂ?ÐĿ;Ṛ
Ç¡Ṫ

Try it online! or verify all test cases.

How it works

Ç¡Ṫ              Main link. No explicit arguments. Default argument: 0
 ¡               Read an integer n from STDIN and do the following n times.
Ç                  Call the helper link.
  Ṫ              Tail; extract the last element of the resulting array.

ḟ@JḢ×3‘$HḂ?ÐĿ;Ṛ  Helper link. Argument: A (array)

  J              Yield all 1-based indices of A, i.e., [1, ..., len(A)]. Since 0
                 belongs to A, there is at least one index that does belong to A.
ḟ@               Filter-false swapped; remove all indices that belong to A.
   Ḣ             Head; extract the first index (i) that hasn't been removed.
           ÐĿ    Call the quicklink to the left on i, then until the results are no
                 longer unique. Collect all unique results in an array.
         Ḃ?      If the last bit of the return value (r) is 1:
       $           Apply the monadic 3-link chain to the left to r.
    ×3‘              Yield 3r + 1.
        H        Else, halve r.
              Ṛ  Yield A, reversed.
             ;   Concatenate the results array with reversed A.

After n iterations, the value of a(n + 1) will be at the beginning of the array. Since we concatenate the new array with a reversed copy of the old one, this means that a(n) will be at the end.


答:
Haskell, 24 bytes

```<code>f(a:b:c)=a:b:b:c
f.map f
</code>```

Uses RootTwo's idea of duplicating the second row and column. The map f does this to each row, and the f. then does this to the rows.

Title: Automatic box expander

Body:
Haskell, 24 bytes

f(a:b:c)=a:b:b:c
f.map f

Uses RootTwo's idea of duplicating the second row and column. The map f does this to each row, and the f. then does this to the rows.


答:
x86_64 machine language for Linux, <s>15 19 17</s> 16 bytes

```<code>L1:
48 0f c7 f0             rdrand %rax
f3 48 0f b8 c0          popcnt %rax,%rax
3c 1a                   cmp    $0x1a,%al
7d f3                   jge    L1
04 41                   add    $0x41,%al
c3                      retq
</code>```

This requires support for the POPCNT and RDRAND instructions.

A uniform distributed random number is generated, the number of 1's in that number is counted, if that number is less than 26, a letter is returned. One will need to let the code run a long time before one sees a letter A.

To test, try something like

```<code>#include<stdio.h>
#define TEST "\x48\xf\xc7\xf0\xf3\x48\xf\xb8\xc0\x3c\x1a\x7d\xf3\4\x41\xc3"
int main(){
  int hist[26]={0};
  for(int i=0;i<10000000;i++){
    hist[ ((int(*)())TEST)() - 'A' ]++;
  }
  for(int i=0;i<26;i++){
    printf("%c %d\n", 'A'+i, hist[i] );
  }
}
</code>```

Sample output

```<code>A 0
B 0
C 0
D 0
E 0
F 0
G 0
H 0
I 0
J 0
K 0
L 8
M 32
N 137
O 511
P 1639
Q 5188
R 14475
S 37539
T 91670
U 205638
V 431381
W 842259
X 1536776
Y 2626524
Z 4206223
</code>```

The analytical expression for the probability of each letter can be derived from the binomial distribution. The letter A is assigned index k=0, B is assigned k=1 and so on.

```<code>        /  \
       | 64 |
       | k  |
        \  /
p(k)=------------
      25
      --- /  \
      \  | 64 |
      /  | i  |
      --- \  /
      i=0

 p(A)~1.0483e-18
 p(B)~6.7093e-17
 p(C)~2.1134e-15
 p(D)~4.3678e-14
 p(E)~6.6608e-13
 p(F)~7.9930e-12
 p(G)~7.8598e-11
 p(H)~6.5124e-10
 p(I)~4.6401e-09
 p(J)~2.8872e-08
 p(K)~1.5879e-07
 p(L)~7.7953e-07
 p(M)~3.4429e-06
 p(N)~1.3772e-05
 p(O)~5.0169e-05
 p(P)~1.6723e-04
 p(Q)~5.1214e-04
 p(R)~1.4460e-03
 p(S)~3.7758e-03
 p(T)~9.1413e-03
 p(U)~2.0568e-02
 p(V)~4.3095e-02
 p(W)~8.4231e-02
 p(X)~1.5381e-01
 p(Y)~2.6276e-01
 p(Z)~4.2042e-01
</code>```

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

Body:
x86_64 machine language for Linux, <s>15 19 17</s> 16 bytes

L1:
48 0f c7 f0             rdrand %rax
f3 48 0f b8 c0          popcnt %rax,%rax
3c 1a                   cmp    $0x1a,%al
7d f3                   jge    L1
04 41                   add    $0x41,%al
c3                      retq

This requires support for the POPCNT and RDRAND instructions.

A uniform distributed random number is generated, the number of 1's in that number is counted, if that number is less than 26, a letter is returned. One will need to let the code run a long time before one sees a letter A.

To test, try something like

#include<stdio.h>
#define TEST "\x48\xf\xc7\xf0\xf3\x48\xf\xb8\xc0\x3c\x1a\x7d\xf3\4\x41\xc3"
int main(){
  int hist[26]={0};
  for(int i=0;i<10000000;i++){
    hist[ ((int(*)())TEST)() - 'A' ]++;
  }
  for(int i=0;i<26;i++){
    printf("%c %d\n", 'A'+i, hist[i] );
  }
}

Sample output

A 0
B 0
C 0
D 0
E 0
F 0
G 0
H 0
I 0
J 0
K 0
L 8
M 32
N 137
O 511
P 1639
Q 5188
R 14475
S 37539
T 91670
U 205638
V 431381
W 842259
X 1536776
Y 2626524
Z 4206223

The analytical expression for the probability of each letter can be derived from the binomial distribution. The letter A is assigned index k=0, B is assigned k=1 and so on.

        /  \
       | 64 |
       | k  |
        \  /
p(k)=------------
      25
      --- /  \
      \  | 64 |
      /  | i  |
      --- \  /
      i=0

 p(A)~1.0483e-18
 p(B)~6.7093e-17
 p(C)~2.1134e-15
 p(D)~4.3678e-14
 p(E)~6.6608e-13
 p(F)~7.9930e-12
 p(G)~7.8598e-11
 p(H)~6.5124e-10
 p(I)~4.6401e-09
 p(J)~2.8872e-08
 p(K)~1.5879e-07
 p(L)~7.7953e-07
 p(M)~3.4429e-06
 p(N)~1.3772e-05
 p(O)~5.0169e-05
 p(P)~1.6723e-04
 p(Q)~5.1214e-04
 p(R)~1.4460e-03
 p(S)~3.7758e-03
 p(T)~9.1413e-03
 p(U)~2.0568e-02
 p(V)~4.3095e-02
 p(W)~8.4231e-02
 p(X)~1.5381e-01
 p(Y)~2.6276e-01
 p(Z)~4.2042e-01


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

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

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

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

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

Example

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

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

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

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

Or you could do a sorting function

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

Example tests

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

答:
Bash + coreutils, 94 bytes93 bytes

```<code>s(){ x=FMAyulgSOND;for y;{ rev<<<${y:0:3}|tr -d -C $x|tr $x C-M;echo B$y;}|sort|cut -f2 -dB;}
</code>```

This is an attempt to come up with a transform that sorts lexicographically.  If you look closely at the transform key FMAyulgSOND you can see the months February through December (January becomes empty after the transform; it's pulled to top by use of 'B' as the separator).  Reversing, truncating, and removing non-keyed letters allow this trick to be pulled off.

90 bytes using C Locale

```<code>s(){ x=FMAyulgSOND;for y;{ rev<<<${y:0:3}|tr -d -C $x|tr $x C-M;echo \␉$y;}|sort|cut -f2;}
</code>```

...where ␉ is the tab character.

80 bytes using C Locale

```<code>s(){ x=anebarprayunulugepctovec;for y;{ echo ${x%${y:1:2}*}\␉$y;}|sort|cut -f2;}
</code>```

...using @atlasolog's method.  Bound to be a way to use this approach to work with more locales.

Test/Usage

```<code>s December November October September August July June May April March February January
</code>```

outputs:

```<code>January
February
March
April
May
June
July
August
September
October
November
December
</code>```

Title: Sort the months of the year

Body:
Bash + coreutils, 94 bytes93 bytes

s(){ x=FMAyulgSOND;for y;{ rev<<<${y:0:3}|tr -d -C $x|tr $x C-M;echo B$y;}|sort|cut -f2 -dB;}

This is an attempt to come up with a transform that sorts lexicographically.  If you look closely at the transform key FMAyulgSOND you can see the months February through December (January becomes empty after the transform; it's pulled to top by use of 'B' as the separator).  Reversing, truncating, and removing non-keyed letters allow this trick to be pulled off.

90 bytes using C Locale

s(){ x=FMAyulgSOND;for y;{ rev<<<${y:0:3}|tr -d -C $x|tr $x C-M;echo \␉$y;}|sort|cut -f2;}

...where ␉ is the tab character.

80 bytes using C Locale

s(){ x=anebarprayunulugepctovec;for y;{ echo ${x%${y:1:2}*}\␉$y;}|sort|cut -f2;}

...using @atlasolog's method.  Bound to be a way to use this approach to work with more locales.

Test/Usage

s December November October September August July June May April March February January

outputs:

January
February
March
April
May
June
July
August
September
October
November
December


答:
Python 2, <s>97</s> 96 bytes

r,=s={-1}
exec'n=r=min({r+1,r+2,r+3}-s)\nwhile{n}-s:s|={n};n=(n/2,3*n+1)[n%2]\n'*input()
print r
```

<p>Takes advantage of the fact that all multiples of <strong>3</strong> are pure. Test it on Ideone.</p>

<h3>How it works</h3>

<p>On the first line, <code>r,=s={-1}</code> sets <strong>s = {-1}</strong> (set) and <strong>r = -1</strong>.</p>

<p>Next we read an integer from STDIN, repeat a certain string that many times, then execute it. This is equivalent to the following Python code.</p>

<pre class="lang-python prettyprint-override"><code>for _ in range(input())
    n=r=min({r+1,r+2,r+3}-s)
    while{n}-s:
        s|={n}
        n=(n/2,3*n+1)[n%2]
</code>```

In each iteration, we start by finding the smallest member of {r+1, r+2, r+3} that does not belong to s. In the first iteration, this initializes r as 0.

In all subsequent runs, s may (and will) contain some of r+1, r+2 and r+3, but never all of them, since all multiples of 3 are pure. To verify this statement, observe that no multiple m of 3 is of the form 3k + 1. That leaves 2m as the only possible pre-image, which is also a multiple of 3. Thus, m cannot appear in the Collatz sequence of any number that is less than m, and is therefore pure.

After identifying r and initializing n, we apply the Collatz function with n=(n/2,3*n+1)[n%2], adding each intermediate value of n to the set s with s|={n}. Once we encounter a number n that is already in s, {n}-s will yield an empty set, and the iteration stops.

The last value of r is the desired element of the sequence.

Title: Numbers of purity

Body:
Python 2, <s>97</s> 96 bytes

r,=s={-1}
exec'n=r=min({r+1,r+2,r+3}-s)\nwhile{n}-s:s|={n};n=(n/2,3*n+1)[n%2]\n'*input()
print r

Takes advantage of the fact that all multiples of 3 are pure. Test it on Ideone.

How it works

On the first line, r,=s={-1} sets s = {-1} (set) and r = -1.

Next we read an integer from STDIN, repeat a certain string that many times, then execute it. This is equivalent to the following Python code.

for _ in range(input())
    n=r=min({r+1,r+2,r+3}-s)
    while{n}-s:
        s|={n}
        n=(n/2,3*n+1)[n%2]

In each iteration, we start by finding the smallest member of {r+1, r+2, r+3} that does not belong to s. In the first iteration, this initializes r as 0.

In all subsequent runs, s may (and will) contain some of r+1, r+2 and r+3, but never all of them, since all multiples of 3 are pure. To verify this statement, observe that no multiple m of 3 is of the form 3k + 1. That leaves 2m as the only possible pre-image, which is also a multiple of 3. Thus, m cannot appear in the Collatz sequence of any number that is less than m, and is therefore pure.

After identifying r and initializing n, we apply the Collatz function with n=(n/2,3*n+1)[n%2], adding each intermediate value of n to the set s with s|={n}. Once we encounter a number n that is already in s, {n}-s will yield an empty set, and the iteration stops.

The last value of r is the desired element of the sequence.


答:
Vim, 7 bytes

```<code>♥GYPjYp
</code>```

where ♥ is Control-V.

```<code>           The cursor starts on the first non-whitespace character of the first line.
♥G         Enter visual block mode and go to bottom of document.
  YP       Duplicate this column.
    j      Move down to the second line of the file.
     Yp    Duplicate this line.
</code>```

Title: Automatic box expander

Body:
Vim, 7 bytes

♥GYPjYp

where ♥ is Control-V.

           The cursor starts on the first non-whitespace character of the first line.
♥G         Enter visual block mode and go to bottom of document.
  YP       Duplicate this column.
    j      Move down to the second line of the file.
     Yp    Duplicate this line.


答:
CJam, 14 bytes

```<code>q~{~\_@]z}2*N*
</code>```

Similar to my MATL answer, but repeats the second-last row instead of the second.

Try it online!

Explanation

```<code>q                e# Read input
 ~               e# Interpret as an array
  {      }2*     e# Do this twice
   ~             e# Dump array contents onto the stack
    \            e# Swap top two elements
     _           e# Duplicate
      @          e# Rotate
       ]         e# Pack into an array again
        z        e# Zip
            N*   e# Join by newlines. Implicitly display
</code>```

Title: Automatic box expander

Body:
CJam, 14 bytes

q~{~\_@]z}2*N*

Similar to my MATL answer, but repeats the second-last row instead of the second.

Try it online!

Explanation

q                e# Read input
 ~               e# Interpret as an array
  {      }2*     e# Do this twice
   ~             e# Dump array contents onto the stack
    \            e# Swap top two elements
     _           e# Duplicate
      @          e# Rotate
       ]         e# Pack into an array again
        z        e# Zip
            N*   e# Join by newlines. Implicitly display


答:
APL, <s>17</s> 15 bytes

```<code>{⍉⍵⌿⍨1+2=⍳≢⍵}⍣2
</code>```

Test:

```<code>      smallbox largebox
┌───┬──────┐
│ # │ OOOO │
│# #│O    O│
│ # │O    O│
│   │O    O│
│   │ OOOO │
└───┴──────┘
      {⍉⍵⌿⍨1+2=⍳≢⍵}⍣2 ¨ smallbox largebox
┌────┬───────┐
│ ## │ OOOOO │
│#  #│O     O│
│#  #│O     O│
│ ## │O     O│
│    │O     O│
│    │ OOOOO │
└────┴───────┘
</code>```

Explanation:

```<code>             ⍣2   run the following function 2 times:
{           }     stretch the box vertically and transpose
         ⍳≢⍵      indices of rows of box
       2=         bit-vector marking the 2nd row
  ⍵/⍨1+           replicate the 2nd row twice, all other rows once
 ⍉                transpose
</code>```

Title: Automatic box expander

Body:
APL, <s>17</s> 15 bytes

{⍉⍵⌿⍨1+2=⍳≢⍵}⍣2

Test:

      smallbox largebox
┌───┬──────┐
│ # │ OOOO │
│# #│O    O│
│ # │O    O│
│   │O    O│
│   │ OOOO │
└───┴──────┘
      {⍉⍵⌿⍨1+2=⍳≢⍵}⍣2 ¨ smallbox largebox
┌────┬───────┐
│ ## │ OOOOO │
│#  #│O     O│
│#  #│O     O│
│ ## │O     O│
│    │O     O│
│    │ OOOOO │
└────┴───────┘

Explanation:

             ⍣2   run the following function 2 times:
{           }     stretch the box vertically and transpose
         ⍳≢⍵      indices of rows of box
       2=         bit-vector marking the 2nd row
  ⍵/⍨1+           replicate the 2nd row twice, all other rows once
 ⍉                transpose


问:
Write a program that uses all printable non-alphanumeric ASCII symbols
In particular, use each of these symbols at least once in your source code:

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

Symbols inside comments, string literals, regexps (or any other kinds of literals etc.) don't count (but their delimiters such as /**/ or "" do count).

The program should not perform any action. It just has to compile and do nothing when run.

If for some reason some of the symbols cannot be used in the language of your choice, explain that rigorously (what and why must be excluded).

Update: A few answers used symbols withing regular expressions. I'd consider this a bit problematic, it's the same thing as putting them into string literals or comments (that's why I put etc. in that requirement). Please try without this. I also updated the requirement above.

Update: Shortest code wins (tagged as code-golf). As suggested, we'll most likely need some tie-breaker criteria. I suggest that if there is a tie, the winning one is the one in which the ASCII symbols appear as much ordered as possible. Formally: Filter out the first occurrence of each of the listed symbols from a program. This will result in a permutation on the listed symbols. The program with less inversion number of its permutation wins.

Update: I'd be happy to see some/more solutions in regular/mainstream languages, such as C(++), Java, Scala, Haskell, etc.

答:
Haskell, 53

```<code>a@""#%&*+/?^b|a'<-a!!0=(\_->a`b`[]);main=do{print$1}
</code>```

We can make this a bit shorter

45

```<code>a'@""#%&*+/?!<|^b=(\_->1`b`[]);main=do{main}
</code>```

however this program doesn't terminate, and uses more characters ('!','<','|') in the newly-defined infix.

Body:
Haskell, 53

a@""#%&*+/?^b|a'<-a!!0=(\_->a`b`[]);main=do{print$1}

We can make this a bit shorter

45

a'@""#%&*+/?!<|^b=(\_->1`b`[]);main=do{main}

however this program doesn't terminate, and uses more characters ('!','<','|') in the newly-defined infix.


Title: Numbers of purity

Body:
Brachylog, <s>70</s> <s>67</s> <s>65</s> <s>63</s> 62 bytes

,[]:?:1ih.
,0<=X=,?'eXg{t{:2/.*?|:3*+.}gB,(?.sB;?:Bc:2&.)}:?c.

Try it online!


问:
Print numbers from 1 to 10
This might be a very simple challenge, but I am surprised it hasn't been done on code-golf yet:

Print all Integers from 1 to 10 inclusive in ascending order to standard output.

Your output format can be whatever your language supports. This includes arbitrary separators (commas, semicolons, newlines, combinations of those, etc., but no digits), and prefixes and postfixes (like [...]). However, you may not output any other numbers than 1 through 10. Your program may not take any input. Standard loopholes are disallowed.

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

Leaderboard

var QUESTION_ID=86075,OVERRIDE_USER=42570;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Title: Print numbers from 1 to 10

Body:
Hexagony, 37 Bytes

Minified:

........./..\..10$\("\.$...).>{<!@.._

Try It Online!

Layed Out:

   . . . .
  . . . . .
 / . . \ . .
1 0 $ \ ( " \
 . $ . . . )
  . > { < !
   @ . . _


答:
K, 15 bytes

```<code>2{+x@&1+1=!#x}/
</code>```

Takes input as a matrix of characters:

```<code>  b: (" OOOO ";"O    O";" OOOO ")
(" OOOO "
 "O    O"
 " OOOO ")
</code>```

Apply a function twice (2{…}/) which gives the transpose (+) of the right argument indexed (x@) by the incremental run-length decode (&) of one plus (1+) a list of the locations equal to 1 (1=) in the range from 0 up to (!) the size of the outer dimension of the right argument (#x).

Step by step,

```<code>  #b
3
  !#b
0 1 2
  1=!#b
0 1 0
  1+1=!#b
1 2 1
  &1+1=!#b
0 1 1 2
  b@&1+1=!#b
(" OOOO "
 "O    O"
 "O    O"
 " OOOO ")
  +b@&1+1=!#b
(" OO "
 "O  O"
 "O  O"
 "O  O"
 "O  O"
 " OO ")
  2{+x@&1+1=!#x}/b
(" OOOOO "
 "O     O"
 "O     O"
 " OOOOO ")
</code>```

Try it here with oK.

Title: Automatic box expander

Body:
K, 15 bytes

2{+x@&1+1=!#x}/

Takes input as a matrix of characters:

  b: (" OOOO ";"O    O";" OOOO ")
(" OOOO "
 "O    O"
 " OOOO ")

Apply a function twice (2{…}/) which gives the transpose (+) of the right argument indexed (x@) by the incremental run-length decode (&) of one plus (1+) a list of the locations equal to 1 (1=) in the range from 0 up to (!) the size of the outer dimension of the right argument (#x).

Step by step,

  #b
3
  !#b
0 1 2
  1=!#b
0 1 0
  1+1=!#b
1 2 1
  &1+1=!#b
0 1 1 2
  b@&1+1=!#b
(" OOOO "
 "O    O"
 "O    O"
 " OOOO ")
  +b@&1+1=!#b
(" OO "
 "O  O"
 "O  O"
 "O  O"
 "O  O"
 " OO ")
  2{+x@&1+1=!#x}/b
(" OOOOO "
 "O     O"
 "O     O"
 " OOOOO ")

Try it here with oK.


问:
Shortest code to determine if a string is a palindrome
A palindrome is some string that is spelled the same way both backwards and forwards.  For instance, 'Eva, can I stab bats in a cave?' is a palindrome (EVACANISTAB | BATSINACAVE)

For this code golf, using the language of your choice, determine if a given string is a palindrome or not.

Edge Cases:

Punctuation is not counted towards palindrominess.

Control characters are not counted towards palindrominess.

Whitespace is not counted towards palindrominess.

Numbers are counted towards palindrominess.

Case in this challenge is not counted towards palindrominess.

There is no limit to the length of strings to evaluate, except for what is imposed by your language of choice.

For this challenge, limit yourself to the ASCII character set.

Technical Requirements:

Only method bodies are needed; additional things like method signatures, data structure declarations, etc. do not count towards the victory requirement.

Code must compile or interpret without compile-time errors or exceptions.

Code must not throw any unhandled exceptions or crash.  (Almost needless to say.  Almost.)

Code must return some value indicating palindrominess.  The data type depends on the language you use (e.g. a C# user might use a bool, whereas a JavaScript user could use a var.)

You may not write your own interpreter that performs this task as a 'native' capability so you can 'golf' a near-winning score.  (Hopefully needless to say.)

Victory Condition:

The shortest code in characters wins.

Current Leader: tmartin (k, 25 characters)

...Want the magic green check mark by your answer?  Beat this guy's answer!

答:
05AB1E, 4 bytes

```<code>álÂQ
</code>```

Explanation:

```<code>á     # Only keep the alphabetic characters.
 l    # Lowercase the characters.
  Â   # Bifurcate, which duplicates the letters and reverses the duplicate.
   Q  # Check if they are equal.
</code>```

Uses the CP-1252 encoding. Try it online!.

Body:
05AB1E, 4 bytes

álÂQ

Explanation:

á     # Only keep the alphabetic characters.
 l    # Lowercase the characters.
  Â   # Bifurcate, which duplicates the letters and reverses the duplicate.
   Q  # Check if they are equal.

Uses the CP-1252 encoding. Try it online!.


问:
Lemon-Limify a String
Write a program or function that takes in a nonempty single-line string. You may assume it only contains printable ASCII excluding space.

Print or return an ASCII art lozenge shape similar to a lemon or lime made from the prefixes of the string.

Suppose the input string is n letters long. Then, such a shape consists of 2n − 1 columns of ASCII art stitched together, each consisting of 2n − 1 lines. Counting from 1, the k-th column is f(k) = min(k, 2n − k) characters wide, and contains f(k) copies of the first f(k) characters of input, centered vertically, with single blank lines separating the copies.

For example, if the input is Lemon, the output should be:

```<code>          Lemon
      Lemo     Lemo
   Lem    Lemon    Lem
 Le   Lemo     Lemo   Le
L  Lem    Lemon    Lem  L
 Le   Lemo     Lemo   Le
   Lem    Lemon    Lem
      Lemo     Lemo
          Lemon
</code>```

If the input is lime the output should be:

```<code>      lime
   lim    lim
 li   lime   li
l  lim    lim  l
 li   lime   li
   lim    lim
      lime
</code>```

And the same pattern is followed for other inputs:

```<code>a

a

Be

 Be
B  B
 Be

/\

 /\
/  /
 /\

cat

   cat
 ca   ca
c  cat  c
 ca   ca
   cat

|||

   |||
 ||   ||
|  |||  |
 ||   ||
   |||

.__.

      .__.
   .__    .__
 ._   .__.   ._
.  .__    .__  .
 ._   .__.   ._
   .__    .__
      .__.

$tring

               $tring
          $trin      $trin
      $tri     $tring     $tri
   $tr    $trin      $trin    $tr
 $t   $tri     $tring     $tri   $t
$  $tr    $trin      $trin    $tr  $
 $t   $tri     $tring     $tri   $t
   $tr    $trin      $trin    $tr
      $tri     $tring     $tri
          $trin      $trin
               $tring
</code>```

Lines in the output may have trailing spaces and there may be one optional trailing newline.

The shortest code in bytes wins.

答:
C, 137 bytes

x,y,w;main(l,v)char**v;{for(y=l=strlen(v[1]);-l<--y;putchar(10))for(x=l;-l<--x;printf("%*.*s",w,w,x+y+l&1&&w>abs(y)?v[1]:""))w=l-abs(x);}
```

<p>Breakdown:</p>

<p>This draws every element of the 2n-1 x 2n-1 grid, with a mask function deciding whether the current element should be blank space or the input word (the mask checks for a diamond shape and checkerboard pattern).</p>

<pre class="lang-c prettyprint-override"><code>x,y,w;
main(l,v)char**v;{
    for(y=l=strlen(v[1]);-l<--y;/*...*/)    // row loop (count down to save bytes)
        for(x=l;-l<--x;/*...*/)             // column loop
            w=l-abs(x);                     // calculate current word's width
            printf("%*.*s",                 // print...
                w,w,                        // ...with min & max width...
                x+y+l&1&&w>abs(y)           // Check mask:
                    ?v[1]                   //  ...word
                    :"")                    //  ...or blank space
        putchar(10)                         // Newline
}
</code>```

Title: Lemon-Limify a String

Body:
C, 137 bytes

x,y,w;main(l,v)char**v;{for(y=l=strlen(v[1]);-l<--y;putchar(10))for(x=l;-l<--x;printf("%*.*s",w,w,x+y+l&1&&w>abs(y)?v[1]:""))w=l-abs(x);}

Breakdown:

This draws every element of the 2n-1 x 2n-1 grid, with a mask function deciding whether the current element should be blank space or the input word (the mask checks for a diamond shape and checkerboard pattern).

x,y,w;
main(l,v)char**v;{
    for(y=l=strlen(v[1]);-l<--y;/*...*/)    // row loop (count down to save bytes)
        for(x=l;-l<--x;/*...*/)             // column loop
            w=l-abs(x);                     // calculate current word's width
            printf("%*.*s",                 // print...
                w,w,                        // ...with min & max width...
                x+y+l&1&&w>abs(y)           // Check mask:
                    ?v[1]                   //  ...word
                    :"")                    //  ...or blank space
        putchar(10)                         // Newline
}


Title: Numbers of purity

Body:
PHP, <s>233</s> 124 bytes

<?$n=$argv[1];for($c=[];$n--;){for($v=0;in_array($v,$c);)$v++;for(;$n&&!in_array($v,$c);$v=$v&1?3*$v+1:$v/2)$c[]=$v;}echo$v;

+4 for function:

function a($n){for($c=[];$n--;){for($v=0;in_array($v,$c);)$v++;for(;$n&&!in_array($v,$c);$v=$v&1?3*$v+1:$v/2)$c[]=$v;}return$v;}


问:
Alphabet Spiral
You are to write a program or function that outputs this exact text:

```<code>OPQRSTU
NQPONMV
MREDCLW
LSFABKX
KTGHIJY
JUVWXYZA
IHGFEDCB
</code>```

May also be lowercase and trailing spaces and newlines are allowed.

Standard loopholes are disallowed

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

答:
MATL, <s>28</s> 26 bytes

```<code>1Y2tIL)P0v7lYLP2:JTF-JQ&()
</code>```

Try it online!

Explanation

```<code>1Y2     % Push string 'AB...Z'
tIL)    % Duplicate, remove last: gives 'AB...Y'
P       % Flip: gives 'YX...A'
0       % Push 0. Char 0 is treated as space
v       % Concatenate into a column vector of char
7lYL    % 7x7 numeric array: clockwise spiral of numbers from 1 to 49
P       % Flip vertically to make it anti-clockwise
2:      % Push [1 2]. Will be attached vertically after the last col
JqJh    % Index "[end-1, end]", to be used as row index
JQ      % Index "end+1", to be used as column index
&(      % Assign [1 2] to those positions. The rest of the new col will contain 0
)       % Index into the char vector. Indexing is modular and 1-based, so 0 as an
        % index refers to the last value of the char vector, which is char 0, or
        % equivalently space. So the 0 values in the numeric array give spaces.
        % Implicitly display
</code>```

Title: Alphabet Spiral

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

1Y2tIL)P0v7lYLP2:JTF-JQ&()

Try it online!

Explanation

1Y2     % Push string 'AB...Z'
tIL)    % Duplicate, remove last: gives 'AB...Y'
P       % Flip: gives 'YX...A'
0       % Push 0. Char 0 is treated as space
v       % Concatenate into a column vector of char
7lYL    % 7x7 numeric array: clockwise spiral of numbers from 1 to 49
P       % Flip vertically to make it anti-clockwise
2:      % Push [1 2]. Will be attached vertically after the last col
JqJh    % Index "[end-1, end]", to be used as row index
JQ      % Index "end+1", to be used as column index
&(      % Assign [1 2] to those positions. The rest of the new col will contain 0
)       % Index into the char vector. Indexing is modular and 1-based, so 0 as an
        % index refers to the last value of the char vector, which is char 0, or
        % equivalently space. So the 0 values in the numeric array give spaces.
        % Implicitly display


答:
Fourier, <s>143</s> 141 bytes

Not a particularly interesting answer except that it stores newlines (ASCII code 10) as the variable T... Uses isaacg's golfing program.

```<code>79a^a^a^a^a^a^a10a~T78a81avavavava86aTa77a82a69avava76a87aTa76a83a70a65a^a75a88aTa75a84a71a^a^a^a89a10a74a85a^a^a^a^a^a65aTa73avavavavavavava
</code>```

<s>Try it online</s>

Try it online!

Title: Alphabet Spiral

Body:
You are to write a program or function that outputs this exact text:

```<code>OPQRSTU
NQPONMV
MREDCLW
LSFABKX
KTGHIJY
JUVWXYZA
IHGFEDCB
</code>```

May also be lowercase and trailing spaces and newlines are allowed.

Standard loopholes are disallowed

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

Body:
Fourier, <s>143</s> 141 bytes

Not a particularly interesting answer except that it stores newlines (ASCII code 10) as the variable T... Uses isaacg's golfing program.

79a^a^a^a^a^a^a10a~T78a81avavavava86aTa77a82a69avava76a87aTa76a83a70a65a^a75a88aTa75a84a71a^a^a^a89a10a74a85a^a^a^a^a^a65aTa73avavavavavavava

<s>Try it online</s>

Try it online!


问:
Render "Digital Clock Style" Numbers
Write the shortest program which will take a string of numbers (of up to at least 20 length) as input, and display the output using the standard digital clock style numbers.  For instance for input 81, a solution with ascii output would give:

```<code> _
|_|  |
|_|  |
</code>```

Graphical output is also acceptable, if it helps.

答:
Ghostscript (270) (248) (214)

Edit: More substitutions. Removed space between digits.

Edit: Even more substitutions. Main loop now looks like what it does!

```<code>/F{forall}def[48<~HUp;::1ncBInp~>{1 index 1 add}F
pop/*{dup
2 idiv exch
2 mod
1 eq}/P{print}/#{( )P}/?{ifelse
P}/O{{( )}?}/|{*{(|)}O}/_{*{(_)}O}>>begin[[[[ARGUMENTS{{load
# _ #}F()=]2{{| _ |}F()=]}repeat]pop[[[[}F
</code>```

Uses ghostscript's argument-processing feature: invoke with gs -dNODISPLAY -- digit.ps 012 345 6789.

ContentLicense: CC BY-SA 2.5

Title: Render "Digital Clock Style" Numbers

Body:
Ghostscript (270) (248) (214)

Edit: More substitutions. Removed space between digits.

Edit: Even more substitutions. Main loop now looks like what it does!

/F{forall}def[48<~HUp;::1ncBInp~>{1 index 1 add}F
pop/*{dup
2 idiv exch
2 mod
1 eq}/P{print}/#{( )P}/?{ifelse
P}/O{{( )}?}/|{*{(|)}O}/_{*{(_)}O}>>begin[[[[ARGUMENTS{{load
# _ #}F()=]2{{| _ |}F()=]}repeat]pop[[[[}F

Uses ghostscript's argument-processing feature: invoke with gs -dNODISPLAY -- digit.ps 012 345 6789.


问:
Write a Sine-Deriving Machine

The Challenge

Your challenge is to write a program that evaluates the following function:

f(x, t) = d^x / dt^x (sin t)

That is, the x-th derivative of sin t. In case you aren't familiar with calculus, here is a table of derivatives for the sine function:

...

f(-1, t) = -cos t

f(0, t) = sin t

f(1, t) = cos t

f(2, t)= -sin  t

...

The sequence repeats these 4 functions.

The Inputs

Your program should take in an integer to be used as the x value in the function, and a float to be used at the t value in the function.

Your program may use radians or degrees for the sine function.

The Output

Your program should output the value of f(x, t) given the integer x and float t.

Scoring

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

答:
J, 17 bytes

4 :'1&o.d.(4|x)y'
```

<p>Computes the (x%4)th derivative of sine, and then apply to right argument.</p>

<h2>Usage:</h2>

<pre class="lang-j prettyprint-override"><code>>> f =: 4 :'1&o.d.(4|x)y'
>> _1 0 1 2 3 (f"0 0) 0
<< _1 0 1 0 _1
</code>```

where >> is STDIN and << is STDOUT.

Title: Write a Sine-Deriving Machine

Body:
J, 17 bytes

4 :'1&o.d.(4|x)y'

Computes the (x%4)th derivative of sine, and then apply to right argument.

Usage:

>> f =: 4 :'1&o.d.(4|x)y'
>> _1 0 1 2 3 (f"0 0) 0
<< _1 0 1 0 _1

where >> is STDIN and << is STDOUT.


答:
Python, 42 bytes

from math import*
lambda x,n:sin(x+pi/2*n)
```

Uses the fact that differentiating shifts the function by pi/2 left.

Title: Write a Sine-Deriving Machine

Body:
The Challenge

Your challenge is to write a program that evaluates the following function:

f(x, t) = d^x / dt^x (sin t)

That is, the x-th derivative of sin t. In case you aren't familiar with calculus, here is a table of derivatives for the sine function:

...

f(-1, t) = -cos t

f(0, t) = sin t

f(1, t) = cos t

f(2, t)= -sin  t

...

The sequence repeats these 4 functions.

The Inputs

Your program should take in an integer to be used as the x value in the function, and a float to be used at the t value in the function.

Your program may use radians or degrees for the sine function.

The Output

Your program should output the value of f(x, t) given the integer x and float t.

Scoring

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

Body:
Python, 42 bytes

from math import*
lambda x,n:sin(x+pi/2*n)

Uses the fact that differentiating shifts the function by pi/2 left.


答:
Haskell, 16 bytes

x%n=sin$x+pi/2*n
```

<p>Defines a binary operator <code>%</code>.</p>

<pre class="lang-haskell prettyprint-override"><code>λ 2.0 % (-3)
-0.4161468365471426
</code>```

Uses the fact that differentiating shifts the function by pi/2 left.

Making it point-free was longer (takes n x):

(sin.).(+).(pi/2*)
```

Title: Write a Sine-Deriving Machine

Body:
Haskell, 16 bytes

x%n=sin$x+pi/2*n

Defines a binary operator %.

λ 2.0 % (-3)
-0.4161468365471426

Uses the fact that differentiating shifts the function by pi/2 left.

Making it point-free was longer (takes n x):

(sin.).(+).(pi/2*)


答:
Convex (IDE version only), 6 bytes

```<code>P½*+ms
</code>```

Try it online!

After futher investigation, with the help of Dennis in chat, it was found that the command-line version of Convex (what TIO uses) has a bug that breaks the code (the link above contains a workaround). However, the IDE version of Convex, avaliable on GitHub before the challenge was posted, does not have this bug. Here is a link to the IDE version that was avaliable before the challenge was posted: Convex IDE.

Title: Write a Sine-Deriving Machine

Body:
Convex (IDE version only), 6 bytes

P½*+ms

Try it online!

After futher investigation, with the help of Dennis in chat, it was found that the command-line version of Convex (what TIO uses) has a bug that breaks the code (the link above contains a workaround). However, the IDE version of Convex, avaliable on GitHub before the challenge was posted, does not have this bug. Here is a link to the IDE version that was avaliable before the challenge was posted: Convex IDE.


答:
Mathematica 14 bytes

With help from Martin Ender,

```<code>Sin[#2+Pi/2#]&
</code>```

Title: Write a Sine-Deriving Machine

Body:
Mathematica 14 bytes

With help from Martin Ender,

Sin[#2+Pi/2#]&


问:
Golf a Brain-Flak Integer
Integers are tedious to represent in Brain-Flak. There are 8 operators:

```<code>()      Evaluates to 1, but does not push anything on any stack
[]      Evaluates to an indeterminate value for the purposes of this question
{}      Removes the top of the stack and evaluates to it
<>      Switches to or back from the alternate stack and evaluates to zero
(foo)   Pushes the value of the expression foo to the stack and evaluates to it
[foo]   Evaluates to the negation of foo
{foo}   Evaluates the expression foo until the top of the stack is zero
<foo>   Evaluates to zero but executes foo anyway
</code>```

foo may consist of multiple operators, in which case they are evaluated and summed. For example (()()) pushes 2 to the stack (and evaluates to 2 too).

Obviously, the (()...()) mechanism is not useful in Code Golf as large numbers would take n*2+2 bytes to represent. Your challenge is therefore to write a program or function that will output in as few bytes as possible a Brain-Flak program that will push a given positive integer n to the active stack. This program must not make any assumptions about the existing contents of the stacks, so it must not leave the stacks exchanged or add or remove extra values from the stacks.

Although your program or function must be capable of returning a working Brain-Flak program for all inputs from 1 to 1,000,000 the winner will be the program or function that generates the smallest set of appropriate Brain-Flak programs for all 1061 prime numbers between 1,000 and 10,000. You should note the total size of your outputs for those 1061 inputs as part of your submission. Your program or function may accept the integer and return the (string) Brain-Flak program in any of the usual acceptable I/O formats. Ties will be broken using the size of your program or function.

答:
Python 2, <s>59394</s> <s>59244</s> <s>58534</s> <s>58416</s> <s>58394</s> 58250

Ok here is my solution.

import re
import math

cache = {0:"<()>"}

def find(x,i,j):
    return i*((x**2+x)/2)+(j+1)*((x**2-x)/2)

def solve(x, i, j):
    a = (i + j + 1)/2.
    b = (i - j - 1)/2.
    c = -x
    return (-b + math.sqrt(b**2 - 4*a*c))/(2*a)

def size(i,j=0):
    return 4*(i+j)+14

def polynomials(n):
    upperBound = int(4*math.log(n,2))
    i = 0
    answers = []
    while size(i) < upperBound:
        for j in range(i):
            sol = int(solve(n, i-j, j)+.5)
            if find(sol, i-j, j) == n:
                answers.append((sol, i-j, j))
        i += 1
    return answers

def complement(character):
        dict = {"(":")","{":"}","<":">","[":"]",")":"(","}":"{",">":"<","]":"["}
        return dict[character]

def findMatch(snippet, index):
        increment = 1 if snippet[index] in "({<[" else -1
        stack = []
        if snippet[index] in "(){}<>[]":
                stack.append(snippet[index])
        while len(stack) > 0 and index + increment < len(snippet):
                index += increment
                if snippet[index] in "(){}<>[]":
                        if complement(snippet[index]) == stack[-1]:
                                stack = stack[:-1]
                        else:
                                stack.append(snippet[index])
        return index

def isPrime(n):
    return not [0 for x in range(2,int(n**.5)+1) if n%x==0] and n>1

def getPrimeFactors(n):
    return [x for x in range(2,n/2) if n%x==0 and isPrime(x)]

def divHardcode(n,m):
    assert n%m == 0
    assert m != 1
    assert n != 1
    binary = bin(m)[3:]
    return (binary.count("1")+len(binary))*"("+getBF(n/m)+")"*binary.count("1")+binary.replace("1","){}{}").replace("0","){}")

def isTriangular(n):
    #Triangles must be between sqrt(2n) and cbrt(2n)
    if n < 0: return isTriangular(-n)
    for x in range(int((2*n)**(1/3.)),int((2*n)**.5)+1):
        if (x**2+x) == 2*n:
            return True
    return False

def getTriangle(n):
    if n < 0: return -getTriangle(-n)
    #Triangles must be between sqrt(2n) and cbrt(2n)
    for x in range(int((2*n)**(1/3.)),int((2*n)**.5)+1):
        if (x**2+x) == 2*n:
            return x
    #If we don't find one we made a mistake
    assert False

def getSimpleBF(n):
    if n in cache:return cache[n]
    if n < 0:
        # There is room for better solutions here
        return "["+getSimpleBF(-n)+"]"
    elif n == 0:
        return ""
    elif n < 6:
        return "()"*n
    #Non-edge cases
    solutions = []
    factors = getPrimeFactors(n)
    if n >= 78 and isTriangular(n):
        solutions.append(
           min([push(getTriangle(n))+"{({}[()])}{}","<"+push(getTriangle(n)+1)+">{({}[()])}{}"],key=len)
        )
    polynomialSolutions = polynomials(n)
    for polynomial in polynomialSolutions:
        solutions.append("<%s>{%s({}[()])%s}{}"%(push(polynomial[0]),"({})"*polynomial[1],"({})"*polynomial[2]))
        #Mod 3 tricks
    if n % 3 == 2:
       solutions.append(("((%s)()){}{}")%getBF(n/3))
    elif n % 3 == 1:
       solutions.append(("((%s)()()){}{}")%getBF(n/3-1))
    #Basic solutions
    if isPrime(n):
        solutions.append(getSimpleBF(n-1) + "()")
    else:
        #TODO multithread
        solutions += map(lambda m:divHardcode(n,m),factors)
    return min(solutions,key=lambda x:len(unpack(x)))

def getBF(n):
    if n in cache: return cache[n]
    result = getSimpleBF(n)
    index = n - 1
    while index > n-(len(result)/2):
        score = getSimpleBF(index)+getSimpleBF(n-index)
        if len(score) < len(result):result = score
        index -= 1
    index = n + 1
    while index < n+(len(result)/2):
        score = getSimpleBF(index)+getSimpleBF(n-index)
        if len(score) < len(result):result = score
        index += 1
    cache[n] = result
    return result

def unpack(string):
    reMatch = re.match("\(*<",string)
    if reMatch:
        location =reMatch.span()
        return string[location[1]:findMatch(string,location[1]-1)] +string[:location[1]-1] + string[findMatch(string,location[1]-1)+1:]
    return string

def push(n):
    return unpack("("+getBF(n)+")")

def kolmo(string):
    code = push(ord(string[-1]))
    stringVector = map(ord,string)
    for x,y in zip(stringVector[-1:0:-1],stringVector[-2::-1]):
        code = "("+code+getBF(y-x)+")"
    code = code.replace("<()>)",")")
    return code

def kolmo(stringVector):
    code = push(stringVector[-1])
    for x,y in zip(stringVector[-1:0:-1],stringVector[-2::-1]):
        code = "("+code+getBF(y-x)+")"
    code = code.replace("<()>)",")")
    return code

if __name__ == "__main__":
    import primes
    sum = 0
    for prime in primes.nums:
        print push(prime)
        sum += len(push(prime))
    print sum
```

The relevant function is push(n). To call it simply call push on the integer you wish to represent.

Explanation

The main optimization done by the program is multiplication hard-coding.  The idea of multiplication hardcoding is pretty simple.  You push the a number and then pop and push it to create a new value.  For example to multiply by two you can use the following code ((n){}) where n code producing a specific number.  This works because both (n) and {} have a value of n.

This simple idea can be made more complex for larger numbers.  Take for instance 5 it was discovered a while ago that the best way to multiply by five was (((n)){}){}{}.  This code makes two copies of the n multiplies one by 4 and adds the two.  Using the same strategy I make every multiplication based on a number's binary representation.  I won't get into the details of how this works right now but I do this by chopping off the first one of the binary representation and replacing 0 with ){} and 1 with ){}{}.  It then makes sure that n is pushed the appropriate number of times and balances all the parentheses.  (If you want to know how this is done you can look at my code).  If you want to know why this works just ask me in a comment.  I don't think anyone actually reads all the updates to my post so I left the explanation out.

When the algorithm attempts to find a multiplication hardcode it attempts all of a numbers prime factors.  It ignores composite factors because at one point composite factors could always be expressed more concisely as its own prime factors it is not known if this is still true.

The other byte saving mechanism is a polynomial solution finder.  There are certain forms of polynomials that are easy to represent with decrementing loops.  These polynomials include, but are not limited to, polygonal numbers. This optimization finds polynomials that fit the form and creates the code that makes them.

Output

paste-bin

Title: Golf a Brain-Flak Integer

Body:
Python 2, <s>59394</s> <s>59244</s> <s>58534</s> <s>58416</s> <s>58394</s> 58250

Ok here is my solution.

import re
import math

cache = {0:"<()>"}

def find(x,i,j):
    return i*((x**2+x)/2)+(j+1)*((x**2-x)/2)

def solve(x, i, j):
    a = (i + j + 1)/2.
    b = (i - j - 1)/2.
    c = -x
    return (-b + math.sqrt(b**2 - 4*a*c))/(2*a)

def size(i,j=0):
    return 4*(i+j)+14

def polynomials(n):
    upperBound = int(4*math.log(n,2))
    i = 0
    answers = []
    while size(i) < upperBound:
        for j in range(i):
            sol = int(solve(n, i-j, j)+.5)
            if find(sol, i-j, j) == n:
                answers.append((sol, i-j, j))
        i += 1
    return answers

def complement(character):
        dict = {"(":")","{":"}","<":">","[":"]",")":"(","}":"{",">":"<","]":"["}
        return dict[character]

def findMatch(snippet, index):
        increment = 1 if snippet[index] in "({<[" else -1
        stack = []
        if snippet[index] in "(){}<>[]":
                stack.append(snippet[index])
        while len(stack) > 0 and index + increment < len(snippet):
                index += increment
                if snippet[index] in "(){}<>[]":
                        if complement(snippet[index]) == stack[-1]:
                                stack = stack[:-1]
                        else:
                                stack.append(snippet[index])
        return index

def isPrime(n):
    return not [0 for x in range(2,int(n**.5)+1) if n%x==0] and n>1

def getPrimeFactors(n):
    return [x for x in range(2,n/2) if n%x==0 and isPrime(x)]

def divHardcode(n,m):
    assert n%m == 0
    assert m != 1
    assert n != 1
    binary = bin(m)[3:]
    return (binary.count("1")+len(binary))*"("+getBF(n/m)+")"*binary.count("1")+binary.replace("1","){}{}").replace("0","){}")

def isTriangular(n):
    #Triangles must be between sqrt(2n) and cbrt(2n)
    if n < 0: return isTriangular(-n)
    for x in range(int((2*n)**(1/3.)),int((2*n)**.5)+1):
        if (x**2+x) == 2*n:
            return True
    return False

def getTriangle(n):
    if n < 0: return -getTriangle(-n)
    #Triangles must be between sqrt(2n) and cbrt(2n)
    for x in range(int((2*n)**(1/3.)),int((2*n)**.5)+1):
        if (x**2+x) == 2*n:
            return x
    #If we don't find one we made a mistake
    assert False

def getSimpleBF(n):
    if n in cache:return cache[n]
    if n < 0:
        # There is room for better solutions here
        return "["+getSimpleBF(-n)+"]"
    elif n == 0:
        return ""
    elif n < 6:
        return "()"*n
    #Non-edge cases
    solutions = []
    factors = getPrimeFactors(n)
    if n >= 78 and isTriangular(n):
        solutions.append(
           min([push(getTriangle(n))+"{({}[()])}{}","<"+push(getTriangle(n)+1)+">{({}[()])}{}"],key=len)
        )
    polynomialSolutions = polynomials(n)
    for polynomial in polynomialSolutions:
        solutions.append("<%s>{%s({}[()])%s}{}"%(push(polynomial[0]),"({})"*polynomial[1],"({})"*polynomial[2]))
        #Mod 3 tricks
    if n % 3 == 2:
       solutions.append(("((%s)()){}{}")%getBF(n/3))
    elif n % 3 == 1:
       solutions.append(("((%s)()()){}{}")%getBF(n/3-1))
    #Basic solutions
    if isPrime(n):
        solutions.append(getSimpleBF(n-1) + "()")
    else:
        #TODO multithread
        solutions += map(lambda m:divHardcode(n,m),factors)
    return min(solutions,key=lambda x:len(unpack(x)))

def getBF(n):
    if n in cache: return cache[n]
    result = getSimpleBF(n)
    index = n - 1
    while index > n-(len(result)/2):
        score = getSimpleBF(index)+getSimpleBF(n-index)
        if len(score) < len(result):result = score
        index -= 1
    index = n + 1
    while index < n+(len(result)/2):
        score = getSimpleBF(index)+getSimpleBF(n-index)
        if len(score) < len(result):result = score
        index += 1
    cache[n] = result
    return result

def unpack(string):
    reMatch = re.match("\(*<",string)
    if reMatch:
        location =reMatch.span()
        return string[location[1]:findMatch(string,location[1]-1)] +string[:location[1]-1] + string[findMatch(string,location[1]-1)+1:]
    return string

def push(n):
    return unpack("("+getBF(n)+")")

def kolmo(string):
    code = push(ord(string[-1]))
    stringVector = map(ord,string)
    for x,y in zip(stringVector[-1:0:-1],stringVector[-2::-1]):
        code = "("+code+getBF(y-x)+")"
    code = code.replace("<()>)",")")
    return code

def kolmo(stringVector):
    code = push(stringVector[-1])
    for x,y in zip(stringVector[-1:0:-1],stringVector[-2::-1]):
        code = "("+code+getBF(y-x)+")"
    code = code.replace("<()>)",")")
    return code

if __name__ == "__main__":
    import primes
    sum = 0
    for prime in primes.nums:
        print push(prime)
        sum += len(push(prime))
    print sum

The relevant function is push(n). To call it simply call push on the integer you wish to represent.

Explanation

The main optimization done by the program is multiplication hard-coding.  The idea of multiplication hardcoding is pretty simple.  You push the a number and then pop and push it to create a new value.  For example to multiply by two you can use the following code ((n){}) where n code producing a specific number.  This works because both (n) and {} have a value of n.

This simple idea can be made more complex for larger numbers.  Take for instance 5 it was discovered a while ago that the best way to multiply by five was (((n)){}){}{}.  This code makes two copies of the n multiplies one by 4 and adds the two.  Using the same strategy I make every multiplication based on a number's binary representation.  I won't get into the details of how this works right now but I do this by chopping off the first one of the binary representation and replacing 0 with ){} and 1 with ){}{}.  It then makes sure that n is pushed the appropriate number of times and balances all the parentheses.  (If you want to know how this is done you can look at my code).  If you want to know why this works just ask me in a comment.  I don't think anyone actually reads all the updates to my post so I left the explanation out.

When the algorithm attempts to find a multiplication hardcode it attempts all of a numbers prime factors.  It ignores composite factors because at one point composite factors could always be expressed more concisely as its own prime factors it is not known if this is still true.

The other byte saving mechanism is a polynomial solution finder.  There are certain forms of polynomials that are easy to represent with decrementing loops.  These polynomials include, but are not limited to, polygonal numbers. This optimization finds polynomials that fit the form and creates the code that makes them.

Output

paste-bin


答:
C (gcc), 53 46 45 bytes

#import<math.h>
#define f(x,n)sin(x+M_PI/2*n)
```

Probably Ideone doesn't have glibc, says M_PI is undeclared.

Title: Write a Sine-Deriving Machine

Body:
C (gcc), 53 46 45 bytes

#import<math.h>
#define f(x,n)sin(x+M_PI/2*n)

Probably Ideone doesn't have glibc, says M_PI is undeclared.


答:
Python 2, 69 bytes

```<code>print'''OPQRSTU
NQPONMV
MREDCLW
LSFABKX
KTGHIJY
JUVWXYZA
IHGFEDCB'''
</code>```

Just do it...

Title: Alphabet Spiral

Body:
Python 2, 69 bytes

print'''OPQRSTU
NQPONMV
MREDCLW
LSFABKX
KTGHIJY
JUVWXYZA
IHGFEDCB'''

Just do it...


答:
Python - 58 chars

Slightly shorter than ugoren's, by taking a set as input:

```<code>p=lambda x:x and[[y]+l for y in x for l in p(x-{y})]or[[]]
</code>```

Title: Code-Golf: Permutations

Body:
Write a function that takes as input a set of integers (can be a list, array or any other container with distinct numbers), and outputs the list of all its permutations.

Python (95 chars):

```<code>p=lambda s:s and sum(map(lambda e:map(lambda p:[e]+p,p(filter(lambda x:x!=e,s))),s),[]) or [[]]</code>```

It'd be nice to be beaten in the same language, but implementations in other languages are more than welcome!

Body:
Python - 58 chars

Slightly shorter than ugoren's, by taking a set as input:

p=lambda x:x and[[y]+l for y in x for l in p(x-{y})]or[[]]


Title: Alphabet Spiral

Body:
Bubblegum, 47 bytes

A hex dump, courtesy of xxd:

00000000: 520a adf6 2e08 7444 c41e c8ff 4096 ca2d  R.....tD....@..-
00000010: 8832 2297 8cd7 1bb1 fe10 43ce 39cc 8e5f  .2".......C.9.._
00000020: 31f7 3d63 432e d3f3 3873 ecf7 7641 a3    1.=cC...8s..vA.

(This is just the spiral, “compressed”.)

Try it online.


答:
Actually, 5 bytes

```<code>╦*½+S
</code>```

Try it online

Takes input as t\nx.

Explanation:

```<code>╦*½+S
╦*     pi*n
  ½    half that
   +   add t
    S  sine
</code>```

Title: Write a Sine-Deriving Machine

Body:
Actually, 5 bytes

╦*½+S

Try it online

Takes input as t\nx.

Explanation:

╦*½+S
╦*     pi*n
  ½    half that
   +   add t
    S  sine


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

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

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

The above rectangle would give a score of 5.

Rules:

Overlapping multiple letters in a word is allowed

Words can go in any of the 8 directions

Words cannot wrap around

You can use any character for the empty locations

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

答:
C++, 34191 character "grid" (with minimal human intervention, 6 or 7 can easily be saved)

This should be taken more as a bound for the 2D case, because the answer is still a 1D string. It's just my code from the previous challenge, but with the new ability to reverse any string. This gives us a lot more scope for combining words (particularly because it caps the worst case of non-overlapping superstrings to 26; one for each letter of the alphabet).

For some slight 2D visual appeal, it puts linebreaks in the result if it can do so for free (i.e. between 0-overlap words).

Pretty slow (still no caching). Here's the code:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

std::size_t calcOverlap(const std::string &a, const std::string &b, std::size_t limit, std::size_t minimal) {
    std::size_t la = a.size();
    for(std::size_t p = std::min(std::min(la, b.size()), limit + 1); -- p > minimal; ) {
        if(a.compare(la - p, p, b, 0, p) == 0) {
            return p;
        }
    }
    return 0;
}

bool isSameReversed(const std::string &a, const std::string &b) {
    std::size_t l = a.size();
    if(b.size() != l) {
        return false;
    }
    for(std::size_t i = 0; i < l; ++ i) {
        if(a[i] != b[l-i-1]) {
            return false;
        }
    }
    return true;
}

int main() {
    std::vector<std::string> words;

    // Load all words from input and their reverses (words can be backwards now)
    while(true) {
        std::string word;
        std::getline(std::cin, word);
        if(word.empty()) {
            break;
        }
        words.push_back(word);
        std::reverse(word.begin(), word.end());
        words.push_back(std::move(word));
    }

    std::cerr
        << "Input word count: " << words.size() << std::endl;

    // Remove all fully subsumed words

    for(auto p = words.begin(); p != words.end(); ) {
        bool subsumed = false;
        for(auto i = words.begin(); i != words.end(); ++ i) {
            if(i == p) {
                continue;
            }
            if(i->find(*p) != std::string::npos) {
                subsumed = true;
                break;
            }
        }
        if(subsumed) {
            p = words.erase(p);
        } else {
            ++ p;
        }
    }

    std::cerr
        << "After subsuming checks: " << words.size()
        << std::endl;

    // Sort words longest-to-shortest (not necessary but doesn't hurt. Makes finding maxlen a tiny bit easier)
    std::sort(words.begin(), words.end(), [](const std::string &a, const std::string &b) {
        return a.size() > b.size();
    });

    std::size_t maxlen = words.front().size();

    // Repeatedly combine most-compatible words until we have only 1 word left (+ its reverse)
    std::size_t bestPossible = maxlen - 1;
    while(words.size() > 2) {
        auto bestA = words.begin();
        auto bestB = -- words.end();
        std::size_t bestOverlap = 0;
        for(auto p = ++ words.begin(), e = words.end(); p != e; ++ p) {
            if(p->size() - 1 <= bestOverlap) {
                continue;
            }
            for(auto q = words.begin(); q != p; ++ q) {
                std::size_t overlap = calcOverlap(*p, *q, bestPossible, bestOverlap);
                if(overlap > bestOverlap && !isSameReversed(*p, *q)) {
                    bestA = p;
                    bestB = q;
                    bestOverlap = overlap;
                }
                overlap = calcOverlap(*q, *p, bestPossible, bestOverlap);
                if(overlap > bestOverlap && !isSameReversed(*p, *q)) {
                    bestA = q;
                    bestB = p;
                    bestOverlap = overlap;
                }
            }
            if(bestOverlap == bestPossible) {
                break;
            }
        }
        std::string newStr = std::move(*bestA);
        if(bestOverlap == 0) {
            newStr.push_back('\n');
        }
        newStr.append(*bestB, bestOverlap, std::string::npos);

        if(bestA == -- words.end()) {
            words.pop_back();
            *bestB = std::move(words.back());
            words.pop_back();
        } else {
            *bestB = std::move(words.back());
            words.pop_back();
            *bestA = std::move(words.back());
            words.pop_back();
        }

        // Remove any words which are now in the result (forward or reverse)
        // (would not be necessary if we didn't have the reversed forms too)
        std::string newRev = newStr;
        std::reverse(newRev.begin(), newRev.end());
        for(auto p = words.begin(); p != words.end(); ) {
            if(newStr.find(*p) != std::string::npos || newRev.find(*p) != std::string::npos) {
                std::cerr << "Now subsumes: " << *p << std::endl;
                p = words.erase(p);
            } else {
                ++ p;
            }
        }

        std::cerr
            << "Words remaining: " << (words.size() + 1)
            << " Latest combination: (" << bestOverlap << ") " << newStr
            << std::endl;

        words.push_back(std::move(newStr));
        words.push_back(std::move(newRev));
        bestPossible = bestOverlap; // Merging existing words will never make longer merges possible
    }

    std::cerr
        << "After non-trivial merging: " << words.size()
        << std::endl;

    if(words.size() == 2 && !isSameReversed(words.front(), words.back())) {
        // must be 2 palindromes, so just join them
        words.front().append(words.back());
    }

    std::string result = words.front();

    std::cout
        << result
        << std::endl;
    std::cerr
        << "Word size: " << result.size() // Note this number includes newlines, so to get the grid size according to the rules, subtract newlines manually
        << std::endl;
    return 0;
}
```

Result: http://pastebin.com/UTe2WMcz (4081 characters less than the previous challenge)

It's pretty clear that some trivial savings can be made by putting the xd and wv lines vertical, intersecting the monster line. Then hhidetautisbneudui can intersect with the d, and lxwwwowaxocnnaesdda with w. This saves 4 characters. nbcllilhn can be substituted in to an existing s overlap (if one can be found) to save another 2 (or just 1 if no such overlap exists and it must be added vertically instead). Finally mjjrajaytq can be added vertically somewhere to save 1. This means with minimal human intervention, 6–7 characters can be saved from the result.

I would like to get this into 2D with the following method, but I'm struggling to find a way to implement it without making the algorithm O(n^4), which is quite impractical to compute!

Run the algorithm as above, but stop short when the overlaps reach 1 character

Repeatedly:

Find a group of 4 words which can be arranged into a rectangle

Add as many words as possible on top of this rectangle where each word overlaps at least 2 characters of the current shape (check all 8 directions) — this is the only stage where we can actually get an advantage over the current code

Combine the resulting grids and lone-words looking for single-letter overlaps each time

Title: Minimal Word Search

Body:
C++, 34191 character "grid" (with minimal human intervention, 6 or 7 can easily be saved)

This should be taken more as a bound for the 2D case, because the answer is still a 1D string. It's just my code from the previous challenge, but with the new ability to reverse any string. This gives us a lot more scope for combining words (particularly because it caps the worst case of non-overlapping superstrings to 26; one for each letter of the alphabet).

For some slight 2D visual appeal, it puts linebreaks in the result if it can do so for free (i.e. between 0-overlap words).

Pretty slow (still no caching). Here's the code:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

std::size_t calcOverlap(const std::string &a, const std::string &b, std::size_t limit, std::size_t minimal) {
    std::size_t la = a.size();
    for(std::size_t p = std::min(std::min(la, b.size()), limit + 1); -- p > minimal; ) {
        if(a.compare(la - p, p, b, 0, p) == 0) {
            return p;
        }
    }
    return 0;
}

bool isSameReversed(const std::string &a, const std::string &b) {
    std::size_t l = a.size();
    if(b.size() != l) {
        return false;
    }
    for(std::size_t i = 0; i < l; ++ i) {
        if(a[i] != b[l-i-1]) {
            return false;
        }
    }
    return true;
}

int main() {
    std::vector<std::string> words;

    // Load all words from input and their reverses (words can be backwards now)
    while(true) {
        std::string word;
        std::getline(std::cin, word);
        if(word.empty()) {
            break;
        }
        words.push_back(word);
        std::reverse(word.begin(), word.end());
        words.push_back(std::move(word));
    }

    std::cerr
        << "Input word count: " << words.size() << std::endl;

    // Remove all fully subsumed words

    for(auto p = words.begin(); p != words.end(); ) {
        bool subsumed = false;
        for(auto i = words.begin(); i != words.end(); ++ i) {
            if(i == p) {
                continue;
            }
            if(i->find(*p) != std::string::npos) {
                subsumed = true;
                break;
            }
        }
        if(subsumed) {
            p = words.erase(p);
        } else {
            ++ p;
        }
    }

    std::cerr
        << "After subsuming checks: " << words.size()
        << std::endl;

    // Sort words longest-to-shortest (not necessary but doesn't hurt. Makes finding maxlen a tiny bit easier)
    std::sort(words.begin(), words.end(), [](const std::string &a, const std::string &b) {
        return a.size() > b.size();
    });

    std::size_t maxlen = words.front().size();

    // Repeatedly combine most-compatible words until we have only 1 word left (+ its reverse)
    std::size_t bestPossible = maxlen - 1;
    while(words.size() > 2) {
        auto bestA = words.begin();
        auto bestB = -- words.end();
        std::size_t bestOverlap = 0;
        for(auto p = ++ words.begin(), e = words.end(); p != e; ++ p) {
            if(p->size() - 1 <= bestOverlap) {
                continue;
            }
            for(auto q = words.begin(); q != p; ++ q) {
                std::size_t overlap = calcOverlap(*p, *q, bestPossible, bestOverlap);
                if(overlap > bestOverlap && !isSameReversed(*p, *q)) {
                    bestA = p;
                    bestB = q;
                    bestOverlap = overlap;
                }
                overlap = calcOverlap(*q, *p, bestPossible, bestOverlap);
                if(overlap > bestOverlap && !isSameReversed(*p, *q)) {
                    bestA = q;
                    bestB = p;
                    bestOverlap = overlap;
                }
            }
            if(bestOverlap == bestPossible) {
                break;
            }
        }
        std::string newStr = std::move(*bestA);
        if(bestOverlap == 0) {
            newStr.push_back('\n');
        }
        newStr.append(*bestB, bestOverlap, std::string::npos);

        if(bestA == -- words.end()) {
            words.pop_back();
            *bestB = std::move(words.back());
            words.pop_back();
        } else {
            *bestB = std::move(words.back());
            words.pop_back();
            *bestA = std::move(words.back());
            words.pop_back();
        }

        // Remove any words which are now in the result (forward or reverse)
        // (would not be necessary if we didn't have the reversed forms too)
        std::string newRev = newStr;
        std::reverse(newRev.begin(), newRev.end());
        for(auto p = words.begin(); p != words.end(); ) {
            if(newStr.find(*p) != std::string::npos || newRev.find(*p) != std::string::npos) {
                std::cerr << "Now subsumes: " << *p << std::endl;
                p = words.erase(p);
            } else {
                ++ p;
            }
        }

        std::cerr
            << "Words remaining: " << (words.size() + 1)
            << " Latest combination: (" << bestOverlap << ") " << newStr
            << std::endl;

        words.push_back(std::move(newStr));
        words.push_back(std::move(newRev));
        bestPossible = bestOverlap; // Merging existing words will never make longer merges possible
    }

    std::cerr
        << "After non-trivial merging: " << words.size()
        << std::endl;

    if(words.size() == 2 && !isSameReversed(words.front(), words.back())) {
        // must be 2 palindromes, so just join them
        words.front().append(words.back());
    }

    std::string result = words.front();

    std::cout
        << result
        << std::endl;
    std::cerr
        << "Word size: " << result.size() // Note this number includes newlines, so to get the grid size according to the rules, subtract newlines manually
        << std::endl;
    return 0;
}

Result: http://pastebin.com/UTe2WMcz (4081 characters less than the previous challenge)

It's pretty clear that some trivial savings can be made by putting the xd and wv lines vertical, intersecting the monster line. Then hhidetautisbneudui can intersect with the d, and lxwwwowaxocnnaesdda with w. This saves 4 characters. nbcllilhn can be substituted in to an existing s overlap (if one can be found) to save another 2 (or just 1 if no such overlap exists and it must be added vertically instead). Finally mjjrajaytq can be added vertically somewhere to save 1. This means with minimal human intervention, 6–7 characters can be saved from the result.

I would like to get this into 2D with the following method, but I'm struggling to find a way to implement it without making the algorithm O(n^4), which is quite impractical to compute!

Run the algorithm as above, but stop short when the overlaps reach 1 character

Repeatedly:

Find a group of 4 words which can be arranged into a rectangle

Add as many words as possible on top of this rectangle where each word overlaps at least 2 characters of the current shape (check all 8 directions) — this is the only stage where we can actually get an advantage over the current code

Combine the resulting grids and lone-words looking for single-letter overlaps each time


答:
R, 26 bytes

```<code>function(t,x)sin(t+pi/2*x)
</code>```

Exactly what it says on the tin...

Title: Write a Sine-Deriving Machine

Body:
R, 26 bytes

function(t,x)sin(t+pi/2*x)

Exactly what it says on the tin...


答:
Julia, 17 bytes

x\t=x*π/2+t|>sin
```

Try it online!

Title: Write a Sine-Deriving Machine

Body:
Julia, 17 bytes

x\t=x*π/2+t|>sin

Try it online!


答:
ListSharp, 326 bytes

```<code>STRG a=READ[<here>+"\\a.txt"]
ROWS p=ROWSPLIT a BY ["\r\n"]
ROWS p=GETLINES p [1 TO p LENGTH-1]
ROWS p=p+p[1]+p[0]
STRG o=p[0]
ROWS y=EXTRACT COLLUM[2] FROM p SPLIT BY [""]
ROWS x=EXTRACT COLLUM[3] FROM p SPLIT BY [""]
[FOREACH NUMB IN 1 TO o LENGTH-1 AS i]
ROWS m=COMBINE[m,x] WITH [""]
ROWS m=COMBINE[y,m,y] WITH [""]
SHOW=m
</code>```

I definitely need to add the nesting of functions, but this works very well

comment if you want an explanation

Title: Automatic box expander

Body:
Introduction

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

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

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

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

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

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

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

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

We expand this by one, so we get:

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

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

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

Becomes:

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

Now we reassemble the box, which results into:

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

The task

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

Test cases

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

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

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

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

Body:
ListSharp, 326 bytes

STRG a=READ[<here>+"\\a.txt"]
ROWS p=ROWSPLIT a BY ["\r\n"]
ROWS p=GETLINES p [1 TO p LENGTH-1]
ROWS p=p+p[1]+p[0]
STRG o=p[0]
ROWS y=EXTRACT COLLUM[2] FROM p SPLIT BY [""]
ROWS x=EXTRACT COLLUM[3] FROM p SPLIT BY [""]
[FOREACH NUMB IN 1 TO o LENGTH-1 AS i]
ROWS m=COMBINE[m,x] WITH [""]
ROWS m=COMBINE[y,m,y] WITH [""]
SHOW=m

I definitely need to add the nesting of functions, but this works very well

comment if you want an explanation