答:
Python 2, 72 bytes

```<code>lambda x:x[:-1]+(" .","\/","/\\")[ord(x[-1])/46+(-1,1)[ord(x[-1])%46>0]]
</code>```

Any help golfing more would be greatly appreciated!

This takes the last character in the input and converts it into its ASCII code to get the corresponding index in the list of two characters. Those two characters are appended to all the characters of the input up until the last one.

Body:
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:

. →  .

 . →   .

  . →    .

   . →     .

    . →      .

     . →       .

      . →        .

       . →         .

In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

/ → /\

\ → \/

/\ → /\/

\/ → \/\

/\/ → /\/\

\/\ → \/\/

/\/\ → /\/\/

\/\/ → \/\/\

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

The shortest code in bytes wins.

Body:
Python 2, 72 bytes

lambda x:x[:-1]+(" .","\/","/\\")[ord(x[-1])/46+(-1,1)[ord(x[-1])%46>0]]

Any help golfing more would be greatly appreciated!

This takes the last character in the input and converts it into its ASCII code to get the corresponding index in the list of two characters. Those two characters are appended to all the characters of the input up until the last one.


问:
Wave-Particle Duality Laterally Programmatically
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:

. →  .

 . →   .

  . →    .

   . →     .

    . →      .

     . →       .

      . →        .

       . →         .

In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

/ → /\

\ → \/

/\ → /\/

\/ → \/\

/\/ → /\/\

\/\ → \/\/

/\/\ → /\/\/

\/\/ → \/\/\

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

The shortest code in bytes wins.

ContentLicense: CC BY-SA 3.0

Body:
C#, <s>80</s> 63 bytes

s=>{var c=s[s.Length-1];return c<'/'?" "+s:c>'/'?s+"/":s+"\\";}


问:
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.

答:
Python 3, 72 bytes

```<code>print('OPQRSTU\nNQPONMV\nMREDCLW\nLSFABKX\nKTGHIJY\nJUVWXYZA\nIHGFEDCB')
</code>```

Not exactly interesting, but it still works!

Title: Alphabet Spiral

Body:
Python 3, 72 bytes

print('OPQRSTU\nNQPONMV\nMREDCLW\nLSFABKX\nKTGHIJY\nJUVWXYZA\nIHGFEDCB')

Not exactly interesting, but it still works!


问:
Testing for admissible sequences
Executive summary: test whether an input sequence of integers is "admissible", meaning that it doesn't cover all residue classes for any modulus.

What is an "admissible" sequence?

Given an integer m ≥ 2, the residue classes modulo m are just the m possible arithmetic progressions of common difference m. For example, when m=4, the 4 residue classes modulo 4 are

```<code>..., -8, -4, 0, 4, 8, 12, ...
..., -7, -3, 1, 5, 9, 13, ...
..., -6, -2, 2, 6, 10, 14, ...
..., -5, -1, 3, 7, 11, 15, ...
</code>```

The kth residue class consists of all the integers whose remainder upon dividing by m equals k. (as long as one defines "remainder" correctly for negative integers)

A sequence of integers a1, a2, ..., ak is admissible modulo m if it fails to intersect at least one of the residue classes. For example, {0, 1, 2, 3} and {-4, 5, 14, 23} are not admissible modulo 4, but {0, 1, 2, 4} and {0, 1, 5, 9} and {0, 1, 2, -3} are admissible modulo 4. Also, {0, 1, 2, 3, 4} is not admissible modulo 4, while {0, 1, 2} is admissible modulo 4.

Finally, a sequence of integers is simply admissible if it is admissible modulo m for every integer m ≥ 2.

The challenge

Write a program or function that takes a sequence of integers as input, and returns a (consistent) Truthy value if the sequence is admissible and a (consistent) Falsy value if the sequence is not admissible.

The input sequence of integers can be in any reasonable format. You may assume that the input sequence has at least two integers. (You may also assume that the input integers are distinct if you want, though it probably doesn't help.) You must be able to handle positive and negative integers (and 0).

Usual code-golf scoring: the shortest answer, in bytes, wins.

Sample input

The following input sequences should each give a Truthy value:

```<code>0 2
-1 1
-100 -200
0 2 6
0 2 6 8
0 2 6 8 12
0 4 6 10 12
-60 0 60 120 180
0 2 6 8 12 26
11 13 17 19 23 29 31
-11 -13 -17 -19 -23 -29 -31
</code>```

The following input sequences should each give a Falsy value:

```<code>0 1
-1 4
-100 -201
0 2 4
0 2 6 10
0 2 6 8 14
7 11 13 17 19 23 29
-60 0 60 120 180 240 300
</code>```

Tips

Note that any sequence of 3 or fewer integers is automatically admissible modulo 4. More generally, a sequence of length k is automatically admissible modulo m when m > k. It follows that testing for admissibility really only requires checking a finite number of m.

Note also that 2 divides 4, and that any sequence that is admissible modulo 2 (that is, all even or all odd) is automatically admissible modulo 4. More generally, if m divides n and a sequence is admissible modulo m, then it is automatically admissible modulo n. To check admissibility, it therefore suffices to consider only prime m if you wish.

If a1, a2, ..., ak is an admissible sequence, then a1+c, a2+c, ..., ak+c is also admissible for any integer c (positive or negative).

Mathematical relevance (optional reading)

Let a1, a2, ..., ak be a sequence of integers. Suppose that there are infinitely many integers n such that n+a1, n+a2, ..., n+ak are all prime. Then it's easy to show that a1, a2, ..., ak must be admissible. Indeed, suppose that a1, a2, ..., ak is not admissible, and let m be a number such that a1, a2, ..., ak is not admissible modulo m. Then no matter what n we choose, one of the numbers n+a1, n+a2, ..., n+ak must be a multiple of m, hence cannot be prime.

The prime k-tuples conjecture is the converse of this statement, which is still a wide open problem in number theory: it asserts that if a1, a2, ..., ak is an admissible sequence (or k-tuple), then there should be infinitely many integers n such that n+a1, n+a2, ..., n+ak are all prime. For example, the admissible sequence 0, 2 yields the statement that there should be infinitely many integers n such that both n and n+2 are prime, this is the twin primes conjecture (still unproved).

答:
Python, 61 60 bytes

q=lambda l,d=2:d>len(l)or q(l,d+1)&(len({v%d for v in l})<d)
```

All test cases on ideone

Edit: replaced logical and with bitwise & to save one byte

Title: Testing for admissible sequences

Body:
Python, 61 60 bytes

q=lambda l,d=2:d>len(l)or q(l,d+1)&(len({v%d for v in l})<d)

All test cases on ideone

Edit: replaced logical and with bitwise & to save one byte


问:
Print alphabet without using strings
The challenge: Write a script to print the alphabet, but you can't use any ASCII strings in your program. Unicode escape characters are allowed (if thats what you call them).

External libraries are allowed, as long as a link to the documentation is provided, and an online example if possible.

As this is code-golf, the answer with the shortest byte count will win!

答:
Neoscript, 27 bytes

```<code>{|65:[]:90:map(chr):fuse()}
</code>```

Lambda returning the alphabet.

Title: Print alphabet without using strings

Body:
Neoscript, 27 bytes

{|65:[]:90:map(chr):fuse()}

Lambda returning the alphabet.


问:
Square free Numbers
Given a number N, write the shortest complete program to find the number of square-free integers below N.

```<code>Sample Input
100000
Sample Output
60794
</code>```

Constraints:

Should work for all positive N below 1,000,000

Should not take more than 10 secs.

Please do not use built in functions, please.

答:
Python - 105 bytes

s=input()
C=set()
for q in [k*k for k in range(2,s+1)]:
 i=1
 while q*i<=s:C.add(q*i);i+=1
print s-len(C)
```

ContentLicense: CC BY-SA 2.5

Title: Square free Numbers

ContentLicense: CC BY-SA 4.0


问:
Match up to 10 in an array

Challenge

Given an array of single digit number, work out if any 2 of them add up to 10 and print them out

Example

Input

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

This returns ((4,6),(5,5),(3,7))

Input

(1,2,3,4,5)

This returns (). as there is only one 5

Input

(5,5,5,5,5)

This returns ((5,5),(5,5)) as there is odd number of 5s and each 5 can be used only once

Rules

Here are the rules!

Assume input will only be an unsorted array of positive single digit integers

Each number will be pair up only once, which means if there are three 5s it only form 1 pair (5,5). If there are (3,3,7) it will only form 1 pair (3,7)

For the input: You can use any type of parentheses(or lack of) as long as readers can tell that the input is a single array of numbers.

For the output: It must look like an array of pairs. Where the array is the same form as your input.(If you did not use any parenheses in your input, you have to use some kind of symbols so that any readers can tell they are pairs in an array)

Test Cases

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

Good luck!

The shorter an answer is, the better!

Edit 1: update the rules and Testcases from comments

Edit 2: update rules to define format of input.

Edit 3: update rules to define format of output. trying to be as accommodating as possible.

答:
J, 54 53 50 46 45 44 characters

```<code>(>:,.9&-)I.<.4({.,-:@{::)(<.|.)+/|:(1+i.9)=/
</code>```

Usage:

```<code>   (>:,.9&-)I.<.4({.,-:@{::)(<.|.)+/|:(1+i.9)=/5 5 5 5 5
5 5
5 5
   (>:,.9&-)I.<.4({.,-:@{::)(<.|.)+/|:(1+i.9)=/9 8 7 6 4 4 3 1
1 9
3 7
4 6
</code>```

The algorithm is basically:

count the instance of each number +/|:(1+i.9)=/

pair the counts of each pair that would add to 10 (<.|.) (so 1 and 9, 2 and 8 etc.)

take the minimum of those counts  (so if you have three 9s but only one 1, you'll only have one 1 9 pair) and drop everything after the first five pairs

the 5s are a special case so divide that by 2 (<.4({.,-:@{::) implements both previous steps)

take the first five items of the list and output the number and 10-the number (>:,.9&-)I.

Title: Match up to 10 in an array

Body:
J, 54 53 50 46 45 44 characters

(>:,.9&-)I.<.4({.,-:@{::)(<.|.)+/|:(1+i.9)=/

Usage:

   (>:,.9&-)I.<.4({.,-:@{::)(<.|.)+/|:(1+i.9)=/5 5 5 5 5
5 5
5 5
   (>:,.9&-)I.<.4({.,-:@{::)(<.|.)+/|:(1+i.9)=/9 8 7 6 4 4 3 1
1 9
3 7
4 6

The algorithm is basically:

count the instance of each number +/|:(1+i.9)=/

pair the counts of each pair that would add to 10 (<.|.) (so 1 and 9, 2 and 8 etc.)

take the minimum of those counts  (so if you have three 9s but only one 1, you'll only have one 1 9 pair) and drop everything after the first five pairs

the 5s are a special case so divide that by 2 (<.4({.,-:@{::) implements both previous steps)

take the first five items of the list and output the number and 10-the number (>:,.9&-)I.


答:
Silicon, 1 byte

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

A is preinitialized to the alphabet. Output is implicit.

Title: Print alphabet without using strings

Body:
The challenge: Write a script to print the alphabet, but you can't use any ASCII strings in your program. Unicode escape characters are allowed (if thats what you call them).

External libraries are allowed, as long as a link to the documentation is provided, and an online example if possible.

As this is code-golf, the answer with the shortest byte count will win!

Body:
Silicon, 1 byte

A

A is preinitialized to the alphabet. Output is implicit.


问:
The infinitely admissable sequence
In this challenge we'll compute an infinite minimal admissible sequence.

The sequence for this challenge starts with a(1) = 1.

We continue this sequence by finding a(n) as the smallest possible number such that a(n) > a(n-1) and for every prime p, the set {a(i) mod p : 1 ≤ i ≤ n} has at most p-1 elements.

Write a program or function that takes positive integer n and outputs a(n). Shortest code in bytes wins.

Example:

a(6) is 19, rather than, say 17 because [1,3,7,9,13,19] (the previous terms) is admissible while [1,3,7,9,13,17] is not.

[1,3,7,9,13,17] is not admissible, because for the base 3, after taking the modulo of each term with 3, we obtain [1,0,1,0,1,2] which contains every non-negative number smaller than 3, our chosen base.

For [1,3,7,9,13,19] however, it would be impossible to come up with a base such that the list after modulo contains every non-negative integer smaller than such base.

Reference:

OEIS A020498

Testcases:

```<code>a(1) = 1
a(2) = 3
a(3) = 7
a(4) = 9
a(5) = 13
a(6) = 19
a(7) = 21
a(8) = 27
a(9) = 31
a(10) = 33
a(100) = 583
</code>```

答:
Brachylog, 44 bytes

```<code>-:[1]r:[1]cit.
t<gX=:?rc.'(l:2eLg:.rz:%adlL)
</code>```

Try it online!

100 takes about a minute here, so be patient if you want to try 100.

Predicate 0 (main predicate)

```<code>-:[1]r:[1]cit.
-:[1]r:[1]c     create array [[1], input-1, 1]
           i    iterate: [1] as input, iterate (input-1) times, predicate 1
            t.  last element is the output
</code>```

Predicate 1 (auxiliary predicate)

```<code>t<gX=:?rc.'(l:2eLg:.rz:%adlL)
t<                              last element of input < Temp
  gX                            [Temp] = X
   X=                           Assign a value to X, which assigns
                                a value to Temp
   X :?rc.                      [Input,X] concatenated is output
         .'(                )   The following about the output cannot
                                be proven:
            l:2eL                   L is a number between 2 and length
                                    of output, inclusive
                Lg:.rz:%a           every element of output, taken modulo L,
                         dlL        after removing duplicates, has length L
</code>```

Title: The infinitely admissable sequence

Body:
Brachylog, 44 bytes

-:[1]r:[1]cit.
t<gX=:?rc.'(l:2eLg:.rz:%adlL)

Try it online!

100 takes about a minute here, so be patient if you want to try 100.

Predicate 0 (main predicate)

-:[1]r:[1]cit.
-:[1]r:[1]c     create array [[1], input-1, 1]
           i    iterate: [1] as input, iterate (input-1) times, predicate 1
            t.  last element is the output

Predicate 1 (auxiliary predicate)

t<gX=:?rc.'(l:2eLg:.rz:%adlL)
t<                              last element of input < Temp
  gX                            [Temp] = X
   X=                           Assign a value to X, which assigns
                                a value to Temp
   X :?rc.                      [Input,X] concatenated is output
         .'(                )   The following about the output cannot
                                be proven:
            l:2eL                   L is a number between 2 and length
                                    of output, inclusive
                Lg:.rz:%a           every element of output, taken modulo L,
                         dlL        after removing duplicates, has length L


答:
Perl, 30 + 1 (-p) = 31 bytes

```<code>s/\./ ./,s|/$|/\\|||s|\\$|\\/|
</code>```

Needs -p and -M5.010 or -E to run :

```<code>perl -pE 's/\./ ./,s|/$|/\\|||s|\\$|\\/|' <<< ".
  .
    .
/
/\/"
</code>```

Straight forward implementation of the challenge. (Note that the || between the last two regex are or, as it might be hard to read, so the three regex are : s/\./ ./, and s|/$|/\\|, and s|\\$|\\/|)

Title: Wave-Particle Duality Laterally Programmatically

Body:
Perl, 30 + 1 (-p) = 31 bytes

s/\./ ./,s|/$|/\\|||s|\\$|\\/|

Needs -p and -M5.010 or -E to run :

perl -pE 's/\./ ./,s|/$|/\\|||s|\\$|\\/|' <<< ".
  .
    .
/
/\/"

Straight forward implementation of the challenge. (Note that the || between the last two regex are or, as it might be hard to read, so the three regex are : s/\./ ./, and s|/$|/\\|, and s|\\$|\\/|)


问:
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.)

答:
perl, 21 bytes

```<code>say+(A..Z)[rand$$%27]
</code>```

Needs -M5.010 or -E to run :

```<code>perl -E 'say+(A..Z)[rand$$%27]'
</code>```

How it works : (A..Z) is an array. $$ is process ID, which introduces some randomness. $$%27 is a number between 0 and 26 (inclusive, and roughly evenly spread). Calling rand on that produces a number between 0 and 26 (inclusive at 0, exclusive at 26), but biased towards smaller numbers. We then use that number for an array lookup, which we print.

Opportunities for improvement :

$$ is random, but not cleanly random. We know that the chance of getting particular numbers differs, but not by much, and not in ways that are easy to predict cleanly. Therefore, the possibility of getting different each letter is probably not identical, but it's very close. If (and only if) we accept that probability{ $$%26 == x } is different for all x, then we could replace "rand$$%27" with "$$%26".

Alternately, we could replace "rand$$%27" with (for example) "26*sin$$", and save one character. This gives a much less regular spread than simply "$$%26":

```
 perl -E 'for(1..32768){say+(A..Z)[26*sin$_]}' | sort | uniq -c
    832 A
   3269 B
   1648 C
   1360 D
   1183 E
   1133 F
   1043 G
   1071 H
    959 I
    978 J
    985 K
    939 L
    926 M
    950 N
    924 O
    939 P
    985 Q
    977 R
    959 S
   1072 T
   1043 U
   1135 V
   1182 W
   1360 X
   1647 Y
   3269 Z
```

But if you check, you'll see that it's not perfect. There are three pairs of numbers that have the same probability as each other: K&Q, I&S, L&P.

(If you use actual PIDs, then depending on what processes are actually running, and depending on the highest allowable pid on your machine, you might get more clashes, or less.)

"15*sin$$" works better, only 2 clashes - but that is still 2 clashes. (Any number between 13 and 26 will work, in the sense of producing all 26 letters, because sin(x) spans -1 to +1 and perl treats negative number array look-ups as starting from the array end).

There might be some way of getting all 26 numbers, with different probabilities, using less (or no more) than the 8 characters that "rand$$%27" needs. But if so, it isn't coming to me.

Body:
perl, 21 bytes

say+(A..Z)[rand$$%27]

Needs -M5.010 or -E to run :

perl -E 'say+(A..Z)[rand$$%27]'

How it works : (A..Z) is an array. $$ is process ID, which introduces some randomness. $$%27 is a number between 0 and 26 (inclusive, and roughly evenly spread). Calling rand on that produces a number between 0 and 26 (inclusive at 0, exclusive at 26), but biased towards smaller numbers. We then use that number for an array lookup, which we print.

Opportunities for improvement :

$$ is random, but not cleanly random. We know that the chance of getting particular numbers differs, but not by much, and not in ways that are easy to predict cleanly. Therefore, the possibility of getting different each letter is probably not identical, but it's very close. If (and only if) we accept that probability{ $$%26 == x } is different for all x, then we could replace "rand$$%27" with "$$%26".

Alternately, we could replace "rand$$%27" with (for example) "26*sin$$", and save one character. This gives a much less regular spread than simply "$$%26":

 perl -E 'for(1..32768){say+(A..Z)[26*sin$_]}' | sort | uniq -c
    832 A
   3269 B
   1648 C
   1360 D
   1183 E
   1133 F
   1043 G
   1071 H
    959 I
    978 J
    985 K
    939 L
    926 M
    950 N
    924 O
    939 P
    985 Q
    977 R
    959 S
   1072 T
   1043 U
   1135 V
   1182 W
   1360 X
   1647 Y
   3269 Z

But if you check, you'll see that it's not perfect. There are three pairs of numbers that have the same probability as each other: K&Q, I&S, L&P.

(If you use actual PIDs, then depending on what processes are actually running, and depending on the highest allowable pid on your machine, you might get more clashes, or less.)

"15*sin$$" works better, only 2 clashes - but that is still 2 clashes. (Any number between 13 and 26 will work, in the sense of producing all 26 letters, because sin(x) spans -1 to +1 and perl treats negative number array look-ups as starting from the array end).

There might be some way of getting all 26 numbers, with different probabilities, using less (or no more) than the 8 characters that "rand$$%27" needs. But if so, it isn't coming to me.


答:
MATL, 11 bytes

```<code>"X@QGy\un>v
</code>```

Truthy is an array (column vector) containing all ones. Falsy is an array containing at least one zero. You can check these definitions using this link.

Try it online! Or verify all test cases: truthy, falsy (slightly modified code, each case produces a horizontal vector for clarity).

Explanation

```<code>"       % Take input array. For each; i.e. repeat n times, where n is arrray size
  X@Q   %   Push iteration index plus 1, say k. So k is 2 in the first iteration,
        %   3 in the second, ... n+1 in the last. Actually we only need 2, ..., n;
        %   but the final n+1 doesn't hurt
  G     %   Push input again
  y     %   Duplicate k onto the top of the stack
  \     %   Modulo. Gives vector of remainders of input when divided by k
  un    %   Number of distinct elements
  >     %   True if that number is smaller than k
  v     %   Vertically concatenate with previous results
        % End for each. Implicitly display
</code>```

Title: Testing for admissible sequences

Body:
Executive summary: test whether an input sequence of integers is "admissible", meaning that it doesn't cover all residue classes for any modulus.

What is an "admissible" sequence?

Given an integer m ≥ 2, the residue classes modulo m are just the m possible arithmetic progressions of common difference m. For example, when m=4, the 4 residue classes modulo 4 are

```<code>..., -8, -4, 0, 4, 8, 12, ...
..., -7, -3, 1, 5, 9, 13, ...
..., -6, -2, 2, 6, 10, 14, ...
..., -5, -1, 3, 7, 11, 15, ...
</code>```

The kth residue class consists of all the integers whose remainder upon dividing by m equals k. (as long as one defines "remainder" correctly for negative integers)

A sequence of integers a1, a2, ..., ak is admissible modulo m if it fails to intersect at least one of the residue classes. For example, {0, 1, 2, 3} and {-4, 5, 14, 23} are not admissible modulo 4, but {0, 1, 2, 4} and {0, 1, 5, 9} and {0, 1, 2, -3} are admissible modulo 4. Also, {0, 1, 2, 3, 4} is not admissible modulo 4, while {0, 1, 2} is admissible modulo 4.

Finally, a sequence of integers is simply admissible if it is admissible modulo m for every integer m ≥ 2.

The challenge

Write a program or function that takes a sequence of integers as input, and returns a (consistent) Truthy value if the sequence is admissible and a (consistent) Falsy value if the sequence is not admissible.

The input sequence of integers can be in any reasonable format. You may assume that the input sequence has at least two integers. (You may also assume that the input integers are distinct if you want, though it probably doesn't help.) You must be able to handle positive and negative integers (and 0).

Usual code-golf scoring: the shortest answer, in bytes, wins.

Sample input

The following input sequences should each give a Truthy value:

```<code>0 2
-1 1
-100 -200
0 2 6
0 2 6 8
0 2 6 8 12
0 4 6 10 12
-60 0 60 120 180
0 2 6 8 12 26
11 13 17 19 23 29 31
-11 -13 -17 -19 -23 -29 -31
</code>```

The following input sequences should each give a Falsy value:

```<code>0 1
-1 4
-100 -201
0 2 4
0 2 6 10
0 2 6 8 14
7 11 13 17 19 23 29
-60 0 60 120 180 240 300
</code>```

Tips

Note that any sequence of 3 or fewer integers is automatically admissible modulo 4. More generally, a sequence of length k is automatically admissible modulo m when m > k. It follows that testing for admissibility really only requires checking a finite number of m.

Note also that 2 divides 4, and that any sequence that is admissible modulo 2 (that is, all even or all odd) is automatically admissible modulo 4. More generally, if m divides n and a sequence is admissible modulo m, then it is automatically admissible modulo n. To check admissibility, it therefore suffices to consider only prime m if you wish.

If a1, a2, ..., ak is an admissible sequence, then a1+c, a2+c, ..., ak+c is also admissible for any integer c (positive or negative).

Mathematical relevance (optional reading)

Let a1, a2, ..., ak be a sequence of integers. Suppose that there are infinitely many integers n such that n+a1, n+a2, ..., n+ak are all prime. Then it's easy to show that a1, a2, ..., ak must be admissible. Indeed, suppose that a1, a2, ..., ak is not admissible, and let m be a number such that a1, a2, ..., ak is not admissible modulo m. Then no matter what n we choose, one of the numbers n+a1, n+a2, ..., n+ak must be a multiple of m, hence cannot be prime.

The prime k-tuples conjecture is the converse of this statement, which is still a wide open problem in number theory: it asserts that if a1, a2, ..., ak is an admissible sequence (or k-tuple), then there should be infinitely many integers n such that n+a1, n+a2, ..., n+ak are all prime. For example, the admissible sequence 0, 2 yields the statement that there should be infinitely many integers n such that both n and n+2 are prime, this is the twin primes conjecture (still unproved).

Body:
MATL, 11 bytes

"X@QGy\un>v

Truthy is an array (column vector) containing all ones. Falsy is an array containing at least one zero. You can check these definitions using this link.

Try it online! Or verify all test cases: truthy, falsy (slightly modified code, each case produces a horizontal vector for clarity).

Explanation

"       % Take input array. For each; i.e. repeat n times, where n is arrray size
  X@Q   %   Push iteration index plus 1, say k. So k is 2 in the first iteration,
        %   3 in the second, ... n+1 in the last. Actually we only need 2, ..., n;
        %   but the final n+1 doesn't hurt
  G     %   Push input again
  y     %   Duplicate k onto the top of the stack
  \     %   Modulo. Gives vector of remainders of input when divided by k
  un    %   Number of distinct elements
  >     %   True if that number is smaller than k
  v     %   Vertically concatenate with previous results
        % End for each. Implicitly display


问:
Print a 10 by 10 grid of asterisks

Background

This is a standard textbook example to demonstrate for loops.

This is one of the first programs I learnt when I started learning programming ~10 years ago.

Task

You are to print this exact text:

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

Specs

You may have extra trailing newlines.

You may have extra trailing spaces (U+0020) at the end of each line, including the extra trailing newlines.

Scoring

This is code-golf. Shortest answer in bytes wins.

答:
LaTeX, <s>122</s> <s>110</s> 105 bytes

-12 bytes thanks to @Leaky Nun

-5 bytes by changing package & document type

Or, if I'm allowed to skip the document class definition & setup, and just count the package import and for-loop code: 55 bytes.

I still need to check if there's another package that has a shorter loop syntax, but for now, this simply uses pgffor (from tikz) and a foreach:

```<code>\documentclass{book}\usepackage{tikz}\begin{document}\foreach\n in{0,...,9}{**********\par}\end{document}
</code>```

Ungolfed:

```<code>\documentclass{book}
\usepackage{tikz}
\begin{document}
\foreach\n in{0,...,9}{**********\par}
\end{document}
</code>```

Output (w/ free page number :) ):

Title: Print a 10 by 10 grid of asterisks

Body:
LaTeX, <s>122</s> <s>110</s> 105 bytes

-12 bytes thanks to @Leaky Nun

-5 bytes by changing package & document type

Or, if I'm allowed to skip the document class definition & setup, and just count the package import and for-loop code: 55 bytes.

I still need to check if there's another package that has a shorter loop syntax, but for now, this simply uses pgffor (from tikz) and a foreach:

\documentclass{book}\usepackage{tikz}\begin{document}\foreach\n in{0,...,9}{**********\par}\end{document}

Ungolfed:

\documentclass{book}
\usepackage{tikz}
\begin{document}
\foreach\n in{0,...,9}{**********\par}
\end{document}

Output (w/ free page number :) ):


答:
Mathematica, 51 bytes

```<code>And@@Table[Length@Union@Mod[#,i]<i,{i,2,Length@#}]&
</code>```

Title: Testing for admissible sequences

Body:
Mathematica, 51 bytes

And@@Table[Length@Union@Mod[#,i]<i,{i,2,Length@#}]&


Title: Match up to 10 in an array

Body:
Challenge

Given an array of single digit number, work out if any 2 of them add up to 10 and print them out

Example

Input

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

This returns ((4,6),(5,5),(3,7))

Input

(1,2,3,4,5)

This returns (). as there is only one 5

Input

(5,5,5,5,5)

This returns ((5,5),(5,5)) as there is odd number of 5s and each 5 can be used only once

Rules

Here are the rules!

Assume input will only be an unsorted array of positive single digit integers

Each number will be pair up only once, which means if there are three 5s it only form 1 pair (5,5). If there are (3,3,7) it will only form 1 pair (3,7)

For the input: You can use any type of parentheses(or lack of) as long as readers can tell that the input is a single array of numbers.

For the output: It must look like an array of pairs. Where the array is the same form as your input.(If you did not use any parenheses in your input, you have to use some kind of symbols so that any readers can tell they are pairs in an array)

Test Cases

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

Good luck!

The shorter an answer is, the better!

Edit 1: update the rules and Testcases from comments

Edit 2: update rules to define format of input.

Edit 3: update rules to define format of output. trying to be as accommodating as possible.

Body:
Mathematica 70

Cases[#//.{x___,n_,y___,d_,z___}/;n+d==10:>{x,y,z,n~f~d},a_~f~b_:>{a,b}]&

Usage

Cases[# //. {x___, n_, y___, d_, z___} /; n + d == 10 :> {x, y, z, n~f~d},
a_~f~b_ :> {a,b}] &[{1, 2, 3, 4, 5, 5, 6, 7}]

{{3, 7}, {4, 6}, {5, 5}}


问:
Percent-Encode a String

Introduction

As some of you may know, URLs actually have a list of characters that do special things. For example, the / character separates parts of the URL, and the ?, &, and = characters are used to pass query parameters to the server. In fact, there is a bunch of characters with special functions: $&+,/:;=?@. When you need to use these characters in the URL for any other reason besides the special functions, you have to do something called percent-encoding.

Percent encoding is when you take a character's hexadecimal value and prepend a % character to the beginning of it. For example, the character ? would be encoded as %3F, and the character & would be encoded as %26. In a URL specifically, this allows you to send these characters as data via the URL without causing parsing problems. Your challenge will be to take a string, and percent-encode all of the characters that need to be encoded.

The Challenge

You shall write a program or function that takes in a single string consisting of characters with codepoints 00-FF (ASCII and Extended ASCII characters). You will then have to output or return the same string with each character percent-encoded if necessary. Built-ins that accomplish this task are not allowed, nor are standard loopholes. For reference, here is a list of every character that needs to be percent encoded:

Control characters (Codepoints 00-1F and 7F)

Extended ASCII characters (Codepoints 80-FF)

Reserved characters ($&+,/:;=?@, i.e. codepoints 24, 26, 2B, 2C, 2F, 3A, 3B, 3D, 3F, 40)

Unsafe characters (" <>#%{}|\^~[]`, i.e. codepoints 20, 22, 3C, 3E, 23, 25, 7B, 7D, 7C, 5C, 5E, 7E, 5B, 5D, 60)

Here is a the same list, but instead as a list of decimal codepoints:

```<code>0-31, 32, 34, 35, 36, 37, 38, 43, 44, 47, 58, 59, 60, 62, 61, 63, 64, 91, 92, 93, 94, 96, 123, 124, 125, 126, 127, 128-255
</code>```

This is code golf, so shortest code in bytes (or approved alternative scoring method) wins!

Test Cases

```<code>http://codegolf.stackexchange.com/  =>  http%3A%2F%2Fcodegolf.stackexchange.com%2F
[@=>]{#}  =>  %5B%40%3D%3E%5D%7B%23%7D
Test String  =>  Test%20String
ÑÉÐÔ®  =>  %D1%C9%D0%D4%AE
  =>  %0F%16%7F (Control characters 0F, 16, and 7F)
 ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ  =>  %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF (Extended ASCII characters 80-FF)
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~  =>  %20!%22%23%24%25%26'()*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E
</code>```

答:
Ruby, 37 + 3 = 40 bytes

Run with -p (3 extra bytes), like $ ruby -p percent_encode.rb:

gsub(/[^\w!'()*-.]/){"%%%02X"%$&.ord}
```

Title: Percent-Encode a String


问:
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.

答:
Lua 5.x, 37 bytes

x,n=...return math.sin(x+math.pi/2*n)
```
<p>usage:</p>
<pre class="lang-lua prettyprint-override"><code>> print(loadfile('sine.lua')(1,0))
0.8414709848079
> print(loadfile('sine.lua')(math.pi,0))
1.2246467991474e-16
> print(loadfile('sine.lua')(math.pi,1))
-1.0
> print(loadfile('sine.lua')(math.pi,2))
-2.4492935982947e-16
> print(loadfile('sine.lua')(math.pi,3))
1.0
</code>```

Title: Write a Sine-Deriving Machine

Body:
Lua 5.x, 37 bytes

x,n=...return math.sin(x+math.pi/2*n)

usage:

> print(loadfile('sine.lua')(1,0))
0.8414709848079
> print(loadfile('sine.lua')(math.pi,0))
1.2246467991474e-16
> print(loadfile('sine.lua')(math.pi,1))
-1.0
> print(loadfile('sine.lua')(math.pi,2))
-2.4492935982947e-16
> print(loadfile('sine.lua')(math.pi,3))
1.0


问:
Langford strings

Challenge description

A Langford string of order N is defined as follows:

The length of the string is equal to 2*N,

The string contains first N letters of the English alphabet, each letter appearing twice,

For each pair of the same letters, there are M letters between them, where M is that letter's position in the alphabet (A = 1, B = 2, ..., Z = 26).

For instance, the only two possible Langford strings of order 3 are BCABAC and CABACB. As you can see, in both of these strings there is one letter between two A's, two letters between B's and three letters between C's. Given a positive integer N, output all Langford strings of order N (in any reasonable format: print them one by one separated by a newline, return a list/array...).

Sample inputs / outputs

```<code>3: [CABACB, BCABAC]
4: [DACABDCB, BCDBACAD]
5: # no output #
7: [GCFBECBDGFEADA, GBFCBDECGFDAEA, GBDFBCEDGCFAEA, GCAFACDEGBFDBE, GADAFCEDGCBFEB, GACAFDCEGBDFBE, GDAEAFDCGEBCFB, GBDEBFCDGECAFA, EGBFCBEDCGFADA, CGDFCBEDBGFAEA, EGDAFAEDCGBFCB, EGBCFBECDGAFAD, AGABFDBECGDFCE, EGADAFECDGBCFB, AGABEFBCDGECFD, BGDBCEFDCGAEAF, FBGDBCEFDCGAEA, BFGBAEADFCGEDC, CFGACADEFBGDBE, EAGAFBEDBCGFDC, BCGBFCEADAGFED, DAGAFDBECBGFCE, EBGCBFECDAGAFD, CEGDCFBEDBGAFA, CEGBCFBEDAGAFD, BDGBCFDECAGAFE, EFAGACEDFCBGDB, DFAGADEBFCBGEC, AFAGBDEBFCDGEC, DFAGADCEFBCGBE, ECFGBCEBDFAGAD, DEFGADAECFBGCB, CDFGCBDEBFAGAE, EBDGBFEDACAGFC, CDEGCFDAEABGFB, AEAGCDFECBDGBF, FAEAGCDFECBDGB, DFCEGDCBFEBAGA, BFCBGDCEFADAGE, ECFDGCEBDFBAGA, DAFAGDCEBFCBGE, BCFBGCDEAFADGE, AEAFGBDEBCFDGC, ADAFGCDEBCFBGE, AFACEGDCFBEDBG, BFCBEGCDFAEADG, EBFDBGECDFACAG, BEFBCGDECFADAG, EBDFBGEDCAFACG, AEAFCGDECBFDBG, AEADFGCEDBCFBG, ADAEFGDBCEBFCG]
12: # <216288 strings> #
</code>```

Notes

Langford strings of order N can only be produced when N ≡ 0 (mod 4) or N ≡ 3 (mod 4),

You can use both lower-case and upper-case letters,

You may use subsequent numbers as well (012... or 123... instead of ABC...)

Order of strings in which they should appear as output is unspecified,

Output can be quite lengthy (for instance, there are over 5 trillion distinct Langford strings of order 20), so your program doesn't actually need to output them all, but it has to work in theory (given enough time and memory).

This challenge has been taken from /r/dailyprogrammer, all credit goes to /u/XenophonOfAthens

答:
Brachylog, 43 bytes

```<code>:1fd.
ybB:1jp.,B:[.]z:2a
:3f-+$_~h?
t:.m~h?
</code>```

Try it online!

Title: Langford strings

Body:
Brachylog, 43 bytes

:1fd.
ybB:1jp.,B:[.]z:2a
:3f-+$_~h?
t:.m~h?

Try it online!


问:
Smallest positive integer which is coprime to the last two predecessors and has not yet appeared; a(1)=1, a(2)=2

Definition

Two integers are coprime if they share no positive common divisors other than 1.

a(1) = 1

a(2) = 2

a(n) is the smallest positive integer which is coprime to the a(n-1) and a(n-2) and has not yet appeared, for integer n >= 3.

Task

Given positive integer n, output/print a(n).

Example

a(11) = 6 because 6 is coprime with the last two predecessors (namely, 11 and 13) and 6 has not appeared before.

Notes

Note that the sequence is not ascending, meaning that an element can be smaller than its predecessor.

Specs

You must use 1-indexed.

Testcases

```<code>n      a(n)
1      1
2      2
3      3
4      5
5      4
6      7
7      9
8      8
9      11
10     13
11     6
12     17
13     19
14     10
15     21
16     23
17     16
18     15
19     29
20     14
100    139
1000   1355
10000  13387
100000 133361
</code>```

Scoring

Since coprime means that the two numbers share only one divisor (1), and 1 is a small number, your code should be as small as possible in terms of byte-count.

References

OEIS A084937

答:
Python 3.5, <s>160</s> <s>141</s> <s>126</s> <s>124</s> <s>121</s> 109 bytes

This is a simple implementation of the sequence's definition. Golfing suggestions welcome.

Edit: -17 bytes thanks to Leaky Nun. -9 bytes thanks to Peter Taylor. -6 bytes thanks to Sp3000 and switching to Python 3.5.

import math;f=lambda n,r=[2,1],c=3:n<2and r[1]or(c in r)+math.gcd(c,r[0]*r[1])<2and f(n-1,[c]+r)or f(n,r,c+1)
```

<p><strong>Ungolfing:</strong></p>

<pre class="lang-python prettyprint-override"><code>import math
def f(n, r=[2,1], c=3):
    if n<2:
        return r[1]
    elif (c in r) + math.gcd(c,r[0]*r[1]) < 2:
        return f(n-1, [c]+r)
    else:
        return f(n, r, c+1)
</code>```

Body:
Python 3.5, <s>160</s> <s>141</s> <s>126</s> <s>124</s> <s>121</s> 109 bytes

This is a simple implementation of the sequence's definition. Golfing suggestions welcome.

Edit: -17 bytes thanks to Leaky Nun. -9 bytes thanks to Peter Taylor. -6 bytes thanks to Sp3000 and switching to Python 3.5.

import math;f=lambda n,r=[2,1],c=3:n<2and r[1]or(c in r)+math.gcd(c,r[0]*r[1])<2and f(n-1,[c]+r)or f(n,r,c+1)

Ungolfing:

import math
def f(n, r=[2,1], c=3):
    if n<2:
        return r[1]
    elif (c in r) + math.gcd(c,r[0]*r[1]) < 2:
        return f(n-1, [c]+r)
    else:
        return f(n, r, c+1)


问:
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++, 27243 character grid (248x219, 50.2% filled)

(Posting this as a new answer because I'd like to keep the 1D bound I originally posted as a reference)

This <s>blatantly rips off</s> is heavily inspired by @AndersKaseorg's answer in its main structure, but has a couple of tweaks. First, I use my original program to merge strings until the best available overlap is just 3 characters. Then I use the method AndersKaseorg describes to progressively fill a 2D grid using these generated strings. The constraints are a little different too: it still tries to add the fewest characters each time, but ties are broken by favouring square grids first, then small grids, and finally by adding the longest word.

The behaviour it displays is to alternate between periods of filling in space and rapidly expanding the grid (unfortunately it ran out of words just after a rapid expansion stage, so there's a lot of blank space around the edges). I suspect with some tweaking of the cost function it could be made to get better than 50% space filling.

There are 2 executables here (to avoid the need to re-run the whole process when iteratively improving the algorithm). The output of one can be piped directly into the other:

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

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(int argc, const char *const *argv) {
    // Usage: prog [<stop_threshold>]

    std::size_t stopThreshold = 3;

    if(argc >= 2) {
        char *check;
        long v = std::strtol(argv[1], &check, 10);
        if(check == argv[1] || v < 0) {
            std::cerr
                << "Invalid stop threshold. Should be an integer >= 0"
                << std::endl;
            return 1;
        }
        stopThreshold = v;
    }

    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 reach the threshold
    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;
            }
        }
        if(bestOverlap <= stopThreshold) {
            break;
        }
        std::string newStr = std::move(*bestA);
        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 merging: " << words.size()
        << std::endl;

    // Remove all fully subsumed words (i.e. reversed words)

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

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

    // Sort words longest-to-shortest for display
    std::sort(words.begin(), words.end(), [](const std::string &a, const std::string &b) {
        return a.size() > b.size();
    });

    std::size_t len = 0;
    for(const auto &word : words) {
        std::cout
            << word
            << std::endl;
        len += word.size();
    }
    std::cerr
        << "Total size: " << len
        << std::endl;
    return 0;
}
```

<pre class="lang-c++ prettyprint-override"><code>#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <limits>

class vec2 {
public:
    int x;
    int y;

    vec2(void) : x(0), y(0) {};
    vec2(int x, int y) : x(x), y(y) {}

    bool operator ==(const vec2 &b) const {
        return x == b.x && y == b.y;
    }

    vec2 &operator +=(const vec2 &b) {
        x += b.x;
        y += b.y;
        return *this;
    }

    vec2 &operator -=(const vec2 &b) {
        x -= b.x;
        y -= b.y;
        return *this;
    }

    vec2 operator +(const vec2 b) const {
        return vec2(x + b.x, y + b.y);
    }

    vec2 operator *(const int b) const {
        return vec2(x * b, y * b);
    }
};

class box2 {
public:
    vec2 tl;
    vec2 br;

    box2(void) : tl(), br() {};
    box2(vec2 a, vec2 b)
        : tl(std::min(a.x, b.x), std::min(a.y, b.y))
        , br(std::max(a.x, b.x) + 1, std::max(a.y, b.y) + 1)
    {}

    void grow(const box2 &b) {
        if(b.tl.x < tl.x) {
            tl.x = b.tl.x;
        }
        if(b.br.x > br.x) {
            br.x = b.br.x;
        }
        if(b.tl.y < tl.y) {
            tl.y = b.tl.y;
        }
        if(b.br.y > br.y) {
            br.y = b.br.y;
        }
    }

    bool intersects(const box2 &b) const {
        return (
            ((tl.x >= b.br.x) != (br.x > b.tl.x)) &&
            ((tl.y >= b.br.y) != (br.y > b.tl.y))
        );
    }

    box2 &operator +=(const vec2 b) {
        tl += b;
        br += b;
        return *this;
    }

    int width(void) const {
        return br.x - tl.x;
    }

    int height(void) const {
        return br.y - tl.y;
    }

    int maxdim(void) const {
        return std::max(width(), height());
    }
};

template <> struct std::hash<vec2> {
    std::size_t operator ()(const vec2 &o) const {
        return std::hash<int>()(o.x) + std::hash<int>()(o.y) * 997;
    }
};

template <class A,class B> struct std::hash<std::pair<A,B>> {
    std::size_t operator ()(const std::pair<A,B> &o) const {
        return std::hash<A>()(o.first) + std::hash<B>()(o.second) * 31;
    }
};

class word_placement {
public:
    vec2 start;
    vec2 dir;
    box2 bounds;
    const std::string *word;

    word_placement(vec2 start, vec2 dir, const std::string *word)
        : start(start)
        , dir(dir)
        , bounds(start, start + dir * (word->size() - 1))
        , word(word)
    {}

    word_placement(vec2 start, const word_placement &copy)
        : start(copy.start + start)
        , dir(copy.dir)
        , bounds(copy.bounds)
        , word(copy.word)
    {
        bounds += start;
    }

    word_placement(const word_placement &copy)
        : start(copy.start)
        , dir(copy.dir)
        , bounds(copy.bounds)
        , word(copy.word)
    {}
};

class word_placement_links {
public:
    std::unordered_set<word_placement*> placements;
    std::unordered_set<std::pair<char,word_placement*>> relativePlacements;
};

class grid {
public:
    std::vector<std::string> wordCache; // Just a block of memory for our pointers to reference
    std::unordered_map<vec2,char> state;
    std::unordered_set<word_placement*> placements;
    std::unordered_map<const std::string*,word_placement_links> wordPlacements;
    std::unordered_map<char,std::unordered_set<word_placement*>> relativeWordPlacements;
    box2 bound;

    grid(const std::vector<std::string> &words) {
        wordCache = words;
        std::vector<vec2> directions;
        directions.emplace_back(+1,  0);
        directions.emplace_back(+1, +1);
        directions.emplace_back( 0, +1);
        directions.emplace_back(-1, +1);
        directions.emplace_back(-1,  0);
        directions.emplace_back(-1, -1);
        directions.emplace_back( 0, -1);
        directions.emplace_back(+1, -1);

        wordPlacements.reserve(wordCache.size());
        placements.reserve(wordCache.size());
        relativeWordPlacements.reserve(64);

        std::size_t total = 0;
        for(const std::string &word : wordCache) {
            word_placement_links &p = wordPlacements[&word];
            p.placements.reserve(8);
            auto &rp = p.relativePlacements;
            std::size_t l = word.size();
            rp.reserve(l * directions.size());
            for(int i = 0; i < l; ++ i) {
                for(const vec2 &d : directions) {
                    word_placement *rwp = new word_placement(d * -i, d, &word);
                    rp.emplace(word[i], rwp);
                    relativeWordPlacements[word[i]].insert(rwp);
                }
            }
            total += l;
        }
        state.reserve(total);
    }

    const std::string *find_word(const std::string &word) const {
        for(const std::string &w : wordCache) {
            if(w == word) {
                return &w;
            }
        }
        throw std::string("Failed to find word in cache");
    }

    void remove_word(const std::string *word) {
        const word_placement_links &links = wordPlacements[word];
        for(word_placement *p : links.placements) {
            placements.erase(p);
            delete p;
        }
        for(auto &p : links.relativePlacements) {
            relativeWordPlacements[p.first].erase(p.second);
            delete p.second;
        }
        wordPlacements.erase(word);
    }

    void remove_placement(word_placement *placement) {
        wordPlacements[placement->word].placements.erase(placement);
        placements.erase(placement);
        delete placement;
    }

    bool check_placement(const word_placement &placement) const {
        vec2 p = placement.start;
        for(const char c : *placement.word) {
            auto i = state.find(p);
            if(i != state.end() && i->second != c) {
                return false;
            }
            p += placement.dir;
        }
        return true;
    }

    int check_new(const word_placement &placement) const {
        int n = 0;
        vec2 p = placement.start;
        for(const char c : *placement.word) {
            n += !state.count(p);
            p += placement.dir;
        }
        return n;
    }

    void check_placements(const box2 &b) {
        for(auto i = placements.begin(); i != placements.end(); ) {
            if(!b.intersects((*i)->bounds) || check_placement(**i)) {
                ++ i;
            } else {
                i = placements.erase(i);
            }
        }
    }

    void add_placement(const vec2 p, const word_placement &relative) {
        word_placement check(p, relative);
        if(check_placement(check)) {
            word_placement *wp = new word_placement(check);
            placements.insert(wp);
            wordPlacements[relative.word].placements.insert(wp);
        }
    }

    void place(word_placement placement) {
        remove_word(placement.word);
        int overlap = 0;
        for(const char c : *placement.word) {
            char &g = state[placement.start];
            if(g == '\0') {
                g = c;
                for(const word_placement *rp : relativeWordPlacements[c]) {
                    add_placement(placement.start, *rp);
                }
            } else if(g != c) {
                throw std::string("New word changes an existing character!");
            } else {
                ++ overlap;
            }
            placement.start += placement.dir;
        }
        bound.grow(placement.bounds);
        check_placements(placement.bounds);

        std::cerr
            << draw('.', "\n")
            << "Added " << *placement.word << " (overlap: " << overlap << ")"
            << ", Grid: " << bound.width() << "x" << bound.height() << " of " << state.size() << " chars"
            << ", Words remaining: " << wordPlacements.size()
            << std::endl;
    }

    int check_cost(box2 b) const {
        b.grow(bound);
        return (
            ((b.maxdim() - bound.maxdim()) << 16) |
            (b.width() + b.height() - bound.width() - bound.height())
        );
    }

    void add_next(void) {
        int bestNew = std::numeric_limits<int>::max();
        int bestCost = std::numeric_limits<int>::max();
        int bestLen = 0;
        word_placement *best = nullptr;
        for(word_placement *p : placements) {
            int n = check_new(*p);
            if(n <= bestNew) {
                int l = p->word->size();
                int cost = check_cost(box2(p->start, p->start + p->dir * l));
                if(n < bestNew || cost < bestCost || (cost == bestCost && l < bestLen)) {
                    bestNew = n;
                    bestCost = cost;
                    bestLen = l;
                    best = p;
                }
            }
        }
        if(best == nullptr) {
            throw std::string("Failed to find join to existing blob");
        }
        place(*best);
    }

    void fill(void) {
        while(!placements.empty()) {
            add_next();
        }
    }

    std::string draw(char blank, const std::string &linesep) const {
        std::string result;
        result.reserve((bound.width() + linesep.size()) * bound.height());
        for(int y = bound.tl.y; y < bound.br.y; ++ y) {
            for(int x = bound.tl.x; x < bound.br.x; ++ x) {
                auto c = state.find(vec2(x, y));
                result.push_back((c == state.end()) ? blank : c->second);
            }
            result.append(linesep);
        }
        return result;
    }

    box2 bounds(void) const {
        return bound;
    }

    int chars(void) const {
        return state.size();
    }
};

int main(int argc, const char *const *argv) {
    std::vector<std::string> words;

    // Load all words from input
    while(true) {
        std::string word;
        std::getline(std::cin, word);
        if(word.empty()) {
            break;
        }
        words.push_back(std::move(word));
    }

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

    // initialise grid
    grid g(words);

    // add first word (order of input file means this is longest word)
    g.place(word_placement(vec2(0, 0), vec2(1, 0), g.find_word(words.front())));

    // add all other words
    g.fill();

    std::cout << g.draw('.', "\n");

    int w = g.bounds().width();
    int h = g.bounds().height();
    int n = g.chars();
    std::cerr
        << "Final grid: " << w << "x" << h
        << " with " << n << " characters"
        << " (" << (n * 100.0 / (w * h)) << "% filled)"
        << std::endl;
    return 0;
}
</code>```

And finally, the result:

Alternative result (after fixing a couple of bugs in the program which were biasing certain directions and tweaking the cost function, I got a more compact but less optimal solution): 29275 chars, 198x195 (75.8% filled):

Again I haven't done much to optimise these programs, so it takes a while. But you can watch as it fills in the grid, which is quite hypnotic.

Title: Minimal Word Search

Body:
C++, 27243 character grid (248x219, 50.2% filled)

(Posting this as a new answer because I'd like to keep the 1D bound I originally posted as a reference)

This <s>blatantly rips off</s> is heavily inspired by @AndersKaseorg's answer in its main structure, but has a couple of tweaks. First, I use my original program to merge strings until the best available overlap is just 3 characters. Then I use the method AndersKaseorg describes to progressively fill a 2D grid using these generated strings. The constraints are a little different too: it still tries to add the fewest characters each time, but ties are broken by favouring square grids first, then small grids, and finally by adding the longest word.

The behaviour it displays is to alternate between periods of filling in space and rapidly expanding the grid (unfortunately it ran out of words just after a rapid expansion stage, so there's a lot of blank space around the edges). I suspect with some tweaking of the cost function it could be made to get better than 50% space filling.

There are 2 executables here (to avoid the need to re-run the whole process when iteratively improving the algorithm). The output of one can be piped directly into the other:

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

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(int argc, const char *const *argv) {
    // Usage: prog [<stop_threshold>]

    std::size_t stopThreshold = 3;

    if(argc >= 2) {
        char *check;
        long v = std::strtol(argv[1], &check, 10);
        if(check == argv[1] || v < 0) {
            std::cerr
                << "Invalid stop threshold. Should be an integer >= 0"
                << std::endl;
            return 1;
        }
        stopThreshold = v;
    }

    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 reach the threshold
    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;
            }
        }
        if(bestOverlap <= stopThreshold) {
            break;
        }
        std::string newStr = std::move(*bestA);
        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 merging: " << words.size()
        << std::endl;

    // Remove all fully subsumed words (i.e. reversed words)

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

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

    // Sort words longest-to-shortest for display
    std::sort(words.begin(), words.end(), [](const std::string &a, const std::string &b) {
        return a.size() > b.size();
    });

    std::size_t len = 0;
    for(const auto &word : words) {
        std::cout
            << word
            << std::endl;
        len += word.size();
    }
    std::cerr
        << "Total size: " << len
        << std::endl;
    return 0;
}

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <limits>

class vec2 {
public:
    int x;
    int y;

    vec2(void) : x(0), y(0) {};
    vec2(int x, int y) : x(x), y(y) {}

    bool operator ==(const vec2 &b) const {
        return x == b.x && y == b.y;
    }

    vec2 &operator +=(const vec2 &b) {
        x += b.x;
        y += b.y;
        return *this;
    }

    vec2 &operator -=(const vec2 &b) {
        x -= b.x;
        y -= b.y;
        return *this;
    }

    vec2 operator +(const vec2 b) const {
        return vec2(x + b.x, y + b.y);
    }

    vec2 operator *(const int b) const {
        return vec2(x * b, y * b);
    }
};

class box2 {
public:
    vec2 tl;
    vec2 br;

    box2(void) : tl(), br() {};
    box2(vec2 a, vec2 b)
        : tl(std::min(a.x, b.x), std::min(a.y, b.y))
        , br(std::max(a.x, b.x) + 1, std::max(a.y, b.y) + 1)
    {}

    void grow(const box2 &b) {
        if(b.tl.x < tl.x) {
            tl.x = b.tl.x;
        }
        if(b.br.x > br.x) {
            br.x = b.br.x;
        }
        if(b.tl.y < tl.y) {
            tl.y = b.tl.y;
        }
        if(b.br.y > br.y) {
            br.y = b.br.y;
        }
    }

    bool intersects(const box2 &b) const {
        return (
            ((tl.x >= b.br.x) != (br.x > b.tl.x)) &&
            ((tl.y >= b.br.y) != (br.y > b.tl.y))
        );
    }

    box2 &operator +=(const vec2 b) {
        tl += b;
        br += b;
        return *this;
    }

    int width(void) const {
        return br.x - tl.x;
    }

    int height(void) const {
        return br.y - tl.y;
    }

    int maxdim(void) const {
        return std::max(width(), height());
    }
};

template <> struct std::hash<vec2> {
    std::size_t operator ()(const vec2 &o) const {
        return std::hash<int>()(o.x) + std::hash<int>()(o.y) * 997;
    }
};

template <class A,class B> struct std::hash<std::pair<A,B>> {
    std::size_t operator ()(const std::pair<A,B> &o) const {
        return std::hash<A>()(o.first) + std::hash<B>()(o.second) * 31;
    }
};

class word_placement {
public:
    vec2 start;
    vec2 dir;
    box2 bounds;
    const std::string *word;

    word_placement(vec2 start, vec2 dir, const std::string *word)
        : start(start)
        , dir(dir)
        , bounds(start, start + dir * (word->size() - 1))
        , word(word)
    {}

    word_placement(vec2 start, const word_placement &copy)
        : start(copy.start + start)
        , dir(copy.dir)
        , bounds(copy.bounds)
        , word(copy.word)
    {
        bounds += start;
    }

    word_placement(const word_placement &copy)
        : start(copy.start)
        , dir(copy.dir)
        , bounds(copy.bounds)
        , word(copy.word)
    {}
};

class word_placement_links {
public:
    std::unordered_set<word_placement*> placements;
    std::unordered_set<std::pair<char,word_placement*>> relativePlacements;
};

class grid {
public:
    std::vector<std::string> wordCache; // Just a block of memory for our pointers to reference
    std::unordered_map<vec2,char> state;
    std::unordered_set<word_placement*> placements;
    std::unordered_map<const std::string*,word_placement_links> wordPlacements;
    std::unordered_map<char,std::unordered_set<word_placement*>> relativeWordPlacements;
    box2 bound;

    grid(const std::vector<std::string> &words) {
        wordCache = words;
        std::vector<vec2> directions;
        directions.emplace_back(+1,  0);
        directions.emplace_back(+1, +1);
        directions.emplace_back( 0, +1);
        directions.emplace_back(-1, +1);
        directions.emplace_back(-1,  0);
        directions.emplace_back(-1, -1);
        directions.emplace_back( 0, -1);
        directions.emplace_back(+1, -1);

        wordPlacements.reserve(wordCache.size());
        placements.reserve(wordCache.size());
        relativeWordPlacements.reserve(64);

        std::size_t total = 0;
        for(const std::string &word : wordCache) {
            word_placement_links &p = wordPlacements[&word];
            p.placements.reserve(8);
            auto &rp = p.relativePlacements;
            std::size_t l = word.size();
            rp.reserve(l * directions.size());
            for(int i = 0; i < l; ++ i) {
                for(const vec2 &d : directions) {
                    word_placement *rwp = new word_placement(d * -i, d, &word);
                    rp.emplace(word[i], rwp);
                    relativeWordPlacements[word[i]].insert(rwp);
                }
            }
            total += l;
        }
        state.reserve(total);
    }

    const std::string *find_word(const std::string &word) const {
        for(const std::string &w : wordCache) {
            if(w == word) {
                return &w;
            }
        }
        throw std::string("Failed to find word in cache");
    }

    void remove_word(const std::string *word) {
        const word_placement_links &links = wordPlacements[word];
        for(word_placement *p : links.placements) {
            placements.erase(p);
            delete p;
        }
        for(auto &p : links.relativePlacements) {
            relativeWordPlacements[p.first].erase(p.second);
            delete p.second;
        }
        wordPlacements.erase(word);
    }

    void remove_placement(word_placement *placement) {
        wordPlacements[placement->word].placements.erase(placement);
        placements.erase(placement);
        delete placement;
    }

    bool check_placement(const word_placement &placement) const {
        vec2 p = placement.start;
        for(const char c : *placement.word) {
            auto i = state.find(p);
            if(i != state.end() && i->second != c) {
                return false;
            }
            p += placement.dir;
        }
        return true;
    }

    int check_new(const word_placement &placement) const {
        int n = 0;
        vec2 p = placement.start;
        for(const char c : *placement.word) {
            n += !state.count(p);
            p += placement.dir;
        }
        return n;
    }

    void check_placements(const box2 &b) {
        for(auto i = placements.begin(); i != placements.end(); ) {
            if(!b.intersects((*i)->bounds) || check_placement(**i)) {
                ++ i;
            } else {
                i = placements.erase(i);
            }
        }
    }

    void add_placement(const vec2 p, const word_placement &relative) {
        word_placement check(p, relative);
        if(check_placement(check)) {
            word_placement *wp = new word_placement(check);
            placements.insert(wp);
            wordPlacements[relative.word].placements.insert(wp);
        }
    }

    void place(word_placement placement) {
        remove_word(placement.word);
        int overlap = 0;
        for(const char c : *placement.word) {
            char &g = state[placement.start];
            if(g == '\0') {
                g = c;
                for(const word_placement *rp : relativeWordPlacements[c]) {
                    add_placement(placement.start, *rp);
                }
            } else if(g != c) {
                throw std::string("New word changes an existing character!");
            } else {
                ++ overlap;
            }
            placement.start += placement.dir;
        }
        bound.grow(placement.bounds);
        check_placements(placement.bounds);

        std::cerr
            << draw('.', "\n")
            << "Added " << *placement.word << " (overlap: " << overlap << ")"
            << ", Grid: " << bound.width() << "x" << bound.height() << " of " << state.size() << " chars"
            << ", Words remaining: " << wordPlacements.size()
            << std::endl;
    }

    int check_cost(box2 b) const {
        b.grow(bound);
        return (
            ((b.maxdim() - bound.maxdim()) << 16) |
            (b.width() + b.height() - bound.width() - bound.height())
        );
    }

    void add_next(void) {
        int bestNew = std::numeric_limits<int>::max();
        int bestCost = std::numeric_limits<int>::max();
        int bestLen = 0;
        word_placement *best = nullptr;
        for(word_placement *p : placements) {
            int n = check_new(*p);
            if(n <= bestNew) {
                int l = p->word->size();
                int cost = check_cost(box2(p->start, p->start + p->dir * l));
                if(n < bestNew || cost < bestCost || (cost == bestCost && l < bestLen)) {
                    bestNew = n;
                    bestCost = cost;
                    bestLen = l;
                    best = p;
                }
            }
        }
        if(best == nullptr) {
            throw std::string("Failed to find join to existing blob");
        }
        place(*best);
    }

    void fill(void) {
        while(!placements.empty()) {
            add_next();
        }
    }

    std::string draw(char blank, const std::string &linesep) const {
        std::string result;
        result.reserve((bound.width() + linesep.size()) * bound.height());
        for(int y = bound.tl.y; y < bound.br.y; ++ y) {
            for(int x = bound.tl.x; x < bound.br.x; ++ x) {
                auto c = state.find(vec2(x, y));
                result.push_back((c == state.end()) ? blank : c->second);
            }
            result.append(linesep);
        }
        return result;
    }

    box2 bounds(void) const {
        return bound;
    }

    int chars(void) const {
        return state.size();
    }
};

int main(int argc, const char *const *argv) {
    std::vector<std::string> words;

    // Load all words from input
    while(true) {
        std::string word;
        std::getline(std::cin, word);
        if(word.empty()) {
            break;
        }
        words.push_back(std::move(word));
    }

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

    // initialise grid
    grid g(words);

    // add first word (order of input file means this is longest word)
    g.place(word_placement(vec2(0, 0), vec2(1, 0), g.find_word(words.front())));

    // add all other words
    g.fill();

    std::cout << g.draw('.', "\n");

    int w = g.bounds().width();
    int h = g.bounds().height();
    int n = g.chars();
    std::cerr
        << "Final grid: " << w << "x" << h
        << " with " << n << " characters"
        << " (" << (n * 100.0 / (w * h)) << "% filled)"
        << std::endl;
    return 0;
}

And finally, the result:

Alternative result (after fixing a couple of bugs in the program which were biasing certain directions and tweaking the cost function, I got a more compact but less optimal solution): 29275 chars, 198x195 (75.8% filled):

Again I haven't done much to optimise these programs, so it takes a while. But you can watch as it fills in the grid, which is quite hypnotic.


答:
Python 2, 78 bytes

```<code>lambda s:"".join(["%%%02x"%ord(c),c][c.isalnum()or c in"!'()*-._"]for c in s)
</code>```

More nicely formatted:

```<code>lambda s:
    "".join(["%%%02x" % ord(c), c][c.isalnum() or c in"!'()*-._"] for c in s)
</code>```

Title: Percent-Encode a String

Body:
Introduction

As some of you may know, URLs actually have a list of characters that do special things. For example, the / character separates parts of the URL, and the ?, &, and = characters are used to pass query parameters to the server. In fact, there is a bunch of characters with special functions: $&+,/:;=?@. When you need to use these characters in the URL for any other reason besides the special functions, you have to do something called percent-encoding.

Percent encoding is when you take a character's hexadecimal value and prepend a % character to the beginning of it. For example, the character ? would be encoded as %3F, and the character & would be encoded as %26. In a URL specifically, this allows you to send these characters as data via the URL without causing parsing problems. Your challenge will be to take a string, and percent-encode all of the characters that need to be encoded.

The Challenge

You shall write a program or function that takes in a single string consisting of characters with codepoints 00-FF (ASCII and Extended ASCII characters). You will then have to output or return the same string with each character percent-encoded if necessary. Built-ins that accomplish this task are not allowed, nor are standard loopholes. For reference, here is a list of every character that needs to be percent encoded:

Control characters (Codepoints 00-1F and 7F)

Extended ASCII characters (Codepoints 80-FF)

Reserved characters ($&+,/:;=?@, i.e. codepoints 24, 26, 2B, 2C, 2F, 3A, 3B, 3D, 3F, 40)

Unsafe characters (" <>#%{}|\^~[]`, i.e. codepoints 20, 22, 3C, 3E, 23, 25, 7B, 7D, 7C, 5C, 5E, 7E, 5B, 5D, 60)

Here is a the same list, but instead as a list of decimal codepoints:

```<code>0-31, 32, 34, 35, 36, 37, 38, 43, 44, 47, 58, 59, 60, 62, 61, 63, 64, 91, 92, 93, 94, 96, 123, 124, 125, 126, 127, 128-255
</code>```

This is code golf, so shortest code in bytes (or approved alternative scoring method) wins!

Test Cases

```<code>http://codegolf.stackexchange.com/  =>  http%3A%2F%2Fcodegolf.stackexchange.com%2F
[@=>]{#}  =>  %5B%40%3D%3E%5D%7B%23%7D
Test String  =>  Test%20String
ÑÉÐÔ®  =>  %D1%C9%D0%D4%AE
  =>  %0F%16%7F (Control characters 0F, 16, and 7F)
 ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ  =>  %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF (Extended ASCII characters 80-FF)
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~  =>  %20!%22%23%24%25%26'()*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E
</code>```

Body:
Python 2, 78 bytes

lambda s:"".join(["%%%02x"%ord(c),c][c.isalnum()or c in"!'()*-._"]for c in s)

More nicely formatted:

lambda s:
    "".join(["%%%02x" % ord(c), c][c.isalnum() or c in"!'()*-._"] for c in s)


答:
Python (142)

Input should be given with square brackets instead of round brackets.
http://ideone.com/p2QR11

```<code>from itertools import*
a=input()
c=lambda:[i for i in product(a,a[1:])if sum(i)==10]
d=c()
while d:print d[0];[a.remove(j)for j in d[0]];d=c()
</code>```

Algorithm:

```<code>1. Get input
2. Generate all pairs of input where the sum is 10
3. If there are no pairs, then END PROGRAM
4. Take the first pair's items and remove them from the input
5. Go back to step 2
</code>```

If seriously malformed output is allowed (90): http://ideone.com/GR762f

```<code>a=input()
c=a.count
for i in range(6):print(`i`+`10-i`+' ')*(min(c(i),c(10-i))/(1+(i==5)))
</code>```

Title: Match up to 10 in an array

Body:
Python (142)

Input should be given with square brackets instead of round brackets.
http://ideone.com/p2QR11

from itertools import*
a=input()
c=lambda:[i for i in product(a,a[1:])if sum(i)==10]
d=c()
while d:print d[0];[a.remove(j)for j in d[0]];d=c()

Algorithm:

1. Get input
2. Generate all pairs of input where the sum is 10
3. If there are no pairs, then END PROGRAM
4. Take the first pair's items and remove them from the input
5. Go back to step 2

If seriously malformed output is allowed (90): http://ideone.com/GR762f

a=input()
c=a.count
for i in range(6):print(`i`+`10-i`+' ')*(min(c(i),c(10-i))/(1+(i==5)))


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

```<code>2:i:"`@ym1MTF_)Zdqa+}@h]]G)
</code>```

The code is slow, but gives the correct result.

Try it online! Or verify the first ten cases.

A small modification of the code produces a plot of the sequence:

```<code>2:i:"`@ym1MTF_)Zdqa+}@h]]G:)XG
</code>```

See it as ASCII art, or with graphical output in the offline compiler:

Explanation

```<code>2:         % Push [1 2] to initiallize the sequence
i:         % Input n. Push [1 2 ... n]
"          % For loop: repeat n times
  `        %   Do while loop
    @      %     Push iteration index, starting at 1. This is the candidate number
           %     to extend the sequence
    y      %     Duplicate vector containing the sequence so far
    m      %     Is member? Gives true if the candidate is in the sequence
    1M     %     Push candidate and vector again
    TF_)   %     Get last two elements of the vector
    Zd     %     GCD between the candidate and those two elements. Produces a
           %     two-element vector
    qa     %     True if any of the two results exceeds 1, meaning
           %     the candidate is not coprime with the latest two sequence values
    +      %     Add. This corresponds to logical "or" of the two conditions, namely
           %     whether the candidate is member of the sequence so far, and
           %     whether it is not coprime with the latest two. In either case
           %     the do...while must continue with a next iteration, to try a new
           %     candidate. Else the loop is exited, and the current candidate
           %     is the new value of the sequence
  }        %   Finally (execute when the loop is exited)
    @h     %     Push current candidate and concatenate to the sequence vector
  ]        %   End do...while
]          % End for
G)         % Get n-th value of the sequence. Implicitly display
</code>```

Title: Smallest positive integer which is coprime to the last two predecessors and has not yet appeared; a(1)=1, a(2)=2

Body:
Definition

Two integers are coprime if they share no positive common divisors other than 1.

a(1) = 1

a(2) = 2

a(n) is the smallest positive integer which is coprime to the a(n-1) and a(n-2) and has not yet appeared, for integer n >= 3.

Task

Given positive integer n, output/print a(n).

Example

a(11) = 6 because 6 is coprime with the last two predecessors (namely, 11 and 13) and 6 has not appeared before.

Notes

Note that the sequence is not ascending, meaning that an element can be smaller than its predecessor.

Specs

You must use 1-indexed.

Testcases

```<code>n      a(n)
1      1
2      2
3      3
4      5
5      4
6      7
7      9
8      8
9      11
10     13
11     6
12     17
13     19
14     10
15     21
16     23
17     16
18     15
19     29
20     14
100    139
1000   1355
10000  13387
100000 133361
</code>```

Scoring

Since coprime means that the two numbers share only one divisor (1), and 1 is a small number, your code should be as small as possible in terms of byte-count.

References

OEIS A084937

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

2:i:"`@ym1MTF_)Zdqa+}@h]]G)

The code is slow, but gives the correct result.

Try it online! Or verify the first ten cases.

A small modification of the code produces a plot of the sequence:

2:i:"`@ym1MTF_)Zdqa+}@h]]G:)XG

See it as ASCII art, or with graphical output in the offline compiler:

Explanation

2:         % Push [1 2] to initiallize the sequence
i:         % Input n. Push [1 2 ... n]
"          % For loop: repeat n times
  `        %   Do while loop
    @      %     Push iteration index, starting at 1. This is the candidate number
           %     to extend the sequence
    y      %     Duplicate vector containing the sequence so far
    m      %     Is member? Gives true if the candidate is in the sequence
    1M     %     Push candidate and vector again
    TF_)   %     Get last two elements of the vector
    Zd     %     GCD between the candidate and those two elements. Produces a
           %     two-element vector
    qa     %     True if any of the two results exceeds 1, meaning
           %     the candidate is not coprime with the latest two sequence values
    +      %     Add. This corresponds to logical "or" of the two conditions, namely
           %     whether the candidate is member of the sequence so far, and
           %     whether it is not coprime with the latest two. In either case
           %     the do...while must continue with a next iteration, to try a new
           %     candidate. Else the loop is exited, and the current candidate
           %     is the new value of the sequence
  }        %   Finally (execute when the loop is exited)
    @h     %     Push current candidate and concatenate to the sequence vector
  ]        %   End do...while
]          % End for
G)         % Get n-th value of the sequence. Implicitly display


问:
Verify a ballot triangle
A ballot number, which we'll label B, is the number of ways of arranging the numbers from 1 through B(B+1)/2 into a triangle, such that each row and column is in any increasing order. The first four ballot numbers are:

```<code>a(0) = 1
a(1) = 1
a(2) = 1
a(3) = 2
</code>```

a(3) is 2, which means that there are 2 ways of arranging the numbers from 1 to 3(3+1)/2 = 6 in such a triangle:

```<code>1          1
2 3    or  2 4
4 5 6      3 5 6
</code>```

See the OEIS sequence entry for more details.

Your challenge, given a ballot triangle, is to verify its correctness. If it satisfies the conditions of a ballot triangle (rows and columns increasing), you should output how many other ways (excluding the one in the input) there are to arrange the triangle correctly. If the input triangle is incorrectly constructed, you should output nothing.

Trailing newlines are allowed.

Input

A triangle of numbers, which may or may not be a valid ballot triangle. For example:

```<code>1
2 3
4 5 6

1
10 5
9 8 2
7 6 4 3

1
3 2

9
2 11
14 3 5
12 8 1 7
15 13 10 4 6

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

Output

If the input is a valid ballot triangle, the remaining number of ways to arrange the same numbers in a valid ballot triangle. If the input is not a valid ballot triangle, nothing. For example, the inputs above produce these outputs (<nothing> is a placeholder for an actual empty output):

```<code>1                     # the same as a(3)-1

<nothing>

<nothing>

<nothing>

33591                 # the same as a(6)-1
</code>```

Scoring

This is code-golf: as usual, lowest byte-count wins. Tiebreaker is earliest posted.

答:
JavaScript (ES6), 143 bytes

```<code>a=>a.some((b,i)=>b.some((c,j)=>c<b[j-1]||i&&c<a[i-1][j]))?'':(f=n=>n<2||n*f(n-1),g=(n,m=f(n*n+n>>1))=>n<2?m:g(--n,m*f(n)/f(n+n+1)),g(a.length))
</code>```

Searches the triangle for an invalid entry and then uses a recursive formulation of the formula in OEIS to calculate the result.

Title: Verify a ballot triangle

Body:
JavaScript (ES6), 143 bytes

a=>a.some((b,i)=>b.some((c,j)=>c<b[j-1]||i&&c<a[i-1][j]))?'':(f=n=>n<2||n*f(n-1),g=(n,m=f(n*n+n>>1))=>n<2?m:g(--n,m*f(n)/f(n+n+1)),g(a.length))

Searches the triangle for an invalid entry and then uses a recursive formulation of the formula in OEIS to calculate the result.


答:
CJam (23 bytes)

```<code>{,2*e!{__f{\a/1=,(}=},}
</code>```

Online demo. This is an anonymous block (function) which takes input on the stack and leaves output on the stack in the form of an array of arrays of 0-based sequential integers.

Title: Langford strings

Body:
Challenge description

A Langford string of order N is defined as follows:

The length of the string is equal to 2*N,

The string contains first N letters of the English alphabet, each letter appearing twice,

For each pair of the same letters, there are M letters between them, where M is that letter's position in the alphabet (A = 1, B = 2, ..., Z = 26).

For instance, the only two possible Langford strings of order 3 are BCABAC and CABACB. As you can see, in both of these strings there is one letter between two A's, two letters between B's and three letters between C's. Given a positive integer N, output all Langford strings of order N (in any reasonable format: print them one by one separated by a newline, return a list/array...).

Sample inputs / outputs

```<code>3: [CABACB, BCABAC]
4: [DACABDCB, BCDBACAD]
5: # no output #
7: [GCFBECBDGFEADA, GBFCBDECGFDAEA, GBDFBCEDGCFAEA, GCAFACDEGBFDBE, GADAFCEDGCBFEB, GACAFDCEGBDFBE, GDAEAFDCGEBCFB, GBDEBFCDGECAFA, EGBFCBEDCGFADA, CGDFCBEDBGFAEA, EGDAFAEDCGBFCB, EGBCFBECDGAFAD, AGABFDBECGDFCE, EGADAFECDGBCFB, AGABEFBCDGECFD, BGDBCEFDCGAEAF, FBGDBCEFDCGAEA, BFGBAEADFCGEDC, CFGACADEFBGDBE, EAGAFBEDBCGFDC, BCGBFCEADAGFED, DAGAFDBECBGFCE, EBGCBFECDAGAFD, CEGDCFBEDBGAFA, CEGBCFBEDAGAFD, BDGBCFDECAGAFE, EFAGACEDFCBGDB, DFAGADEBFCBGEC, AFAGBDEBFCDGEC, DFAGADCEFBCGBE, ECFGBCEBDFAGAD, DEFGADAECFBGCB, CDFGCBDEBFAGAE, EBDGBFEDACAGFC, CDEGCFDAEABGFB, AEAGCDFECBDGBF, FAEAGCDFECBDGB, DFCEGDCBFEBAGA, BFCBGDCEFADAGE, ECFDGCEBDFBAGA, DAFAGDCEBFCBGE, BCFBGCDEAFADGE, AEAFGBDEBCFDGC, ADAFGCDEBCFBGE, AFACEGDCFBEDBG, BFCBEGCDFAEADG, EBFDBGECDFACAG, BEFBCGDECFADAG, EBDFBGEDCAFACG, AEAFCGDECBFDBG, AEADFGCEDBCFBG, ADAEFGDBCEBFCG]
12: # <216288 strings> #
</code>```

Notes

Langford strings of order N can only be produced when N ≡ 0 (mod 4) or N ≡ 3 (mod 4),

You can use both lower-case and upper-case letters,

You may use subsequent numbers as well (012... or 123... instead of ABC...)

Order of strings in which they should appear as output is unspecified,

Output can be quite lengthy (for instance, there are over 5 trillion distinct Langford strings of order 20), so your program doesn't actually need to output them all, but it has to work in theory (given enough time and memory).

This challenge has been taken from /r/dailyprogrammer, all credit goes to /u/XenophonOfAthens

Body:
CJam (23 bytes)

{,2*e!{__f{\a/1=,(}=},}

Online demo. This is an anonymous block (function) which takes input on the stack and leaves output on the stack in the form of an array of arrays of 0-based sequential integers.