问:
Simple cat program
One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a "cat program": read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility cat it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc.

Task

You should write a full program which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's prompt and alert). These are the only admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable.

The output should contain exactly the input and nothing else. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. This also applies to trailing newlines. If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.)

Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. If you do this, I encourage you to add an error-free version to your answer as well (for reference).

As this is intended as a challenge within each language and not between languages, there are a few language specific rules:

If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well).

If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example yes | tr -d \\n | ./my_cat should print an infinite stream of ys. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing).

Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output.

Additional rules

This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

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

Also note that languages do have to fulfil our usual criteria for programming languages.

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

Unless they have been overruled earlier, all standard code-golf rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

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

Catalogue

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Clojure, 18 bytes

```<code>(print(read-line))
</code>```

This 30-bytes program runs forever:

```<code>(while true(print(read-line)))
</code>```

Title: Simple cat program

Body:
Clojure, 18 bytes

(print(read-line))

This 30-bytes program runs forever:

(while true(print(read-line)))


问:
Has My Pie Been Bisected?
Write a program or function that takes in a nonempty list of positive integers. You may assume it is input in a reasonable convenient format such as "1 2 3 4" or [1, 2, 3, 4].

The numbers in the input list represent the slices of a full pie chart where each slice size is proportional to its corresponding number and all slices are arranged around the chart in the order given.

For example, the pie for 1 2 3 4 is:

The question your code must answer is: Is the pie chart ever bisected? That is, is there ever a perfectly straight line from one side of the circle to the other, splitting it symmetrically in two?

You need to output a truthy value if there is at least one bisector and output a falsy value if there are none.

In the 1 2 3 4 example there is a bisection between 4 1 and 2 3 so the output would be truthy.

But for input 1 2 3 4 5 there is no bisector so the output would be falsy:

Additional Examples

Arranging numbers differently may remove bisectors.

e.g. 2 1 3 4 → falsy:

If only one number is in the input list the pie is not bisected.

e.g. 10 → falsy:

There may be multiple bisectors. As long as there are more than zero the output is truthy.

e.g. 6 6 12 12 12 11 1 12 → truthy: (there are 3 bisectors here)

Bisections may exist even if they are not visually obvious.

e.g. 1000000 1000001 → falsy:

e.g. 1000000 1000001 1 → truthy:

(Thanks to nces.ed.gov for generating the pie charts.)

Test Cases

```<code>Truthy
1 2 3 4
6 6 12 12 12 11 1 12
1000000 1000001 1
1 2 3
1 1
42 42
1 17 9 13 2 7 3
3 1 2
10 20 10

Falsy
1 2 3 4 5
2 1 3 4
10
1000000 1000001
1
1 2
3 1 1
1 2 1 2 1 2
10 20 10 1
</code>```

Scoring

The shortest code in bytes wins. Tiebreaker is earlier answer.

答:
APL, 25 chars

Assuming the list is given in X ← 1 2 3 4.

```<code>(+/X)∊∘.{2×+/⍺↑⍵↓X,X}⍨⍳⍴X←⎕
</code>```

Explanation:

First note that APL evaluates form right to left. Then:

X←⎕ takes the user input and stores it in X

⍴X gives the length of X

⍳⍴X the numbers from 1 to ⍴X

The ⍺ and ⍵ in {2×+/⍺↑⍵↓X,X} are the left and right argument
to a dyadic function we are defining inside the braces.

Now for the ⍺↑⍵↓X,X part:
X,X just concatenates X with itself; ↑ and ↓ are take and drop.

+/ reduces/folds + over the list on its right

So 2 {2×+/⍺↑⍵↓X,X} 1 = 2×+/2↑1↓X,X = 2×+/2↑1↓1 2 3 4 1 2 3 4 =

= 2×+/2↑2 3 4 1 2 3 4 = 2×+/2 3 = 2×5 = 10.

∘.brace⍨idx is just idx ∘.brace idx. (⍨ is the diagonal map; ∘. is the outer product)

So this gives us a ⍴X by ⍴X matrix which contains twice the sums of all connected sublists.

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

The last thing we have to do is to check if the sum of X is somewhere inside this matrix.

Which we do with (+/X)∊matrix.

ContentLicense: CC BY-SA 3.0

Title: Has My Pie Been Bisected?

Body:
APL, 25 chars

Assuming the list is given in X ← 1 2 3 4.

(+/X)∊∘.{2×+/⍺↑⍵↓X,X}⍨⍳⍴X←⎕

Explanation:

First note that APL evaluates form right to left. Then:

X←⎕ takes the user input and stores it in X

⍴X gives the length of X

⍳⍴X the numbers from 1 to ⍴X

The ⍺ and ⍵ in {2×+/⍺↑⍵↓X,X} are the left and right argument
to a dyadic function we are defining inside the braces.

Now for the ⍺↑⍵↓X,X part:
X,X just concatenates X with itself; ↑ and ↓ are take and drop.

+/ reduces/folds + over the list on its right

So 2 {2×+/⍺↑⍵↓X,X} 1 = 2×+/2↑1↓X,X = 2×+/2↑1↓1 2 3 4 1 2 3 4 =

= 2×+/2↑2 3 4 1 2 3 4 = 2×+/2 3 = 2×5 = 10.

∘.brace⍨idx is just idx ∘.brace idx. (⍨ is the diagonal map; ∘. is the outer product)

So this gives us a ⍴X by ⍴X matrix which contains twice the sums of all connected sublists.

 4  6  8  2
10 14 10  6
18 16 14 12
20 20 20 20

The last thing we have to do is to check if the sum of X is somewhere inside this matrix.

Which we do with (+/X)∊matrix.


问:
Swap prime exponents with their neighbours
(Follow-up to my question about swapping bits with their neighbours.)

Task

Given a positive integer x = (2a · 3b) · (5c · 7d) · (11e · 13f) · …, print the integer obtained by swapping the exponents in this factorization for each successive pair of primes, y = (2b · 3a) · (5d · 7c) · (11f · 13e) · …

A061898 in the OEIS. This is code-golf, so the shortest program (in bytes) wins!

Test cases

```<code>1 -> 1
2 -> 3
3 -> 2
10 -> 21
37 -> 31
360 -> 756
12345 -> 11578
67895678 -> 125630871
</code>```

答:
Julia, <s>155</s> <s>131</s> 127 bytes

n->(x=[sort([merge([p=>0for p=primes(n+1)],factor(n))...]);1=>0];prod([x[i-1][1]^x[i][2]*x[i][1]^x[i-1][2]for i=2:2:endof(x)]))
```

<p>This is an anonymous function that accepts an integer and returns an integer. To call it, assign it to a variable. It requires a Julia version < 0.5 because the prime functionality has been removed from Base in 0.5.</p>

<p>Ungolfed:</p>

<pre class="lang-default prettyprint-override"><code>function f(n::Int)
    # Create an array of pairs by merging the Dict created from factoring n
    # with all primes less than n+1 with a 0 exponent. Append an extra pair
    # to account for 1 and situations where x would otherwise have odd length.
    x = [sort([(merge([p=>0 for p in primes(n+1)], factor(n))...]); 1=>0]

    # Compute a^d * c^b, where a and c are primes with b and d as their
    # respective exponents.
    prod([x[i-1][1]^x[i][2] * x[i][1]^x[i-1][2] for i = 2:2:endof(x)])
end
</code>```

Try it online! (Includes all test cases)

Body:
Julia, <s>155</s> <s>131</s> 127 bytes

n->(x=[sort([merge([p=>0for p=primes(n+1)],factor(n))...]);1=>0];prod([x[i-1][1]^x[i][2]*x[i][1]^x[i-1][2]for i=2:2:endof(x)]))

This is an anonymous function that accepts an integer and returns an integer. To call it, assign it to a variable. It requires a Julia version < 0.5 because the prime functionality has been removed from Base in 0.5.

Ungolfed:

function f(n::Int)
    # Create an array of pairs by merging the Dict created from factoring n
    # with all primes less than n+1 with a 0 exponent. Append an extra pair
    # to account for 1 and situations where x would otherwise have odd length.
    x = [sort([(merge([p=>0 for p in primes(n+1)], factor(n))...]); 1=>0]

    # Compute a^d * c^b, where a and c are primes with b and d as their
    # respective exponents.
    prod([x[i-1][1]^x[i][2] * x[i][1]^x[i-1][2] for i = 2:2:endof(x)])
end

Try it online! (Includes all test cases)


问:
Fairly rank values

Task

Given an input list of integers x1…xn, compute a list of ranks r1…rn (a permutation of {1…n}) so that xr1 ≤ xr2 ≤ … ≤ xrn. Then, for each xi, replace its rank by the arithmetic mean of the ranks of all values in x that are equal to xi. (That is, whenever there is a tie between equal values in x, fairly redistribute the ranks among all of them.) Output the modified list of ranks r’1…r’n.

(For statistics geeks: such a ranking of observations is used in the Mann–Whitney U test (method two, step 1.))

Example

Given an input list [3, -6, 3, 3, 14, 3], the first list of ranks would be [2, 1, 3, 4, 6, 5], which would sort the list into [-6, 3, 3, 3, 3, 14]. Then, the ranks for all 3s in the input list are evened out into (2 + 3 + 4 + 5) ÷ 4 = 3.5. The final output is [3.5, 1, 3.5, 3.5, 6, 3.5].

Test cases

```<code>[4, 1, 4] -> [2.5, 1.0, 2.5]
[5, 14, 14, 14, 14, 5, 14] -> [1.5, 5.0, 5.0, 5.0, 5.0, 1.5, 5.0]
[9, 9, -5, -5, 13, -5, 13, 9, 9, 13] -> [5.5, 5.5, 2.0, 2.0, 9.0, 2.0, 9.0, 5.5, 5.5, 9.0]
[13, 16, 2, -5, -5, -5, 13, 16, -5, -5] -> [7.5, 9.5, 6.0, 3.0, 3.0, 3.0, 7.5, 9.5, 3.0, 3.0]
</code>```

Rules

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

答:
APL, 17 chars

```<code>(y+.×⍋X)÷+/y←∘.=⍨X
</code>```

Assuming the list is stored in X.

Explanation:

Note that APL evaluates expressions from right to left. Then:

∘.=⍨X = X∘.=X where ∘.= is the outer product using = as dyadic function. (Where you normally would multiply. So the mathematical outer product may be written as ∘.×.)

The resulting matrix is stored in y and y is directly folded using + to give a vector of the number of equal objects for each rank (lets call it z←+/y).

⍋X returns the ranks of X

y+.×⍋X gives the inner product of our matrix y with this vector.

The result is divided (component wise) by z.

Title: Fairly rank values

Body:
APL, 17 chars

(y+.×⍋X)÷+/y←∘.=⍨X

Assuming the list is stored in X.

Explanation:

Note that APL evaluates expressions from right to left. Then:

∘.=⍨X = X∘.=X where ∘.= is the outer product using = as dyadic function. (Where you normally would multiply. So the mathematical outer product may be written as ∘.×.)

The resulting matrix is stored in y and y is directly folded using + to give a vector of the number of equal objects for each rank (lets call it z←+/y).

⍋X returns the ranks of X

y+.×⍋X gives the inner product of our matrix y with this vector.

The result is divided (component wise) by z.


问:
Implement Bogosort
Is solving Sudoku too hard? Even the brute force version? Here's a coding exercise that's a little easier. I hope. :-P

Write the shortest function to implement bogosort. In specific, your function should:

Take an array (or your language's equivalent) as input

Check if its elements are in sorted order; if so, return the array

If not, shuffle the elements, and start again

The shortest entry wins. In the case of a tie, a function that supports a custom comparator (and/or pseudorandom number generator) is favoured. Any remaining ties are resolved by favouring the earlier submission.

Clarifications: You can use any element type you want, as long as there's some way to order them, of course. Also, the shuffling has to be uniform; none of this "I'll just quicksort it and call it shuffled" business. :-)

答:
C++14, 158 bytes

```<code>#include <algorithm>
#include <random>
[](int*a,int s){std::random_device r;for(std::knuth_b g(r());!std::is_sorted(a,a+s);std::shuffle(a,a+s,g));return a;};
</code>```

ContentLicense: CC BY-SA 2.5

Title: Implement Bogosort

Body:
C++14, 158 bytes

#include <algorithm>
#include <random>
[](int*a,int s){std::random_device r;for(std::knuth_b g(r());!std::is_sorted(a,a+s);std::shuffle(a,a+s,g));return a;};


答:
Haskell, 41 bytes

f l=elem(sum l/2)$scanr(:)[]l>>=scanl(+)0
```
<p>The idea is to check whether there is a sublist of <code>l</code> whose sum equals <code>sum l/2</code>. We generate the sums of these sublists as <code>scanr(:)[]l>>=scanl(+)0</code>. Let's look at how this works with <code>l=[1,2,3]</code></p>
<pre class="lang-haskell prettyprint-override"><code>>> scanr(:)[]l
[[1,2,3],[2,3],[3],[]]
-- the suffixes of l

>> scanl(+)0 [2,3,4]
[0,2,5,9]
-- the cumulative sums of the input

>> scanr(:)[]l>>=scanl(+)0
[0,1,3,6,0,2,5,0,3,0]
-- the cumulative sums of the suffixes of l, flattened to a single list
</code>```

Old 43 bytes:

f l|c<-scanl1(+)l=elem(sum l/2)$(-)<$>c<*>c
```

Generates the list c of cumulative sums. Then, checks if any two of these sums differ by sum l/2 by checking if it is an element of the list of differences (-)<$>c<*>c.

Title: Has My Pie Been Bisected?

Body:
Write a program or function that takes in a nonempty list of positive integers. You may assume it is input in a reasonable convenient format such as "1 2 3 4" or [1, 2, 3, 4].

The numbers in the input list represent the slices of a full pie chart where each slice size is proportional to its corresponding number and all slices are arranged around the chart in the order given.

For example, the pie for 1 2 3 4 is:

The question your code must answer is: Is the pie chart ever bisected? That is, is there ever a perfectly straight line from one side of the circle to the other, splitting it symmetrically in two?

You need to output a truthy value if there is at least one bisector and output a falsy value if there are none.

In the 1 2 3 4 example there is a bisection between 4 1 and 2 3 so the output would be truthy.

But for input 1 2 3 4 5 there is no bisector so the output would be falsy:

Additional Examples

Arranging numbers differently may remove bisectors.

e.g. 2 1 3 4 → falsy:

If only one number is in the input list the pie is not bisected.

e.g. 10 → falsy:

There may be multiple bisectors. As long as there are more than zero the output is truthy.

e.g. 6 6 12 12 12 11 1 12 → truthy: (there are 3 bisectors here)

Bisections may exist even if they are not visually obvious.

e.g. 1000000 1000001 → falsy:

e.g. 1000000 1000001 1 → truthy:

(Thanks to nces.ed.gov for generating the pie charts.)

Test Cases

```<code>Truthy
1 2 3 4
6 6 12 12 12 11 1 12
1000000 1000001 1
1 2 3
1 1
42 42
1 17 9 13 2 7 3
3 1 2
10 20 10

Falsy
1 2 3 4 5
2 1 3 4
10
1000000 1000001
1
1 2
3 1 1
1 2 1 2 1 2
10 20 10 1
</code>```

Scoring

The shortest code in bytes wins. Tiebreaker is earlier answer.

Body:
Haskell, 41 bytes

f l=elem(sum l/2)$scanr(:)[]l>>=scanl(+)0

The idea is to check whether there is a sublist of l whose sum equals sum l/2. We generate the sums of these sublists as scanr(:)[]l>>=scanl(+)0. Let's look at how this works with l=[1,2,3]

>> scanr(:)[]l
[[1,2,3],[2,3],[3],[]]
-- the suffixes of l

>> scanl(+)0 [2,3,4]
[0,2,5,9]
-- the cumulative sums of the input

>> scanr(:)[]l>>=scanl(+)0
[0,1,3,6,0,2,5,0,3,0]
-- the cumulative sums of the suffixes of l, flattened to a single list

Old 43 bytes:

f l|c<-scanl1(+)l=elem(sum l/2)$(-)<$>c<*>c

Generates the list c of cumulative sums. Then, checks if any two of these sums differ by sum l/2 by checking if it is an element of the list of differences (-)<$>c<*>c.


问:
Color count, sorted by occurences
This one is simple to describe and I could hardly believe that this was not golfed before:

For a given image (whatever format is supported by your language), find the unique colors and output a list of the colors.

Print the color code in hex RGB, that is a hash sign # followed by 2 digits for R, 2 digits for G and 2 digits for B. (#xxxxxx where x can be 0-9, A-F and/or a-f).

The hex code shall be followed by a space  and the decimal pixel count, then a newline (\n or \r\n).

The list shall be sorted by count descending (most frequent color at the top).

If there's a tie (two colors with the same amount), the order is not important.

The image will not contain transparency, so any alpha value is not important. The alpha value may not be part of the output.

An image size of 4000x3000 must be supported (that may matter to type definitions)

Sample image "10red 20blue 30black 40white":

Expected output:

```<code>#FFFFFF 40
#000000 30
#0000FF 20
#FF0000 10
</code>```

Sample image "blue gradient":

One of the expected outputs (since the order of same colors may vary):

```<code>#718DFF 19
#5571FF 15
#3855FF 11
#8DAAFF 11
#1C38FF 7
#AAAAFF 7
#8D8DFF 6
#AAC6FF 6
#C6C6FF 5
#C6E2FF 4
#001CFF 3
#E2E2FF 3
#FFFFFF 3
</code>```

Sample image "testImage", kindly provided by @Luis Mendo:

Expected output:

```<code>#FFFFFF 18042
#000000 1754
#FF3300 204
</code>```

Similar to this question, but the output is text, not an image.

答:
Mathematica <s>103</s> 92 bytes

```<code>{"#"<>IntegerString[255Round[List@@#],16,2],#2}&@@@DominantColors[#,9999,{"Color","Count"}]&
</code>```

Example

Explanation

DominantColors normally returns a list of colors and counts representing the main clusters in a picture.
When the number of colors requested exceeds the number of colors in the image, the exact pixel colors are returned.  (I am assuming that fewer than 10 000 colors will be in the input image.)

 {"#"<>IntegerString[255Round[List@@#],16,2],#2} converts the base 10 color values with hexadecimal values.

Note: there are only 5 colors in the mandrill image. (I used ColorQuantize[<image>,5] to reduce the number of colors in the standard mandrill image.)

Title: Color count, sorted by occurences

Body:
Mathematica <s>103</s> 92 bytes

{"#"<>IntegerString[255Round[List@@#],16,2],#2}&@@@DominantColors[#,9999,{"Color","Count"}]&

Example

Explanation

DominantColors normally returns a list of colors and counts representing the main clusters in a picture.
When the number of colors requested exceeds the number of colors in the image, the exact pixel colors are returned.  (I am assuming that fewer than 10 000 colors will be in the input image.)

 {"#"<>IntegerString[255Round[List@@#],16,2],#2} converts the base 10 color values with hexadecimal values.

Note: there are only 5 colors in the mandrill image. (I used ColorQuantize[<image>,5] to reduce the number of colors in the standard mandrill image.)


问:
Help My Brother Work on his Tan(gent)!
This challenge is entirely fictional. There is no time limit for this challenge.

My little brother is terrible with computers! He saved up all of his money to buy a new one, and within half an hour the hard drive was wiped and the only software left is a lousy BF interpreter. The worst part of it is, he has a huge Geometry test tomorrow and needs help!

The Challenge

There's no way I'm going to let him touch my machine, so I'm going to need a fast way to write BF programs that solve his problem. He's learning about finding the area of regular polygons, and writing a new BF program for every calculation is a massive task. I need a fast way to generate BF programs! That's where you come in...

The Input

Your program or function will receive an integer 2 < N <= 100 which shall represent the number of sides of a regular polygon. You may receive input from function arguments, command line arguments, STDIN, or your language's closest alternative. If necessary, you may additionally require trailing or leading whitespace.

The Output

Your program should generate a separate BF program that takes input of a single positive integer 0 < a <= 10^10 that shall represent the length of the apothem of a regular polygon. When run, the BF program should output the area of a polygon with N sides and an apothem of a. More specifically:

Assume that the BF interpreter is set up such that , takes a number as input and . outputs a value as a number, not a character. An input of 12 does not translate to the characters '1' '2' in memory, rather the literal number 12. Similarly, when a value of 48 is output, it outputs '48', not the character '0'.

Assume also that each value on the tape of the BF program may contain an infinitely large integer -- the value will never wrap to 0.

Assume that the tape of the BF spans infinitely to the right, but has no negative indices. The pointer starts at 0.

My brother is as careless with numbers as he is with computers. As such, the BF code should output the area rounded to the nearest integer.

The Rules

In a separate and unrelated incident, my brother downloaded so much garbage onto my primary programming machine that I have virtually no hard drive space left. As such, your original program may not exceed 512 bytes.

Your score in this challenge is the length of all BF programs generated by your program for values of N from 3 to 100 inclusive.

Standard loopholes are disallowed.

答:
Python, 23938 score

```<code>from math import*
def apothem(n):
 c=int(n*tan(pi/n)/2*10)

 s=',>' + '+'*c
 m=">[-]>[-]<<[>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-]<<"*2
 p=">>[-]<[-]<+++++<[-]++++++++++"
 d=">[>+<-]>[<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<->>[-]]+>-]<-]<<+>]"
 o="<."
 print s+m+p+d+o
</code>```

the area of a regular polygon is nsa/2 width n given in Python and a later in BF. s is the sidelength of the polygon, which can be computed from a and n

c is a constant, such that the area is (aac+5)/10, so only this formula must be coded into BF. c is between 15 and 25.

s is the starting point for the BF code: read the apothem and write c

m does c=ca twice, so in the cell formaly holding c there is aac

p prepares for the final operation, clearing temporary cells, adding 5 to aac and setting the first cell to 10

d division

o output

This is my first writing in BF, so all algorithms are from this page.

Title: Help My Brother Work on his Tan(gent)!

Body:
Python, 23938 score

from math import*
def apothem(n):
 c=int(n*tan(pi/n)/2*10)

 s=',>' + '+'*c
 m=">[-]>[-]<<[>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-]<<"*2
 p=">>[-]<[-]<+++++<[-]++++++++++"
 d=">[>+<-]>[<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<->>[-]]+>-]<-]<<+>]"
 o="<."
 print s+m+p+d+o

the area of a regular polygon is nsa/2 width n given in Python and a later in BF. s is the sidelength of the polygon, which can be computed from a and n

c is a constant, such that the area is (aac+5)/10, so only this formula must be coded into BF. c is between 15 and 25.

s is the starting point for the BF code: read the apothem and write c

m does c=ca twice, so in the cell formaly holding c there is aac

p prepares for the final operation, clearing temporary cells, adding 5 to aac and setting the first cell to 10

d division

o output

This is my first writing in BF, so all algorithms are from this page.


问:
Stack Overflowing
(Inspired by this question)

Objective

Your task is to write a program or function to print an ASCII version of the Stack Overflow logo to STDOUT

```<code> \|/
(-)
(-)
(-)
(-)
</code>```

Your program should take two inputs, referred to here as H and N.
The height of the stack "container" (the parentheses) is determined by H. The number of items in the stack is determined by N. If N>H, the stack will "overflow".

Input/Output

H will determine the height of the containers

For example:

H=1:

```<code>( )
</code>```

H=2:

```<code>( )
( )
</code>```

H=3:

```<code>( )
( )
( )
</code>```

H will always be at least 1

N will determine how many items are in the stack. The following examples are all H = 2:

N=0

```<code>( )
( )
</code>```

N=1

```<code>( )
(-)
</code>```

N=2

```<code>(-)
(-)
</code>```

N=3

```<code> \
(-)
(-)
</code>```

N=4

```<code> \|
(-)
(-)
</code>```

N=5

```<code> \|/
(-)
(-)
</code>```

N=6

```<code>( )
</code>```0

N=7

```<code>( )
</code>```1

N will never be more than 2H+3 (In other words, the stack will never go through the ground).

Rules

No Standard Loopholes.

Your program must not produce any errors.

All test cases must pass.

You can input H and N any way you want.

I seriously doubt that your language has a built-in for this.

Each line may optionally have an extra space at the end. A blank line above a stack where N <= H is optional, as is a trailing newline.

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

Test Cases

In addition to all of the H=2 test cases from the Input/Output section, all of the following test cases must pass:

H=1, N=1

```<code>( )
</code>```2

H=1, N=5

```<code> \|/
(-)-
</code>```

H=4, N=7

```<code> \|/
(-)
(-)
(-)
(-)
</code>```

H=5, N=0

```<code>( )
( )
( )
( )
( )
</code>```

Leaderboards

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

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

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

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

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

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

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

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

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

var QUESTION_ID=81167,OVERRIDE_USER=41505;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

```

答:
JavaScript (ES6), <s>87</s> 80 bytes

F=(h,n)=>h?F(h-1,n-1)+`
(${n>0?'-':' '})${n>2*h+2?'-':''}`:' \\|/'.substr(0,n+1)
```

<p>Uses recursion to create the output string from the bottom up.</p>

<p><strong>EDIT</strong>: Thanks to @Neil for shaving 7 bytes off from 87 bytes</p>

<h2>Original</h2>

```(h,n)=>(E=s=>h--?E(`
(${n>0?'-':' '})${--n>2*h+3?'-':''}`+s):` \\|/`.substr(0,n+1)+s)``
```

<h2>Test snippet:</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>F=(h,n)=>h?F(h-1,n-1)+`
(${n>0?'-':' '})${n>2*h+2?'-':''}`:' \\|/'.substr(0,n+1)

h.oninput = n.oninput = () => output.innerHTML = F(+h.value, +n.value);</code>```

h <input type="number" min="0" value="0" id="h" />
n <input type="number" min="0" value="0" id="n" />

```</code>```

Title: Stack Overflowing

Body:
JavaScript (ES6), <s>87</s> 80 bytes

F=(h,n)=>h?F(h-1,n-1)+`
(${n>0?'-':' '})${n>2*h+2?'-':''}`:' \\|/'.substr(0,n+1)

Uses recursion to create the output string from the bottom up.

EDIT: Thanks to @Neil for shaving 7 bytes off from 87 bytes

Original

(h,n)=>(E=s=>h--?E(`
(${n>0?'-':' '})${--n>2*h+3?'-':''}`+s):` \\|/`.substr(0,n+1)+s)``

Test snippet:

F=(h,n)=>h?F(h-1,n-1)+`
(${n>0?'-':' '})${n>2*h+2?'-':''}`:' \\|/'.substr(0,n+1)

h.oninput = n.oninput = () => output.innerHTML = F(+h.value, +n.value);

<label>h <input type="number" min="0" value="0" id="h" /></label>
<label>n <input type="number" min="0" value="0" id="n" /></label>
<hr />
<pre id="output"></pre>


答:
Julia, 64 bytes

~=primes
!n=prod(t->(~3n)[endof(~t[1])+1$1-1]^t[2],factor(2n))/3
```

Try it online! The last test case requires too much memory for TIO, but I've verified it locally.

How it works

To avoid special-casing input 1 – the product of an empty dictionary is not defined – we multiply the input n by 2 and divide the final result by its pair 3.

factor(2n) gives all positive exponents of prime factors of 2n as a dictionary. When iterating over the dictionary, we'll get key-value/prime-exponent pairs. The function prod will take these pairs, apply the anonymous function t->... to them and return the product of the results.

For each pair t = (p,e), endof(~t[1]) or endof(primes(t[1])) return k, the number of primes that are less or equal to p, meaning that p is the kth prime.

+1$1-1 will increment k, XOR k + 1 with 1 and decrement the result. If k is odd, k + 1 is even, so the XOR increments and the final result is k + 1. If k is even, k + 1 is odd, so the XOR decrements and the final result is k - 1.

Finally, we compute all prime numbers less or equal to 3n with (~3n) or primes(3n) (the highest prime factor of 2n is less or equal to n if n > 2, and there's always a prime between n and 2n), select the one at index k + 1 or k - 1, and elevate it to the eth power with ^t[2].

Title: Swap prime exponents with their neighbours

Body:
(Follow-up to my question about swapping bits with their neighbours.)

Task

Given a positive integer x = (2a · 3b) · (5c · 7d) · (11e · 13f) · …, print the integer obtained by swapping the exponents in this factorization for each successive pair of primes, y = (2b · 3a) · (5d · 7c) · (11f · 13e) · …

A061898 in the OEIS. This is code-golf, so the shortest program (in bytes) wins!

Test cases

```<code>1 -> 1
2 -> 3
3 -> 2
10 -> 21
37 -> 31
360 -> 756
12345 -> 11578
67895678 -> 125630871
</code>```

Body:
Julia, 64 bytes

~=primes
!n=prod(t->(~3n)[endof(~t[1])+1$1-1]^t[2],factor(2n))/3

Try it online! The last test case requires too much memory for TIO, but I've verified it locally.

How it works

To avoid special-casing input 1 – the product of an empty dictionary is not defined – we multiply the input n by 2 and divide the final result by its pair 3.

factor(2n) gives all positive exponents of prime factors of 2n as a dictionary. When iterating over the dictionary, we'll get key-value/prime-exponent pairs. The function prod will take these pairs, apply the anonymous function t->... to them and return the product of the results.

For each pair t = (p,e), endof(~t[1]) or endof(primes(t[1])) return k, the number of primes that are less or equal to p, meaning that p is the kth prime.

+1$1-1 will increment k, XOR k + 1 with 1 and decrement the result. If k is odd, k + 1 is even, so the XOR increments and the final result is k + 1. If k is even, k + 1 is odd, so the XOR decrements and the final result is k - 1.

Finally, we compute all prime numbers less or equal to 3n with (~3n) or primes(3n) (the highest prime factor of 2n is less or equal to n if n > 2, and there's always a prime between n and 2n), select the one at index k + 1 or k - 1, and elevate it to the eth power with ^t[2].


答:
Bash + coreutils, 54

7 bytes saved thanks to @manatwork

grep -oE '#\w+'|sort|uniq -c|sort -nr|awk '$0=$2" "$1'
```
<p>This assumes STDIN input of Imagemagick's .txt format.</p>
<p>Ideone.</p>
<hr />
<p>If the above input format is too much of a stretch, then we can add Imagemagick conversion from any format:</p>
<h1>Bash + coreutils + Imagemagick, 71</h1>
<pre class="lang-bash prettyprint-override"><code>convert $1 txt:-|grep -oE '#\w+'|sort|uniq -c|sort -nr|awk '$0=$2" "$1'
</code>```

Here, the input image filename is passed in as a command-line parameter.

Title: Color count, sorted by occurences

Body:
This one is simple to describe and I could hardly believe that this was not golfed before:

For a given image (whatever format is supported by your language), find the unique colors and output a list of the colors.

Print the color code in hex RGB, that is a hash sign # followed by 2 digits for R, 2 digits for G and 2 digits for B. (#xxxxxx where x can be 0-9, A-F and/or a-f).

The hex code shall be followed by a space  and the decimal pixel count, then a newline (\n or \r\n).

The list shall be sorted by count descending (most frequent color at the top).

If there's a tie (two colors with the same amount), the order is not important.

The image will not contain transparency, so any alpha value is not important. The alpha value may not be part of the output.

An image size of 4000x3000 must be supported (that may matter to type definitions)

Sample image "10red 20blue 30black 40white":

Expected output:

```<code>#FFFFFF 40
#000000 30
#0000FF 20
#FF0000 10
</code>```

Sample image "blue gradient":

One of the expected outputs (since the order of same colors may vary):

```<code>#718DFF 19
#5571FF 15
#3855FF 11
#8DAAFF 11
#1C38FF 7
#AAAAFF 7
#8D8DFF 6
#AAC6FF 6
#C6C6FF 5
#C6E2FF 4
#001CFF 3
#E2E2FF 3
#FFFFFF 3
</code>```

Sample image "testImage", kindly provided by @Luis Mendo:

Expected output:

```<code>#FFFFFF 18042
#000000 1754
#FF3300 204
</code>```

Similar to this question, but the output is text, not an image.

Body:
Bash + coreutils, 54

7 bytes saved thanks to @manatwork

grep -oE '#\w+'|sort|uniq -c|sort -nr|awk '$0=$2" "$1'

This assumes STDIN input of Imagemagick's .txt format.

Ideone.

If the above input format is too much of a stretch, then we can add Imagemagick conversion from any format:

Bash + coreutils + Imagemagick, 71

convert $1 txt:-|grep -oE '#\w+'|sort|uniq -c|sort -nr|awk '$0=$2" "$1'

Here, the input image filename is passed in as a command-line parameter.


答:
Mathematica, 91 bytes

```<code>StringRiffle@SortBy[Tally["#"<>IntegerString[#,16,2]&/@Join@@#~ImageData~"Byte"],-Last@#&]&
</code>```

Uses a completely different method from @DavidC's answer. Unlike that one, this can support images with any size and color count. Explanation:

```<code>#~ImageData~"Byte"                   Take the RGB values of the image...
Join@@(...)                          Flatten to a list of colors...
"#"<>IntegerString[#,16,2]&/@(...)   Convert each color to #012def format...
Tally[(...)]                         Convert to a list of {color, multiplicity}
                                      pairs (this does most of the work)...
SortBy[(...),-Last@#&]               Order by the multiplicity descending...
StringRiffle@(...)                   And create a string with the desired format.
</code>```

Title: Color count, sorted by occurences

Body:
Mathematica, 91 bytes

StringRiffle@SortBy[Tally["#"<>IntegerString[#,16,2]&/@Join@@#~ImageData~"Byte"],-Last@#&]&

Uses a completely different method from @DavidC's answer. Unlike that one, this can support images with any size and color count. Explanation:

#~ImageData~"Byte"                   Take the RGB values of the image...
Join@@(...)                          Flatten to a list of colors...
"#"<>IntegerString[#,16,2]&/@(...)   Convert each color to #012def format...
Tally[(...)]                         Convert to a list of {color, multiplicity}
                                      pairs (this does most of the work)...
SortBy[(...),-Last@#&]               Order by the multiplicity descending...
StringRiffle@(...)                   And create a string with the desired format.


问:
Jam don't add like that

Background

Jelly's arithmetic atoms vectorize automatically. In fact, x + y is well-defined whenever x and y are numbers or ragged arrays of numbers. Jelly's source code implements this behavior using a generic vectorizer, but for this challenge, we'll only consider addition of integers and nested integer arrays.

Definitions

Define the depth of x as 0 if x is an integer, as 1 if it is a (possibly empty) flat array of integers, and as n + 1 if it contains at least one element of depth n and no elements of depth k > n.

This way, 1 has depth 0, [] and [1] and [1, 1] have depth 1, [[], []] and [[1], [1]] and [[1]] and [1, []] have depth 2, [1, [1, [1]]] has depth 3, etc.

The operation x + y is defined as follows.

If x and y have depth 0, return their sum.

If x and y have equal but positive depths, recursively apply + to all items of x and the corresponding items of y.

If x and y have different lengths, append the tail of the longer array to the array of sums.

Return the result.

If x's depth is strictly smaller than y's depth, recursively apply + to x and all items of y, and return the result.

Do the opposite if y's depth is strictly smaller than x's.

For example, consider the operation [1, [2, 3], [4]] + [[[10, 20], [30], 40, 50], 60].

The depth of the left argument is 2, while the depth of the right argument is 3, so we compute [1, [2, 3], [4]] + [[10, 20], [30], 40, 50] and [1, [2, 3], [4]] + 60.

[1, [2, 3], [4]] and [[10, 20], [30], 40, 50] both have depth 2, so we compute 1 + [10, 20], [2, 3] + [30] and [4] + 40.

1 + [10, 20] = [1 + 10, 1 + 20] = [11, 21]

[2, 3] + [30] = [2 + 30, 3] = [32, 3]

Note that 3 remains untouched, since it doesn't have a matching element.

[4] + 40 = [4 + 40] = [44]

50 doesn't have a matching element, so the result is [[[11, 21], [32, 3], [44], 50]].

[1, [2, 3], [4]] + 60 = [1 + 60, [2, 3] + 60, [4] + 60] = [61, [2 + 60, 3 + 60], [4 + 60]], resulting in [61, [62, 63], [64]].

The final result is [[[11, 21], [32, 3], [44], 50], [61, [62, 63], [64]]].

Task

Write a program or a function that takes two integers, two nested arrays of integers or a combination thereof as input and returns their sum, as defined above.

If your language has multiple array-like types (lists, tuples, vectors, etc.) you may choose any of them for your answer. The return type must match the argument type.

To prevent boring and unbeatable solutions, if a language has this exact operation as a built-in, you may not use that language.

All built-ins of all other languages are allowed. If your language of choice permits this, you may overload and/or redefine the built-in addition.

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

Test cases

```<code>0 + 0                           = 0
[-1, 0, -1] + [1]               = [0, 0, -1]
[] + [0]                        = [0]
[] + 0                          = []
[] + []                         = []
[[], 0] + []                    = [[], []]
[1, 2, 3] + 10                  = [11, 12, 13]
[1, 2, 3] + [10]                = [11, 2, 3]
[1, 2, 3] + [10, [20]]          = [[11, 12, 13], [21, 2, 3]]
[1, 2, 3, []] + [10, [20]]      = [11, [22], 3, []]
[1, [2, [3, [4]]]] + [10, [20]] = [[11, [21]], [[12, [22]], [13, [24]]]]
</code>```

To generate more test cases, you can use this Jelly program.

答:
Python 2, <s>145</s> 136 bytes

d=lambda t:t>{}and-~max(map(d,t+[0]))
s=lambda x,y:s(y,x)if d(y)<d(x)else map(s,(x,[x]*len(y))[d(x)<d(y)],y)if d(y)else(x or 0)+(y or 0)
```

Test it on Ideone.

How it works

In Python 2, all integers are less than all dictionaries, but all lists are greater. d recursively computes the depth of t by returning 0 for integers or the incremented maximum of the depths of its elements and 0. t+[0] avoids special-casing the empty list.

s recursively computes the Jelly sum of x and y.

If y's depth exceeds x's, s(y,x) calls s with swapped arguments, making sure that d(x) ≤ d(y).

If y has positive depth, map(s,(x,[x]*len(y))[d(x)<d(y)],y) does the following.

If the x's and y's depths match, it executes map(s,x,y), mapping s over all elements of x and the corresponding elements of y.

In the case of lists of different lengths, map will pass None as left or right argument for missing elements in the shorter list.

If x's depth is lower than y's, it executes map(s,[x]*len(y),y), mapping s(x, · ) over y.

If y (and, therefore, x) has depth 0, (x or 0)+(y or 0) replaces falsy arguments (None or 0) with zeroes and returns the sum of the resulting integers.

Title: Jam don't add like that

Body:
Python 2, <s>145</s> 136 bytes

d=lambda t:t>{}and-~max(map(d,t+[0]))
s=lambda x,y:s(y,x)if d(y)<d(x)else map(s,(x,[x]*len(y))[d(x)<d(y)],y)if d(y)else(x or 0)+(y or 0)

Test it on Ideone.

How it works

In Python 2, all integers are less than all dictionaries, but all lists are greater. d recursively computes the depth of t by returning 0 for integers or the incremented maximum of the depths of its elements and 0. t+[0] avoids special-casing the empty list.

s recursively computes the Jelly sum of x and y.

If y's depth exceeds x's, s(y,x) calls s with swapped arguments, making sure that d(x) ≤ d(y).

If y has positive depth, map(s,(x,[x]*len(y))[d(x)<d(y)],y) does the following.

If the x's and y's depths match, it executes map(s,x,y), mapping s over all elements of x and the corresponding elements of y.

In the case of lists of different lengths, map will pass None as left or right argument for missing elements in the shorter list.

If x's depth is lower than y's, it executes map(s,[x]*len(y),y), mapping s(x, · ) over y.

If y (and, therefore, x) has depth 0, (x or 0)+(y or 0) replaces falsy arguments (None or 0) with zeroes and returns the sum of the resulting integers.


问:
Minimum cost block diagonalisation
Consider binary block diagonal matrices which have square blocks of 1s on the main diagonal, and are 0 everywhere else. Let's call such matrices "valid" matrices.

For example, here are some valid 4x4 matrices:

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

Note that an alternative way of describing such matrices is that there is a chain of square 1 blocks from the top-left to the bottom-right, touching corner to corner, and everywhere else is 0.

For contrast, here are some invalid 4x4 matrices:

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

You will be given an n by n binary matrix as input – what is the minimum number of 0 bits you'll need to set to 1 in order to get a valid matrix?

You may write a function or program taking in any convenient string, list or matrix format representing an n by n matrix of 0s and 1s (as long as it isn't preprocessed). Rows must be clearly separated in some way, so formats like a 1D array of bits are not allowed.

This is code-golf, so the goal is to minimise the number of bytes in your program.

Examples

For example, if the input is

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

then the answer is 5, since you can set five 0 bits to 1 to get:

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

and this is the minimum number required. However, if the input was

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

then the answer is 24, since the only valid 5x5 matrix where the top-right is 1 is the matrix of all 1s.

Test cases

Tests are represented here as a 2D array of integers.

```<code>[[0]] -> 1
[[1]] -> 0
[[0,1],[0,0]] -> 3
[[1,0],[0,0]] -> 1
[[0,0,0],[0,1,0],[0,0,0]] -> 2
[[0,1,0],[0,0,0],[0,1,0]] -> 7
[[0,1,0],[1,0,0],[0,0,1]] -> 2
[[1,1,1],[1,1,1],[1,1,1]] -> 0
[[0,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,0]] -> 4
[[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]] -> 8
[[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,0,1,0]] -> 14
[[0,0,1,0],[0,0,0,0],[0,0,0,0],[0,1,0,0]] -> 14
[[0,0,0,0,0],[0,0,0,0,0],[0,1,0,0,0],[0,0,0,0,1],[0,0,0,0,0]] -> 7
[[0,0,0,0,0],[0,0,0,0,0],[1,0,0,0,0],[0,0,0,0,1],[0,0,0,0,0]] -> 11
[[0,0,0,0,0],[0,0,1,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,1]] -> 5
[[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] -> 24
[[0,0,0,1,0],[0,0,0,0,1],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]] -> 23
[[0,1,0,0,0],[1,0,0,0,0],[0,0,1,0,0],[0,0,0,0,1],[0,0,0,1,0]] -> 4
[[0,1,1,1,0],[0,1,1,0,1],[0,1,1,1,0],[0,1,0,0,1],[0,0,0,0,0]] -> 14
</code>```

Notes

Related challenge: Print a Block-Diagonal Matrix

Inspiration: Freedom Factory, Google Code Jam 2016 Problem 2D

答:
Matricks, 180 bytes (noncompeting)

Matricks is a new esolang I created very recently to deal with matrix problems (such as this one), by only having 2 data types: floats and matricies. It is not fully featured yet, and still has a lot of missing operations (I had to add some functionality for this challenge). Anyway, here's the code:

```<code>il=1:j3;:bdx;;;s1::L;j1;;
b{q:1;mgr:c;|gc:r;|(r=c)|(gr-1:c;|gr:c+1;)&(rec)|(gr+1:c;|gr:c-1;)&(cer):l:L;};z:(l-1)/2;B1;s1::g1:;-1;ig1:;=0:j2;:j1;;
s1::d{q:1;};;kg1:;-g:;;
kg:;*-1+1;
</code>```

Explanation

The first part, il=1:j3;:...; checks if the array is of size 1. If it is, it jumps to the last line, kg:;*-1+1;, which is a simple 0 <-> 1 function.

Otherwise, it continues on with the rest of the code. bdx;;; sets the cell 0,0 to the current sum, and s1::L;j1; creates a counter in the cell in the row below.

The next line is a bit more complicated. It is a loop that runs n times, n being the size of the matrix. I'll use the 3rd test case as an example. When we first get to the second line, the matrix looks like this:

```<code>1 0 1
2 0 0
</code>```

First, we go into the matrix comprehension {q:1;m...;}. This makes the diagonal, and tries its best to clean up 0 that need filling in. All this is accomplished using simple boolean operators. Then, we prepend it to the current matrix, giving this:

```<code>    V--data we want to keep
1 1 1 0 1 <-|
1 1 2 0 0 <-- old matrix
</code>```

Then, we cut of the old matrix using z:(l-1)/2;, and rotate the entire matrix to the left using B1;. That gives us a matrix ready for the next iteration, looking like:

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

Finally, we decrement the counter, check it, and continue with ig1:;=0:j2;:j1;;

Once the loop is broken out of, we find the new sum and set the counter's old spot with s1::d{q:1;};;. Finally, we take the difference and return kg1:;-g:;;. k sets the current array to a value, and printing is implicit.

...

As you can see, Matricks is pretty verbose, and not a very good golfing language. But heck, I wanted to show it off.

Title: Minimum cost block diagonalisation

Body:
Matricks, 180 bytes (noncompeting)

Matricks is a new esolang I created very recently to deal with matrix problems (such as this one), by only having 2 data types: floats and matricies. It is not fully featured yet, and still has a lot of missing operations (I had to add some functionality for this challenge). Anyway, here's the code:

il=1:j3;:bdx;;;s1::L;j1;;
b{q:1;mgr:c;|gc:r;|(r=c)|(gr-1:c;|gr:c+1;)&(rec)|(gr+1:c;|gr:c-1;)&(cer):l:L;};z:(l-1)/2;B1;s1::g1:;-1;ig1:;=0:j2;:j1;;
s1::d{q:1;};;kg1:;-g:;;
kg:;*-1+1;

Explanation

The first part, il=1:j3;:...; checks if the array is of size 1. If it is, it jumps to the last line, kg:;*-1+1;, which is a simple 0 <-> 1 function.

Otherwise, it continues on with the rest of the code. bdx;;; sets the cell 0,0 to the current sum, and s1::L;j1; creates a counter in the cell in the row below.

The next line is a bit more complicated. It is a loop that runs n times, n being the size of the matrix. I'll use the 3rd test case as an example. When we first get to the second line, the matrix looks like this:

1 0 1
2 0 0

First, we go into the matrix comprehension {q:1;m...;}. This makes the diagonal, and tries its best to clean up 0 that need filling in. All this is accomplished using simple boolean operators. Then, we prepend it to the current matrix, giving this:

    V--data we want to keep
1 1 1 0 1 <-|
1 1 2 0 0 <-- old matrix

Then, we cut of the old matrix using z:(l-1)/2;, and rotate the entire matrix to the left using B1;. That gives us a matrix ready for the next iteration, looking like:

1 1 1
2 1 1

Finally, we decrement the counter, check it, and continue with ig1:;=0:j2;:j1;;

Once the loop is broken out of, we find the new sum and set the counter's old spot with s1::d{q:1;};;. Finally, we take the difference and return kg1:;-g:;;. k sets the current array to a value, and printing is implicit.

...

As you can see, Matricks is pretty verbose, and not a very good golfing language. But heck, I wanted to show it off.


问:
Partition of a positive integer N
Find the number of partitions of a positive integer n. Hope someone uses the explicit finite formula for the partition function defined in Jan Hendrik Brunier and Ken Ono paper here.

```<code>Sample Input
8
Sample Output
22
</code>```

N is less than or equal to 1000.
Write the complete program. More than anything I would like to see the different approaches.

答:
Mathematica 11 chars

Sorry, no need to implement the algorithm

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

Usage

```<code>%[8]
22
</code>```

Title: Partition of a positive integer N

Body:
Mathematica 11 chars

Sorry, no need to implement the algorithm

PartitionsP

Usage

%[8]
22


问:
Print NxN spiral of ascending numbers
The numbers should be printed with leading zeroes in a field with length = (number of digits of N^2).

Input (N):

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

Output:

```<code>01 12 11 10
02 13 16 09
03 14 15 08
04 05 06 07
</code>```

I am interested in the algorithm and the cleanliness of the implementation.
So, the white space does not count and the upper limit for N is 42.

Title: Print NxN spiral of ascending numbers

Body:
Python

n=input()

matrix=[[j+1]*n for j in range(n)]

x=y=0
for i in range(n)[::-2]:
    x+=i*4;y+=1

    for j in range(i):
        matrix[j+y-1][y]=x+j

    matrix[y-1][y:y+i]=range(x,x-i,-1)

    R=matrix[n-y][y-1]+1
    matrix[n-y][y:n-y+1]=range(R,R+i)

    for j in range(y,y+i-1):
        matrix[j][n-y]=matrix[j-1][n-y]-1

for row in matrix:
    print ' '.join(`r`.zfill(len(`n*n`)) for r in row)

An approach that precalculate corner numbers. Eg, for 9x box, 32 56 72 80, which is (n-1)*4 where n is box sizes (9,7,5,3) in this case.

Right side of those numbers are 1-, and top to bottom is 1+, so basically generate from left to right, top to bottom, bottom to right, right to top side.

$ echo 9 | python codegolf-769-me.py
01 32 31 30 29 28 27 26 25
02 33 56 55 54 53 52 51 24
03 34 57 72 71 70 69 50 23
04 35 58 73 80 79 68 49 22
05 36 59 74 81 78 67 48 21
06 37 60 75 76 77 66 47 20
07 38 61 62 63 64 65 46 19
08 39 40 41 42 43 44 45 18
09 10 11 12 13 14 15 16 17

Other tests

$ echo 2 | python codegolf-769-me.py
1 4
2 3

$ echo 5 | python codegolf-769-me.py
01 16 15 14 13
02 17 24 23 12
03 18 25 22 11
04 19 20 21 10
05 06 07 08 09

$ echo 10 | python codegolf-769-me.py
001 036 035 034 033 032 031 030 029 028
002 037 064 063 062 061 060 059 058 027
003 038 065 084 083 082 081 080 057 026
004 039 066 085 096 095 094 079 056 025
005 040 067 086 097 100 093 078 055 024
006 041 068 087 098 099 092 077 054 023
007 042 069 088 089 090 091 076 053 022
008 043 070 071 072 073 074 075 052 021
009 044 045 046 047 048 049 050 051 020
010 011 012 013 014 015 016 017 018 019


问:
Random Sentence Generator
Write the shortest program you can in any language that reads a context-free grammar from and the number of sentences to produce from stdin, and generates that many random sentences from the grammar.

Input

Input will come in the following format:

```<code>n <START>
{"<A>":["as<A>df","0<A>","<B><C>","A<A>", ...], "<B>":["1<C>1","\<<T>>",...], ...}
</code>```

n is the number of sentences to generate.  <START> is identifier of the starting nonterminal symbol.

The grammar is enclosed in the {} and is formatted as follows:

Rules are of the form "<S>":[productions].  <S> is the identifier of the nonterminal.

Rules are delimited with commas.

The right-hand side of a rule is a double-quoted string whose first and last characters are "<" and ">", respectively. The remaining character should be in [A-Z] (upper-case alpha).

productions is a comma-delimited list of double-quoted strings, representing productions.  All characters, including whitespace, in the rule are terminal symbols, except those that are enclosed in angle brackets ("<" and ">"), which are non-terminal symbols and will be the left-hand side of another rule.  An open angle bracket may be escaped, but there is no need to escape a close angle bracket.

Productions will not contain newlines or the newline escape sequence.

Output

You should print each generated sentence to stdout with a trailing newline.

Test Cases

5 sets of balanced parentheses:

```<code>5 <S>
{"<S>":["<S><S>", "(<S>)", ""]}
</code>```

Example result:

```<code>(())()
()
()()()

(())(()())((((()))()()))
</code>```

4 postfix arithmetic expressions (note whitespace within strings is significant, whitespace elsewhere is not):

```<code>4 <S>
{"<S>":["<N>", "<S> <S> <O>"], "<O>":["+","-","*","/"], "<N>":["<D><N>", "<D>"],
 "<D>":["1","2","3","4","5","6","7","8","9","0"]}
</code>```

Example result:

```<code>1535235 76451 +
973812
312 734 99 3 + / *
1 1 1 1 1 + - * +
</code>```

答:
I felt like doing a little JavaScript.
Also, I cried a little on the inside when I wrote "document.write"

```<code><body>
    <script type='text/javascript'>
    function foo(){
        t=document.getElementById('ta').value.split("\n");
        eval('p='+t[1]);
        t[0]=t[0].split(' ');
        while(t[0][0]--) {
            s=t[0][1]
            while(x=s.match(/<\w+>/)) {
                ps=s;
                s=s.replace(x,p[x][Math.floor(Math.random()*p[x].length)]);
            }
            document.write(s+"<br>");
        }
    }
    </script>
    <textarea id='ta' cols='80'></textarea>
    <button onclick="foo()">go</button>
</body>
</code>```

Input:

```<code>10 <A>
{"<A>":["a<A>b","c<A>d","<B>"],"<B>":["e<C>e"],"<C>":["z","<A>","<B>"]}
</code>```

Output:

```<code>ccaaceeeeezeeeeedbbdd
accccceeeezeeeedddddb
aecezedeb
eaezebe
ccccaacezedbbdddd
eeeaaaceecacezedbdeedbbbeee
acaecaeaaeacccceeeeeeeaeeezeeebeeeeeeeddddbebbebdebdb
aaceezeedbb
aacezedbb
ceeaceecacaacezedbbdbdeedbeed
</code>```

Title: Random Sentence Generator

Body:
I felt like doing a little JavaScript.
Also, I cried a little on the inside when I wrote "document.write"

<body>
    <script type='text/javascript'>
    function foo(){
        t=document.getElementById('ta').value.split("\n");
        eval('p='+t[1]);
        t[0]=t[0].split(' ');
        while(t[0][0]--) {
            s=t[0][1]
            while(x=s.match(/<\w+>/)) {
                ps=s;
                s=s.replace(x,p[x][Math.floor(Math.random()*p[x].length)]);
            }
            document.write(s+"<br>");
        }
    }
    </script>
    <textarea id='ta' cols='80'></textarea>
    <button onclick="foo()">go</button>
</body>

Input:

10 <A>
{"<A>":["a<A>b","c<A>d","<B>"],"<B>":["e<C>e"],"<C>":["z","<A>","<B>"]}

Output:

ccaaceeeeezeeeeedbbdd
accccceeeezeeeedddddb
aecezedeb
eaezebe
ccccaacezedbbdddd
eeeaaaceecacezedbdeedbbbeee
acaecaeaaeacccceeeeeeeaeeezeeebeeeeeeeddddbebbebdebdb
aaceezeedbb
aacezedbb
ceeaceecacaacezedbbdbdeedbeed


问:
Word Spinner Puzzle
This is a word puzzle.

Your program should accept two words on the standard input.

Word one is the start word. Word two is the end word.

From the start word you have to reach the end word changing/add/remove one letter at a time. After each modification it must form a new valid word. Added letters are added to the beginning or end. You can remove letters from any location (but word must not fall bellow three letters in length). Note: You can not rearrange the letters to form a word.

The output of the program is the sequence of words to get from the start word to the end word.

Example:

```<code>Input:
    Post Shot

Output:
    Post
    cost
    coat
    goat
    got
    hot
    shot
</code>```

Winner:

The program must run in a reasonable time (less than a 10 seconds).

The program that can generate the shortest output sequence to the prize words.

Zink -> Silicon

If more than one program gets the shortest sequence then the shortest program in chars (ignoring white space).

If we still have more than one program submission date/time shall be used.

Notes:

Capitalization is not relevant.

The code to build a dictionary does not count towards code cost.

Prize Words and sequence will be generated from:

http://dl.packetstormsecurity.net/Crackers/wordlists/dictionaries/websters-dictionary.gz

答:
Python

Since I couldn't golf dijkstra codes to compress to few hundreds bytes, here is ungolfed version of mine.

import sys, heapq, time

# dijkstra algorithm from
# http://code.activestate.com/recipes/119466-dijkstras-algorithm-for-shortest-paths/
def dijkstra(G, start, end):
   def flatten(L):
      while len(L) > 0:
         yield L[0]
         L = L[1]

   q = [(0, start, ())]
   visited = set()
   while True:
      (cost, v1, path) = heapq.heappop(q)
      if v1 not in visited:
         visited.add(v1)
         if v1 == end:
            return list(flatten(path))[::-1] + [v1]
         path = (v1, path)
         for (v2, cost2) in G[v1].iteritems():
            if v2 not in visited:
               heapq.heappush(q, (cost + cost2, v2, path))

nodes = tuple(sys.argv[1:])

print "Generating connections,",
current_time = time.time()

words = set(x for x in open("websters-dictionary", "rb").read().lower().split() if 3 <= len(x) <= max(5, *[len(l)+1 for l in nodes]))

print len(words), "nodes found"

def error():
    sys.exit("Unreachable Route between '%s' and '%s'" % nodes)

if not all(node in words for node in nodes):
    error()

# following codes are modified version of
# http://norvig.com/spell-correct.html
alphabet = 'abcdefghijklmnopqrstuvwxyz'

def edits(word):
   splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
   deletes = [a + b[1:] for a, b in splits if b]
   replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b]
   prepends = [c+word for c in alphabet]
   appends = [word+c for c in alphabet]
   return words & set(deletes + replaces + prepends + appends)

# Generate connections between nodes to pass to dijkstra algorithm
G = dict((x, dict((y, 1) for y in edits(x))) for x in words)

print "All connections generated, %0.2fs taken" % (time.time() - current_time)
current_time = time.time()

try:
    route = dijkstra(G, *nodes)
    print '\n'.join(route)
    print "%d hops, %0.2fs taken to search shortest path between '%s' & '%s'" % (len(route), time.time() - current_time, nodes[0], nodes[1])
except IndexError:
    error()
```
<p>Tests</p>
<pre class="lang-py prettyprint-override"><code>$ python codegolf-693.py post shot
Generating connections, 15930 nodes found
All connections generated, 2.09s taken
post
host
hot
shot
4 hops, 0.04s taken to search shortest path between 'post' & 'shot'

$ python codegolf-693.py zink silicon
Generating connections, 86565 nodes found
All connections generated, 13.91s taken
zink
pink
pank
pani
panic
pinic
sinic
sinico
silico
silicon
10 hops, 0.75s taken to search shortest path between 'zink' & 'silicon'
</code>```

Added user300's Tests

$ python codegolf-693.py vas arm
Generating connections, 15930 nodes found
All connections generated, 2.06s taken
vas
bas
bam
aam
arm
5 hops, 0.07s taken to search shortest path between 'vas' & 'arm'

$ python codegolf-693.py oxy pom
Generating connections, 15930 nodes found
All connections generated, 2.05s taken
oxy
poxy
pox
pom
4 hops, 0.01s taken to search shortest path between 'oxy' & 'pom'

$ python codegolf-693.py regatta gyrally
Generating connections, 86565 nodes found
All connections generated, 13.95s taken
Unreachable Route between 'regatta' and 'gyrally'
```
<p>Some more</p>
<pre class="lang-py prettyprint-override"><code>$ python codegolf-693.py gap shrend
Generating connections, 56783 nodes found
All connections generated, 8.16s taken
gap
rap
crap
craw
crew
screw
shrew
shrewd
shrend
9 hops, 0.67s taken to search shortest path between 'gap' & 'shrend'

$ python codegolf-693.py guester overturn
Generating connections, 118828 nodes found
All connections generated, 19.63s taken
guester
guesten
gesten
geste
gest
gast
east
ease
erse
verse
verset
overset
oversee
overseed
oversend
oversand
overhand
overhard
overcard
overcare
overtare
overture
overturn
23 hops, 0.82s taken to search shortest path between 'guester' & 'overturn'
</code>```

Title: Word Spinner Puzzle

Body:
Python

Since I couldn't golf dijkstra codes to compress to few hundreds bytes, here is ungolfed version of mine.

import sys, heapq, time

# dijkstra algorithm from
# http://code.activestate.com/recipes/119466-dijkstras-algorithm-for-shortest-paths/
def dijkstra(G, start, end):
   def flatten(L):
      while len(L) > 0:
         yield L[0]
         L = L[1]

   q = [(0, start, ())]
   visited = set()
   while True:
      (cost, v1, path) = heapq.heappop(q)
      if v1 not in visited:
         visited.add(v1)
         if v1 == end:
            return list(flatten(path))[::-1] + [v1]
         path = (v1, path)
         for (v2, cost2) in G[v1].iteritems():
            if v2 not in visited:
               heapq.heappush(q, (cost + cost2, v2, path))

nodes = tuple(sys.argv[1:])

print "Generating connections,",
current_time = time.time()

words = set(x for x in open("websters-dictionary", "rb").read().lower().split() if 3 <= len(x) <= max(5, *[len(l)+1 for l in nodes]))

print len(words), "nodes found"

def error():
    sys.exit("Unreachable Route between '%s' and '%s'" % nodes)

if not all(node in words for node in nodes):
    error()

# following codes are modified version of
# http://norvig.com/spell-correct.html
alphabet = 'abcdefghijklmnopqrstuvwxyz'

def edits(word):
   splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
   deletes = [a + b[1:] for a, b in splits if b]
   replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b]
   prepends = [c+word for c in alphabet]
   appends = [word+c for c in alphabet]
   return words & set(deletes + replaces + prepends + appends)

# Generate connections between nodes to pass to dijkstra algorithm
G = dict((x, dict((y, 1) for y in edits(x))) for x in words)

print "All connections generated, %0.2fs taken" % (time.time() - current_time)
current_time = time.time()

try:
    route = dijkstra(G, *nodes)
    print '\n'.join(route)
    print "%d hops, %0.2fs taken to search shortest path between '%s' & '%s'" % (len(route), time.time() - current_time, nodes[0], nodes[1])
except IndexError:
    error()

Tests

$ python codegolf-693.py post shot
Generating connections, 15930 nodes found
All connections generated, 2.09s taken
post
host
hot
shot
4 hops, 0.04s taken to search shortest path between 'post' & 'shot'

$ python codegolf-693.py zink silicon
Generating connections, 86565 nodes found
All connections generated, 13.91s taken
zink
pink
pank
pani
panic
pinic
sinic
sinico
silico
silicon
10 hops, 0.75s taken to search shortest path between 'zink' & 'silicon'

Added user300's Tests

$ python codegolf-693.py vas arm
Generating connections, 15930 nodes found
All connections generated, 2.06s taken
vas
bas
bam
aam
arm
5 hops, 0.07s taken to search shortest path between 'vas' & 'arm'

$ python codegolf-693.py oxy pom
Generating connections, 15930 nodes found
All connections generated, 2.05s taken
oxy
poxy
pox
pom
4 hops, 0.01s taken to search shortest path between 'oxy' & 'pom'

$ python codegolf-693.py regatta gyrally
Generating connections, 86565 nodes found
All connections generated, 13.95s taken
Unreachable Route between 'regatta' and 'gyrally'

Some more

$ python codegolf-693.py gap shrend
Generating connections, 56783 nodes found
All connections generated, 8.16s taken
gap
rap
crap
craw
crew
screw
shrew
shrewd
shrend
9 hops, 0.67s taken to search shortest path between 'gap' & 'shrend'

$ python codegolf-693.py guester overturn
Generating connections, 118828 nodes found
All connections generated, 19.63s taken
guester
guesten
gesten
geste
gest
gast
east
ease
erse
verse
verset
overset
oversee
overseed
oversend
oversand
overhand
overhard
overcard
overcare
overtare
overture
overturn
23 hops, 0.82s taken to search shortest path between 'guester' & 'overturn'


问:
Golf you a quine for great good!
Using your language of choice, golf a quine.

A quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output.

No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either.

No error quines -- there is already a separate challenge for error quines.

Points for:

Smallest code (in bytes)

Most obfuscated/obscure solution

Using esoteric/obscure languages

Successfully using languages that are difficult to golf in

The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat:

var QUESTION_ID=69;
var OVERRIDE_USER=98;

var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}
function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}
function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=!1;comment_page=1;getComments()}})}
function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}
getAnswers();var SCORE_REG=(function(){var headerTag=String.raw `h\d`
var score=String.raw `\-?\d+\.?\d*`
var normalText=String.raw `[^\n<>]*`
var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
var noDigitText=String.raw `[^\n\d<>]*`
var htmlTag=String.raw `<[^\n<>]+>`
return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}
function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))
body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)
valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,})});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)
lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+a.language+'').text().toLowerCase();languages[lang]=languages[lang]||{lang:a.language,user:a.user,size:a.size,link:a.link,uniq:lang}});var langs=[];for(var lang in languages)
if(languages.hasOwnProperty(lang))
langs.push(languages[lang]);langs.sort(function(a,b){if(a.uniq>b.uniq)return 1;if(a.uniq<b.uniq)return-1;return 0});for(var i=0;i<langs.length;++i)
{var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Winners by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

 ```

答:
Python, 104 bytes

Uses eval and repr

```<code>a = "print 'a','=', repr(eval('a'))\nprint eval('a'),\n"
print 'a','=', repr(eval('a'))
print eval('a'),
</code>```

ContentLicense: CC BY-SA 4.0

Title: Golf you a quine for great good!

Body:
Python, 104 bytes

Uses eval and repr

a = "print 'a','=', repr(eval('a'))\nprint eval('a'),\n"
print 'a','=', repr(eval('a'))
print eval('a'),


问:
Make a directory tree
Imagine for a second that you can compose a tree out of dots.

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

This tree is 13 dots tall.

Now imagine for a second that your filesystem looked like these dots. Your task in this challenge is to make a tree out of folders.

The Challenge

Given an input integer (let's call it n), make a tree out of subdirectories.

In each tree, you should start with a folder called 1.

In that folder, put the folders 1, 2, and 3.

In every level of folder thereon until n-3, in folder 1 of this level of the tree, there should be a folder labelled 1 and 2. In folder 2 of this level of the tree, there should be a folder called 3, in folder 3, a folder called called 4, and so on until the last folder (the integer this folder is called, we'll call k), in which there should be a folder called k and one called k+1.

At level n-3, however, all of the subdirectories but the middle three folders should be replaced with a file with the name that the subdirectories would have had. The middle three subdirectories should remain as subdirectories.

These three subdirectories should contain a folder called 1, 2, or 3 with respect to the order of these directories' name.

These are followed by a layer of files where 1 is in folder 1, 2 is in folder 2, and 3 is in folder three.

The example shown at the top of this question is represented below in folder form.

This would be n = 13.

Rules

You may use builtins for folder creation, but not for subdirectory creation.

All other standard loopholes apply.

You must support past n=5, but do not have to support greater than n=30.

Title: Make a directory tree

Body:
Windows Batch File, <s>429</s> <s>423</s> 404 bytes

md 1
set C= call:
set/a M=%1-2
%C%f 1 1 2 L
%C%f 1 2 2 M
%C%f 1 3 2 R
goto:eof
:f
md %1\%2
set/a P=%2+1
set/a Q=%2+2
set/a L=%3+1
set D= (%C%t %1\%2\%P%
if %L%==%M% (if %4==L .>%1\%2\1
if %Q%==%M%%D%1)else (if %P%==%M%%D%2)else (if %2==%M%%D%3)else .>%1\%2\%P%))
if %4==R .>%1\%2\%Q%
)else (if %4==L%C%f %1\%2 1 %L% L
%C%f %1\%2 %P% %L% M
if %4==R%C%f %1\%2 %Q% %L% R)
goto:eof
:t
md %1\%2
.>%1\%2\%2

Call it with the value of n as a command line parameter.

Here is a visualization of the output tree for n=9:

                   1
                +--+--+
                1  2  3
             +--+  |  +--+
             1  2  3  4  5
          +--+  |  |  |  +--+
          1  2  3  4  5  6  7
       +--+  +  |  |  |  |  +--+
       1  2  3  4  5  6  7  8  9
    +--+  |  |  |  |  |  |  |  +--+
    1  2  3  4  5  6  7  8  9 10 11
 +--+  |  |  |  |  |  |  |  |  |  +--+
 1  2  3  4  5  6  7  8  9 10 11 12 13
                |  |  |
                1  2  3
                |  |  |
                1  2  3


答:
Julia, 113 bytes

~=endof;!t=0t!=0&&1+maximum(!,[t;0])
x::Array+y::Array=(!x,~x)>(!y,~y)?y+x:!x<!y?map(t->x+t,y):~x<~y?[x;0]+y:x.+y
```

<p>Try it online!</p>

<h3>How it works</h3>

<pre class="lang-julia prettyprint-override"><code>~=endof
</code>```

creates a 1-byte alias for endof, which returns the length of an array.

!t=0t!=0&&1+maximum(!,[t;0])
```

<p>defines a depth function. The depth of <strong>t</strong> is zero if and only if <strong>0t == 0</strong>. If not, <strong>t</strong> is an array, and its depth is calculated as the incremented maximum of the depths of its elements and <strong>0</strong>. <code>[t;0]</code> appends a <strong>0</strong> to the array <strong>t</strong>, thus avoiding the need to special-case the empty array.</p>

<p>Julia's built-in sum <strong>+</strong> already behaves like Jelly's sum if either (or both) of its arguments is an integer. However, the sum of two arrays (<strong>+</strong>) requires arrays of the same shape, and even the vectorized sum (<strong>.+</strong>) required arrays that can be broadcast to a common shape.</p>

<p>We redefine <strong>+</strong> for a pair of arrays via</p>

<pre class="lang-julia prettyprint-override"><code>x::Array+y::Array=(!x,~x)>(!y,~y)?y+x:!x<!y?map(t->x+t,y):~x<~y?[x;0]+y:x.+y
</code>```

This does not affect the definition of + for integer/integer, array/integer or integer/array arguments.

(!x,~x)>(!y,~y) lexicographically compares the pairs of depths and lengths of both x and y. If x's depth exceeds y's, or if their depth match and x's length exceeds y's, y+x recursively calls + with swapped arguments.

Otherwise, !x<!y tests if x's depth is lower than y's. If it is, map(t->x+t,y) maps x + · over y.

If the depths match, ~x<~y tests if x is shorter than y. If it is, [x;0]+y recursively calls + after appending a 0 to the left argument.

Finally, if both depths and lengths are identical, x.+y maps + over all elements of x and the corresponding elements of y.

Title: Jam don't add like that

Body:
Background

Jelly's arithmetic atoms vectorize automatically. In fact, x + y is well-defined whenever x and y are numbers or ragged arrays of numbers. Jelly's source code implements this behavior using a generic vectorizer, but for this challenge, we'll only consider addition of integers and nested integer arrays.

Definitions

Define the depth of x as 0 if x is an integer, as 1 if it is a (possibly empty) flat array of integers, and as n + 1 if it contains at least one element of depth n and no elements of depth k > n.

This way, 1 has depth 0, [] and [1] and [1, 1] have depth 1, [[], []] and [[1], [1]] and [[1]] and [1, []] have depth 2, [1, [1, [1]]] has depth 3, etc.

The operation x + y is defined as follows.

If x and y have depth 0, return their sum.

If x and y have equal but positive depths, recursively apply + to all items of x and the corresponding items of y.

If x and y have different lengths, append the tail of the longer array to the array of sums.

Return the result.

If x's depth is strictly smaller than y's depth, recursively apply + to x and all items of y, and return the result.

Do the opposite if y's depth is strictly smaller than x's.

For example, consider the operation [1, [2, 3], [4]] + [[[10, 20], [30], 40, 50], 60].

The depth of the left argument is 2, while the depth of the right argument is 3, so we compute [1, [2, 3], [4]] + [[10, 20], [30], 40, 50] and [1, [2, 3], [4]] + 60.

[1, [2, 3], [4]] and [[10, 20], [30], 40, 50] both have depth 2, so we compute 1 + [10, 20], [2, 3] + [30] and [4] + 40.

1 + [10, 20] = [1 + 10, 1 + 20] = [11, 21]

[2, 3] + [30] = [2 + 30, 3] = [32, 3]

Note that 3 remains untouched, since it doesn't have a matching element.

[4] + 40 = [4 + 40] = [44]

50 doesn't have a matching element, so the result is [[[11, 21], [32, 3], [44], 50]].

[1, [2, 3], [4]] + 60 = [1 + 60, [2, 3] + 60, [4] + 60] = [61, [2 + 60, 3 + 60], [4 + 60]], resulting in [61, [62, 63], [64]].

The final result is [[[11, 21], [32, 3], [44], 50], [61, [62, 63], [64]]].

Task

Write a program or a function that takes two integers, two nested arrays of integers or a combination thereof as input and returns their sum, as defined above.

If your language has multiple array-like types (lists, tuples, vectors, etc.) you may choose any of them for your answer. The return type must match the argument type.

To prevent boring and unbeatable solutions, if a language has this exact operation as a built-in, you may not use that language.

All built-ins of all other languages are allowed. If your language of choice permits this, you may overload and/or redefine the built-in addition.

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

Test cases

```<code>0 + 0                           = 0
[-1, 0, -1] + [1]               = [0, 0, -1]
[] + [0]                        = [0]
[] + 0                          = []
[] + []                         = []
[[], 0] + []                    = [[], []]
[1, 2, 3] + 10                  = [11, 12, 13]
[1, 2, 3] + [10]                = [11, 2, 3]
[1, 2, 3] + [10, [20]]          = [[11, 12, 13], [21, 2, 3]]
[1, 2, 3, []] + [10, [20]]      = [11, [22], 3, []]
[1, [2, [3, [4]]]] + [10, [20]] = [[11, [21]], [[12, [22]], [13, [24]]]]
</code>```

To generate more test cases, you can use this Jelly program.

Body:
Julia, 113 bytes

~=endof;!t=0t!=0&&1+maximum(!,[t;0])
x::Array+y::Array=(!x,~x)>(!y,~y)?y+x:!x<!y?map(t->x+t,y):~x<~y?[x;0]+y:x.+y

<a href="http://julia.tryitonline.net/#code=fj1lbmRvZjshdD0wdCE9MCYmMSttYXhpbXVtKCEsW3Q7MF0pCng6OkFycmF5K3k6OkFycmF5PSgheCx-eCk-KCF5LH55KT95K3g6IXg8IXk_bWFwKHQtPngrdCx5KTp-eDx-eT9beDswXSt5OnguK3kKCmZvciByZXN1bHQgaW4gKAogICAgMCArIDAsCiAgICBBbnlbLTEsIDAsIC0xXSArIEFueVsxXSwKICAgIEFueVtdICsgQW55WzBdLAogICAgQW55W10gKyAwLAogICAgQW55W10gKyBBbnlbXSwKICAgIEFueVtBbnlbXSwgMF0gKyBBbnlbXSwKICAgIEFueVsxLCAyLCAzXSArIDEwLAogICAgQW55WzEsIDIsIDNdICsgQW55WzEwXSwKICAgIEFueVsxLCAyLCAzXSArIEFueVsxMCwgQW55WzIwXV0sCiAgICBBbnlbMSwgMiwgMywgQW55W11dICsgQW55WzEwLCBBbnlbMjBdXSwKICAgIEFueVsxLCBBbnlbMiwgQW55WzMsIEFueVs0XV1dXSArIEFueVsxMCwgQW55WzIwXV0KKQogICAgcHJpbnRsbihyZXN1bHQpCmVuZA&input=" rel="nofollow">Try it online!

How it works

~=endof

creates a 1-byte alias for endof, which returns the length of an array.

!t=0t!=0&&1+maximum(!,[t;0])

defines a depth function. The depth of t is zero if and only if 0t == 0. If not, t is an array, and its depth is calculated as the incremented maximum of the depths of its elements and 0. [t;0] appends a 0 to the array t, thus avoiding the need to special-case the empty array.

Julia's built-in sum + already behaves like Jelly's sum if either (or both) of its arguments is an integer. However, the sum of two arrays (+) requires arrays of the same shape, and even the vectorized sum (.+) required arrays that can be broadcast to a common shape.

We redefine + for a pair of arrays via

x::Array+y::Array=(!x,~x)>(!y,~y)?y+x:!x<!y?map(t->x+t,y):~x<~y?[x;0]+y:x.+y

This does not affect the definition of + for integer/integer, array/integer or integer/array arguments.

(!x,~x)>(!y,~y) lexicographically compares the pairs of depths and lengths of both x and y. If x's depth exceeds y's, or if their depth match and x's length exceeds y's, y+x recursively calls + with swapped arguments.

Otherwise, !x<!y tests if x's depth is lower than y's. If it is, map(t->x+t,y) maps x + · over y.

If the depths match, ~x<~y tests if x is shorter than y. If it is, [x;0]+y recursively calls + after appending a 0 to the left argument.

Finally, if both depths and lengths are identical, x.+y maps + over all elements of x and the corresponding elements of y.


问:
Generate a "GitHub" Avatar

Background / Description

Note: as @HelkaHomba points out, the actual GitHub identicons are not actually random but based on the hash of a username

The default GitHub avatar is a 5x5-pixel image. A color is picked randomly, and then random pixels are filled in on one side (right or left, 2x5 size) using that color. Then that side is copied & flipped to the other side, across the y-axis. The pixels left over that are not filled in are #F0F0F0, or rgb(240,240,240).

The center column's pixels (1x5 size) are then randomly filled in, using the same color as previously.

Output

Note: for this challenge we will ignore the space that encloses the GitHub avatars

The program should output a 5x5 pixel image file. See http://meta.codegolf.stackexchange.com/a/9095/42499 for specifics

Examples

Note: these were obviously scaled up from 5x5 so you can see them

Good luck!

答:
Pyth - 27 bytes

```<code>.wC+Kc3O^Cm,240O256 3 15_PK
</code>```

Obviously doesn't work online, but you can have it print color codes here.

Title: Generate a "GitHub" Avatar

Body:
Pyth - 27 bytes

.wC+Kc3O^Cm,240O256 3 15_PK

Obviously doesn't work online, but you can have it print color codes here.


答:
MATL, <s>36</s> 29 bytes

```<code>5l$rtP+!kllII$r*O16tQ/XE'a'YG
</code>```

This saves the result in file a.png.

Replacing 'a' by 2 in the code displays the image (scaled up) instead of saving a file:

```<code>5l$rtP+!kllII$r*O16tQ/XE2YG
</code>```

Here's an example output:

Explanation

```<code>5l$r     % 5×5 matrix of independent random values with uniform distribution
         % on the interval (0,1)
tP+!     % Duplicate, flip vertically, add, transpose. This gives a horizontally
         % symetric matrix. Center column pixels are uniformly distributed on the
         % interval (0,2). Rest have a triangular distribution on (0,2)
k        % Round down. In either of the above cases, this gives 0 and 1
         % with the same probability
llII$r   % 1×1×3 array of independent random numbers with uniform distribution
         % on (0,1). This is the foreground color.
*        % Multiply the two arrays with broadcast. Gives a 5×5×3 array. Ones in the
         % 5×5 array become the random foreground color. Zeros remain as zeros.
O        % Push 0
16tQ/    % 16, duplicate, add 1, divide: gives 16/17, or 240/255
XE       % Replace 0 by 16/17: background color
'a'      % Push file name
YG       % Write image to that file
</code>```

Title: Generate a "GitHub" Avatar

Body:
Background / Description

Note: as @HelkaHomba points out, the actual GitHub identicons are not actually random but based on the hash of a username

The default GitHub avatar is a 5x5-pixel image. A color is picked randomly, and then random pixels are filled in on one side (right or left, 2x5 size) using that color. Then that side is copied & flipped to the other side, across the y-axis. The pixels left over that are not filled in are #F0F0F0, or rgb(240,240,240).

The center column's pixels (1x5 size) are then randomly filled in, using the same color as previously.

Output

Note: for this challenge we will ignore the space that encloses the GitHub avatars

The program should output a 5x5 pixel image file. See http://meta.codegolf.stackexchange.com/a/9095/42499 for specifics

Examples

Note: these were obviously scaled up from 5x5 so you can see them

Good luck!

Body:
MATL, <s>36</s> 29 bytes

5l$rtP+!kllII$r*O16tQ/XE'a'YG

This saves the result in file a.png.

Replacing 'a' by 2 in the code displays the image (scaled up) instead of saving a file:

5l$rtP+!kllII$r*O16tQ/XE2YG

Here's an example output:

Explanation

5l$r     % 5×5 matrix of independent random values with uniform distribution
         % on the interval (0,1)
tP+!     % Duplicate, flip vertically, add, transpose. This gives a horizontally
         % symetric matrix. Center column pixels are uniformly distributed on the
         % interval (0,2). Rest have a triangular distribution on (0,2)
k        % Round down. In either of the above cases, this gives 0 and 1
         % with the same probability
llII$r   % 1×1×3 array of independent random numbers with uniform distribution
         % on (0,1). This is the foreground color.
*        % Multiply the two arrays with broadcast. Gives a 5×5×3 array. Ones in the
         % 5×5 array become the random foreground color. Zeros remain as zeros.
O        % Push 0
16tQ/    % 16, duplicate, add 1, divide: gives 16/17, or 240/255
XE       % Replace 0 by 16/17: background color
'a'      % Push file name
YG       % Write image to that file


问:
Faro shuffle an array
A Faro shuffle is a technique frequently used by magicians to "shuffle" a deck. To perform a Faro shuffle you first cut the deck into 2 equal halves then you interleave the two halves. For example

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

Faro shuffled is

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

This can be repeated any number of times. Interestingly enough, if you repeat this enough times, you will always end up back at the original array. For example:

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

Notice that 1 stays on the bottom and 8 stays on the top. That makes this an outer-shuffle. This is an important distinction.

The Challenge

Given an array of integers A, and a number N, output the array after N Faro shuffles. A may contain repeated or negative elements, but it will always have an even number of elements. You can assume the array will not be empty. You can also assume that N will be a non-negative integer, although it may be 0. You can take these inputs in any reasonable manner. The shortest answer in bytes wins!

Test IO:

```<code>#N, A,                                              Output
1,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 5, 2, 6, 3, 7, 4, 8]
2,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 3, 5, 7, 2, 4, 6, 8]
7,  [-23, -37, 52, 0, -6, -7, -8, 89]               [-23, -6, -37, -7, 52, -8, 0, 89]
0,  [4, 8, 15, 16, 23, 42]                          [4, 8, 15, 16, 23, 42]
11, [10, 11, 8, 15, 13, 13, 19, 3, 7, 3, 15, 19]    [10, 19, 11, 3, 8, 7, 15, 3, 13, 15, 13, 19]
</code>```

And, a massive test case:

```<code>23, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
</code>```

Should output:

```<code>[1, 30, 59, 88, 18, 47, 76, 6, 35, 64, 93, 23, 52, 81, 11, 40, 69, 98, 28, 57, 86, 16, 45, 74, 4, 33, 62, 91, 21, 50, 79, 9, 38, 67, 96, 26, 55, 84, 14, 43, 72, 2, 31, 60, 89, 19, 48, 77, 7, 36, 65, 94, 24, 53, 82, 12, 41, 70, 99, 29, 58, 87, 17, 46, 75, 5, 34, 63, 92, 22, 51, 80, 10, 39, 68, 97, 27, 56, 85, 15, 44, 73, 3, 32, 61, 90, 20, 49, 78, 8, 37, 66, 95, 25, 54, 83, 13, 42, 71, 100]
</code>```

答:
Pyth - <s>8</s> 7 bytes

saved 1 byte thanks to @issacg

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

Try it online here.

Title: Faro shuffle an array

Body:
Pyth - <s>8</s> 7 bytes

saved 1 byte thanks to @issacg

usCc2GE

<a href="http://pyth.herokuapp.com/?code=usCc2GE&input=%5B1%2C+2%2C+3%2C+4%2C+5%2C+6%2C+7%2C+8%2C+9%2C+10%2C+11%2C+12%2C+13%2C+14%2C+15%2C+16%2C+17%2C+18%2C+19%2C+20%2C+21%2C+22%2C+23%2C+24%2C+25%2C+26%2C+27%2C+28%2C+29%2C+30%2C+31%2C+32%2C+33%2C+34%2C+35%2C+36%2C+37%2C+38%2C+39%2C+40%2C+41%2C+42%2C+43%2C+44%2C+45%2C+46%2C+47%2C+48%2C+49%2C+50%2C+51%2C+52%2C+53%2C+54%2C+55%2C+56%2C+57%2C+58%2C+59%2C+60%2C+61%2C+62%2C+63%2C+64%2C+65%2C+66%2C+67%2C+68%2C+69%2C+70%2C+71%2C+72%2C+73%2C+74%2C+75%2C+76%2C+77%2C+78%2C+79%2C+80%2C+81%2C+82%2C+83%2C+84%2C+85%2C+86%2C+87%2C+88%2C+89%2C+90%2C+91%2C+92%2C+93%2C+94%2C+95%2C+96%2C+97%2C+98%2C+99%2C+100%5D%0A23&debug=0" rel="nofollow noreferrer">Try it online here.


答:
Jelly, <s>9</s> 7 bytes

2 bytes thanks to Dennis!

```<code>œs2ZFð¡
</code>```

Try it online!

Explanation

```<code>œs2ZFð¡  Main dyadic chain. Arguments: x,y
      ¡  Repeat the following y time:
œs2          Split into two.
   Z         Transpose.
    F        Flatten.
</code>```

Previous 9-byte version:

```<code>œs2ZF
Ç⁴¡
</code>```

Try it online!

Title: Faro shuffle an array

Body:
A Faro shuffle is a technique frequently used by magicians to "shuffle" a deck. To perform a Faro shuffle you first cut the deck into 2 equal halves then you interleave the two halves. For example

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

Faro shuffled is

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

This can be repeated any number of times. Interestingly enough, if you repeat this enough times, you will always end up back at the original array. For example:

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

Notice that 1 stays on the bottom and 8 stays on the top. That makes this an outer-shuffle. This is an important distinction.

The Challenge

Given an array of integers A, and a number N, output the array after N Faro shuffles. A may contain repeated or negative elements, but it will always have an even number of elements. You can assume the array will not be empty. You can also assume that N will be a non-negative integer, although it may be 0. You can take these inputs in any reasonable manner. The shortest answer in bytes wins!

Test IO:

```<code>#N, A,                                              Output
1,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 5, 2, 6, 3, 7, 4, 8]
2,  [1, 2, 3, 4, 5, 6, 7, 8]                        [1, 3, 5, 7, 2, 4, 6, 8]
7,  [-23, -37, 52, 0, -6, -7, -8, 89]               [-23, -6, -37, -7, 52, -8, 0, 89]
0,  [4, 8, 15, 16, 23, 42]                          [4, 8, 15, 16, 23, 42]
11, [10, 11, 8, 15, 13, 13, 19, 3, 7, 3, 15, 19]    [10, 19, 11, 3, 8, 7, 15, 3, 13, 15, 13, 19]
</code>```

And, a massive test case:

```<code>23, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
</code>```

Should output:

```<code>[1, 30, 59, 88, 18, 47, 76, 6, 35, 64, 93, 23, 52, 81, 11, 40, 69, 98, 28, 57, 86, 16, 45, 74, 4, 33, 62, 91, 21, 50, 79, 9, 38, 67, 96, 26, 55, 84, 14, 43, 72, 2, 31, 60, 89, 19, 48, 77, 7, 36, 65, 94, 24, 53, 82, 12, 41, 70, 99, 29, 58, 87, 17, 46, 75, 5, 34, 63, 92, 22, 51, 80, 10, 39, 68, 97, 27, 56, 85, 15, 44, 73, 3, 32, 61, 90, 20, 49, 78, 8, 37, 66, 95, 25, 54, 83, 13, 42, 71, 100]
</code>```

Body:
Jelly, <s>9</s> 7 bytes

2 bytes thanks to Dennis!

œs2ZFð¡

Try it online!

Explanation

œs2ZFð¡  Main dyadic chain. Arguments: x,y
      ¡  Repeat the following y time:
œs2          Split into two.
   Z         Transpose.
    F        Flatten.

Previous 9-byte version:

œs2ZF
Ç⁴¡

Try it online!


答:
Python, <s>68</s> 57 bytes

f=lambda n,x:n and f(n-1,sum(zip(x,x[len(x)/2:]),()))or x
```

Thanks to @Sp3000 for golfing off 11 bytes!

Test it on Ideone.

Title: Faro shuffle an array

Body:
Python, <s>68</s> 57 bytes

f=lambda n,x:n and f(n-1,sum(zip(x,x[len(x)/2:]),()))or x

Thanks to @Sp3000 for golfing off 11 bytes!

Test it on Ideone.


答:
MATL, 11 bytes

```<code>w:"tn2/e!1e
</code>```

Thanks to @Dennis for a correction

Try it online!

Explanation

```<code>w         % Take the two inputs N and A. Swap them
:         % Generate [1 2 ... N]
"         % Repeat N times
  tn2/    %   Duplicate A. Number of elements divided by 2
  e       %   Reshape to that number of rows
  !       %   Transpose
  1e      %   Reshape to one row
          % End (implicit)
          % Display (implicit)
</code>```

Title: Faro shuffle an array

Body:
MATL, 11 bytes

w:"tn2/e!1e

Thanks to @Dennis for a correction

<a href="http://matl.tryitonline.net/#code=dzoidG4yL2UhMWU&input=MjMKWzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDksIDEwLCAxMSwgMTIsIDEzLCAxNCwgMTUsIDE2LCAxNywgMTgsIDE5LCAyMCwgMjEsIDIyLCAyMywgMjQsIDI1LCAyNiwgMjcsIDI4LCAyOSwgMzAsIDMxLCAzMiwgMzMsIDM0LCAzNSwgMzYsIDM3LCAzOCwgMzksIDQwLCA0MSwgNDIsIDQzLCA0NCwgNDUsIDQ2LCA0NywgNDgsIDQ5LCA1MCwgNTEsIDUyLCA1MywgNTQsIDU1LCA1NiwgNTcsIDU4LCA1OSwgNjAsIDYxLCA2MiwgNjMsIDY0LCA2NSwgNjYsIDY3LCA2OCwgNjksIDcwLCA3MSwgNzIsIDczLCA3NCwgNzUsIDc2LCA3NywgNzgsIDc5LCA4MCwgODEsIDgyLCA4MywgODQsIDg1LCA4NiwgODcsIDg4LCA4OSwgOTAsIDkxLCA5MiwgOTMsIDk0LCA5NSwgOTYsIDk3LCA5OCwgOTksIDEwMF0K" rel="nofollow noreferrer">Try it online!

Explanation

w         % Take the two inputs N and A. Swap them
:         % Generate [1 2 ... N]
"         % Repeat N times
  tn2/    %   Duplicate A. Number of elements divided by 2
  e       %   Reshape to that number of rows
  !       %   Transpose
  1e      %   Reshape to one row
          % End (implicit)
          % Display (implicit)


Title: Faro shuffle an array

Body:
J, <s>22</s> <s>19</s> 17 bytes

3 bytes thanks to @Gareth.

2 bytes thanks to @algorithmshark.

-:@#({.,@,.}.)]^:

Usage

>> f =: -:@#({.,@,.}.)]^:
>> 2 f 1 2 3 4 5 6 7 8
<< 1 3 5 7 2 4 6 8

Where >> is STDIN and << is STDOUT.

Previous 22-byte version:

({~[:,/@|:@i.2,-:@#)^:

Usage

>> f =: ({~[:,/@|:@i.2,-:@#)^:
>> 2 f 1 2 3 4 5 6 7 8
<< 1 3 5 7 2 4 6 8

Where >> is STDIN and << is STDOUT.