问:
Electrical outlet
This is a problem from NCPC 2005.  Roy has
an apartment with only one single electrical outlet, but he has a bunch of power strips.
Compute the maximum number of outlets he can have using the power strips he
has.  The number of outlets per power strip is given as input.

It turns out that if the number of outlets of the strips respectively are

$$p_1,  p_2, \dots, p_n$$

then the number of outlets is
$$1 - n + \sum_i p_i$$ ,

or

$$1 + p_1-1 + p_2-1 + \dots + p_n-1$$.

The input to the program or function is a non-empty series of positive integers.

Examples

```<code>2 3 4
> 7
2 4 6
> 10
1 1 1 1 1 1 1 1
> 1
100 1000 10000
> 11098
</code>```

答:
Mornington Crescent, <s> 1909 1873 </s> 1839 bytes

```<code>Take Northern Line to Stockwell
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Turnham Green
Take District Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Bank
Take Circle Line to Embankment
Take Northern Line to Stockwell
Take Northern Line to Embankment
Take Circle Line to Temple
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Blackfriars
Take Circle Line to Embankment
Take District Line to Parsons Green
Take District Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Parsons Green
Take District Line to Embankment
Take Circle Line to Blackfriars
Take Circle Line to Bank
Take Northern Line to Angel
Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent
</code>```

Try it online!

Title: Electrical outlet

Body:
Mornington Crescent, <s> 1909 1873 </s> 1839 bytes

Take Northern Line to Stockwell
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Turnham Green
Take District Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Bank
Take Circle Line to Embankment
Take Northern Line to Stockwell
Take Northern Line to Embankment
Take Circle Line to Temple
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Blackfriars
Take Circle Line to Embankment
Take District Line to Parsons Green
Take District Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Upminster
Take District Line to Becontree
Take District Line to Parsons Green
Take District Line to Embankment
Take Circle Line to Blackfriars
Take Circle Line to Bank
Take Northern Line to Angel
Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent

Try it online!


问:
Do these squares overlap?
Given the coordinates of the upper left corners of two squares and their side lengths, determine whether the squares overlap. A square includes the top and left lines, but not the bottom and right lines. That is, a point (a,b) is inside a square with side length k that starts at (x,y) if and only if x <= a < x+k and y <= b < y+k. A square with side length 0 is degenerate and will not be considered here, thus, k will be positive.

As usual, all standard rules apply. Input and output may be in whatever form is convenient, so long as it's human readable and there is no precomputation. Be sure to specify what input format you use. Your code should take six numbers and output truthy if the squares overlap and falsy otherwise.

Test Cases

```<code>x1 y1 k1  x2 y2 k2  overlap?
 1  1  1   0  1  1  false
 0  0  3   1  1  1  true
 1  1  1   0  0  3  true
 0  0  3   2  1  2  true
 0  0  2   1  1  2  true
 1  1  2   0  0  2  true
 0  1  2   1  0  2  true
 1  0  2   0  1  2  true
 2  0  2   0  2  2  false
 1  0  3   0  1  1  false
 0  2  3   0  0  2  false
</code>```

All inputs will be non-negative integers. That said, I expect that many or most solutions will also be able to handle negatives and floats.

答:
MATLAB, <s>36</s> 21 bytes

```<code>@(a,b)a-flip(a)<[b,b]
</code>```

Creates an anonymous function which can be evaluated as ans(a,b). Accepts two inputs of the following format:

2 x 2 matrix containing the corner of each square as a row: [x1, y1; x2, y2].

2 x 1 array containing the size of the two squares: [k2; k1]

All test cases here.

Explanation

Here is a commented un-golfed solution

```<code>%// Example input
a = [1 1;
     0 1];

b = [1; 1];

%// Flip a along the first dimension and subtract from a to yield:
%//
%// [x1-x2   y1-y2]
%// [x2-x1   y2-y1]
d = a - flip(a);

%// Compare this matrix element-wise with two horizontally concatenated copies
%// of the second input [k2; k1]
result = d < [b,b];

%// Truthy values have all ones in the result and falsey values have at
%// least one 0 in the result.
</code>```

ContentLicense: CC BY-SA 3.0

Title: Do these squares overlap?

Body:
MATLAB, <s>36</s> 21 bytes

@(a,b)a-flip(a)<[b,b]

Creates an anonymous function which can be evaluated as ans(a,b). Accepts two inputs of the following format:

2 x 2 matrix containing the corner of each square as a row: [x1, y1; x2, y2].

2 x 1 array containing the size of the two squares: [k2; k1]

All test cases here.

Explanation

Here is a commented un-golfed solution

%// Example input
a = [1 1;
     0 1];

b = [1; 1];

%// Flip a along the first dimension and subtract from a to yield:
%//
%// [x1-x2   y1-y2]
%// [x2-x1   y2-y1]
d = a - flip(a);

%// Compare this matrix element-wise with two horizontally concatenated copies
%// of the second input [k2; k1]
result = d < [b,b];

%// Truthy values have all ones in the result and falsey values have at
%// least one 0 in the result.


答:
MATL, <s>14</s> <s>11</s> <s>10</s> <s>5</s> 4 bytes

```<code>tP->
</code>```

This solution accepts input in the form of two arrays:

A 2 x 2 matrix that contains the coordinates of the corners [x1, y1; x2, y2]

A 2 x 1 array containing the square dimensions [k2; k1]

Try it Online

Slightly modified version to run all test cases

Explanation

```<code>        % Implicitly grab the first input
t       % Duplicate the input
P       % Flip along the first dimension (columns)
-       % Subtract the two to yield [x1-x2, y1-y2; x2-x1, y2-y1]
        % Implicitly grab the second input
>       % Compare with [k2, k1] (automatically broadcasts)
        % Implicitly display the truthy/falsey result
</code>```

Title: Do these squares overlap?

Body:
Given the coordinates of the upper left corners of two squares and their side lengths, determine whether the squares overlap. A square includes the top and left lines, but not the bottom and right lines. That is, a point (a,b) is inside a square with side length k that starts at (x,y) if and only if x <= a < x+k and y <= b < y+k. A square with side length 0 is degenerate and will not be considered here, thus, k will be positive.

As usual, all standard rules apply. Input and output may be in whatever form is convenient, so long as it's human readable and there is no precomputation. Be sure to specify what input format you use. Your code should take six numbers and output truthy if the squares overlap and falsy otherwise.

Test Cases

```<code>x1 y1 k1  x2 y2 k2  overlap?
 1  1  1   0  1  1  false
 0  0  3   1  1  1  true
 1  1  1   0  0  3  true
 0  0  3   2  1  2  true
 0  0  2   1  1  2  true
 1  1  2   0  0  2  true
 0  1  2   1  0  2  true
 1  0  2   0  1  2  true
 2  0  2   0  2  2  false
 1  0  3   0  1  1  false
 0  2  3   0  0  2  false
</code>```

All inputs will be non-negative integers. That said, I expect that many or most solutions will also be able to handle negatives and floats.

Body:
MATL, <s>14</s> <s>11</s> <s>10</s> <s>5</s> 4 bytes

tP->

This solution accepts input in the form of two arrays:

A 2 x 2 matrix that contains the coordinates of the corners [x1, y1; x2, y2]

A 2 x 1 array containing the square dimensions [k2; k1]

Try it Online

Slightly modified version to run all test cases

Explanation

        % Implicitly grab the first input
t       % Duplicate the input
P       % Flip along the first dimension (columns)
-       % Subtract the two to yield [x1-x2, y1-y2; x2-x1, y2-y1]
        % Implicitly grab the second input
>       % Compare with [k2, k1] (automatically broadcasts)
        % Implicitly display the truthy/falsey result


问:
Zeroes at the end of a factorial
Write a program or function that finds the number of zeroes at the end of n! in base 10, where n is an input number (in any desired format).

It can be assumed that n is a positive integer, meaning that n! is also an integer. There are no zeroes after a decimal point in n!. Also, it can be assumed that your programming language can handle the value of n and n!.

Test cases

```<code>1
==> 0

5
==> 1

100
==> 24

666
==> 165

2016
==> 502

1234567891011121314151617181920
==> 308641972752780328537904295461
</code>```

This is code golf. Standard rules apply. The shortest code in bytes wins.

答:
Python 2, 27 bytes

f=lambda n:n and n/5+f(n/5)
```

The ending zeroes are limited by factors of 5. The number of multiples of 5 that are at most n is n/5 (with floor division), but this doesn't count the repeated factors in multiples of 25, 125, .... To get those, divide n by 5 and recurse.

Title: Zeroes at the end of a factorial

Body:
Python 2, 27 bytes

f=lambda n:n and n/5+f(n/5)

The ending zeroes are limited by factors of 5. The number of multiples of 5 that are at most n is n/5 (with floor division), but this doesn't count the repeated factors in multiples of 25, 125, .... To get those, divide n by 5 and recurse.


答:
Python 3, 52 bytes

```<code>g=lambda x,y=1,z=0:z-x if y>x else g(x,y*5,z+x//y)
</code>```

Title: Zeroes at the end of a factorial

Body:
Write a program or function that finds the number of zeroes at the end of n! in base 10, where n is an input number (in any desired format).

It can be assumed that n is a positive integer, meaning that n! is also an integer. There are no zeroes after a decimal point in n!. Also, it can be assumed that your programming language can handle the value of n and n!.

Test cases

```<code>1
==> 0

5
==> 1

100
==> 24

666
==> 165

2016
==> 502

1234567891011121314151617181920
==> 308641972752780328537904295461
</code>```

This is code golf. Standard rules apply. The shortest code in bytes wins.

Body:
Python 3, 52 bytes

g=lambda x,y=1,z=0:z-x if y>x else g(x,y*5,z+x//y)


答:
JavaScript ES6, 20 bytes

```<code>f=x=>x&&x/5+f(x/5)|0
</code>```

Same tactic as in xnor's answer, but shorter.

Title: Zeroes at the end of a factorial

Body:
JavaScript ES6, 20 bytes

f=x=>x&&x/5+f(x/5)|0

Same tactic as in xnor's answer, but shorter.


答:
J, <s>28</s> <s>17</s> 16 bytes

```<code><.@+/@(%5^>:@i.)
</code>```

Pretty much the same as the non-recursive technique from xnor's answer.

Here's an older version I have kept here because I personally like it more, clocking in at 28 bytes:

```<code>+/@>@{:@(0<;._1@,'0'&=@":@!)
</code>```

Whilst not needed, I have included x: in the test cases for extended precision.

```<code>   tf0 =: +/@>@{:@(0<;._1@,'0'&=@":@!@x:)
   tf0 5
1
   tf0 100
24

   tf0g =: tf0"0
   tf0g 1 5 100 666 2016
0 1 24 165 502
</code>```

The last number  doesn't work with this function.

Explanation

This works by calculating n!, converting it to a string, and checking each member for equality with '0'. For n = 15, this process would be:

```<code>15
15! => 1307674368000
": 1307674368000 => '1307674368000'
'0' = '1307674368000' => 0 0 1 0 0 0 0 0 0 0 1 1 1
</code>```

Now, we use ;._1 to split the list on its first element (zero), boxing each split result, yielding a box filled with aces (a:) or runs of 1s, like so:

```<code>┌┬─┬┬┬┬┬┬┬─────┐
││1│││││││1 1 1│
└┴─┴┴┴┴┴┴┴─────┘
</code>```

We simple obtain the last member ({:), unbox it (>), and perform a summation over it +/, yielding the number of zeroes.

Here is the more readable version:

```<code>split =: <;._1@,
tostr =: ":
is =: =
last =: {:
unbox =: >
sum =: +/
precision =: x:
n =: 15

NB. the function itself
tf0 =: sum unbox last 0 split '0' is tostr ! precision n
tf0 =: sum @ unbox @ last @ (0 split '0'&is @ tostr @ ! @ precision)
tf0 =: +/ @ > @ {: @ (0 <;._1@, '0'&= @ ": @ ! )
</code>```

Title: Zeroes at the end of a factorial

Body:
J, <s>28</s> <s>17</s> 16 bytes

<.@+/@(%5^>:@i.)

Pretty much the same as the non-recursive technique from xnor's answer.

Here's an older version I have kept here because I personally like it more, clocking in at 28 bytes:

+/@>@{:@(0<;._1@,'0'&=@":@!)

Whilst not needed, I have included x: in the test cases for extended precision.

   tf0 =: +/@>@{:@(0<;._1@,'0'&=@":@!@x:)
   tf0 5
1
   tf0 100
24

   tf0g =: tf0"0
   tf0g 1 5 100 666 2016
0 1 24 165 502

The last number  doesn't work with this function.

Explanation

This works by calculating n!, converting it to a string, and checking each member for equality with '0'. For n = 15, this process would be:

15
15! => 1307674368000
": 1307674368000 => '1307674368000'
'0' = '1307674368000' => 0 0 1 0 0 0 0 0 0 0 1 1 1

Now, we use ;._1 to split the list on its first element (zero), boxing each split result, yielding a box filled with aces (a:) or runs of 1s, like so:

┌┬─┬┬┬┬┬┬┬─────┐
││1│││││││1 1 1│
└┴─┴┴┴┴┴┴┴─────┘

We simple obtain the last member ({:), unbox it (>), and perform a summation over it +/, yielding the number of zeroes.

Here is the more readable version:

split =: <;._1@,
tostr =: ":
is =: =
last =: {:
unbox =: >
sum =: +/
precision =: x:
n =: 15

NB. the function itself
tf0 =: sum unbox last 0 split '0' is tostr ! precision n
tf0 =: sum @ unbox @ last @ (0 split '0'&is @ tostr @ ! @ precision)
tf0 =: +/ @ > @ {: @ (0 <;._1@, '0'&= @ ": @ ! )


答:
Haskell, 26 bytes

f 0=0
f n=(+)=<<f$div n 5
```

<p>Floor-divides the input by <code>5</code>, then adds the result to the function called on it. The expression <code>(+)=<<f</code> takes an input <code>x</code> and outputs <code>x+(f x)</code>.</p>

<p>Shortened from:</p>

<pre class="lang-haskell prettyprint-override"><code>f 0=0
f n=div n 5+f(div n 5)

f 0=0
f n|k<-div n 5=k+f k
</code>```

A non-recursive expression gave 28 bytes:

f n=sum[n`div`5^i|i<-[1..n]]
```

Title: Zeroes at the end of a factorial

Body:
Haskell, 26 bytes

f 0=0
f n=(+)=<<f$div n 5

Floor-divides the input by 5, then adds the result to the function called on it. The expression (+)=<<f takes an input x and outputs x+(f x).

Shortened from:

f 0=0
f n=div n 5+f(div n 5)

f 0=0
f n|k<-div n 5=k+f k

A non-recursive expression gave 28 bytes:

f n=sum[n`div`5^i|i<-[1..n]]


答:
Jolf, 13 bytes

```<code>Ώmf?H+γ/H5ΏγH
</code>```

Defines a recursive function which is called on the input. Try it here!

```<code>Ώmf?H+γ/H5ΏγH  Ώ(H) = floor(H ? (γ = H/5) + Ώ(γ) : H)
Ώ              Ώ(H) =
       /H5                           H/5
      γ                         (γ =    )
     +    Ώγ                              + Ώ(γ)
   ?H       H               H ?                  : H
 mf                   floor(                        )
               // called implicitly with input
</code>```

Title: Zeroes at the end of a factorial

Body:
Jolf, 13 bytes

Ώmf?H+γ/H5ΏγH

Defines a recursive function which is called on the input. Try it here!

Ώmf?H+γ/H5ΏγH  Ώ(H) = floor(H ? (γ = H/5) + Ώ(γ) : H)
Ώ              Ώ(H) =
       /H5                           H/5
      γ                         (γ =    )
     +    Ώγ                              + Ώ(γ)
   ?H       H               H ?                  : H
 mf                   floor(                        )
               // called implicitly with input


问:
Read n random lines from a potentially huge file
This challenge is about reading random lines from a potentially huge file without reading the whole file into memory.

Input

An integer n and the name of a text file.

Output

n lines of the text file chosen uniformly at random without replacement.

You can assume that n is in the range 1 to the number of lines in the file.

Be careful when sampling n numbers at random from the range that the answer you get is uniform. rand()%n in C is not uniform for example. Every outcome must be equally likely.

Rules and restrictions

Each line of the text file will have the same number of characters and that will be no more than 80.

Your code must not read any of the contents of text file except:

Those lines it outputs.

The first line to work out how many characters per line there are in the text file.

We can assume each character in the text file takes exactly one byte.

Line separators are assumed to be 1 byte long. Solutions may use 2 bytes long line separators only if they specify this need. You may also assume the last line is terminated by a line separator.

Your answer should be a complete program but you can specify the input in any way that is convenient.

Languages and libraries

You can use any language or library you like.

Notes

There was a concern about calculating the number of lines in the file. As nimi points out in the comments, you can infer this from the file size and the number of chars per line.

Motivation

In chat some people asked if this is really a "Do X without Y" question. I interpret this to ask if the restrictions are unusually artificial.

The task of randomly sampling lines from huge files is not uncommon and is in fact one I sometimes have to do. One way to do this is in bash:

shuf -n <num-lines>

This is however very slow for large files as it reads in the whole file.

答:
Lua, <s>126</s> 122

```<code>r=io.read;f=io.open(r())c=2+f:read():len()for i=1,r()do f:seek("set",c*math.random(0,f:seek("end")/c-1))print(f:read())end
</code>```

Uses 2 bytes for line breaks. Change the 2 to a 1 for 1. I only have it as 2 because that's what my test file had.

Got myself under the PHP entry, but still 2nd place (currently). Curse you, Ruby entry!

Body:
Lua, <s>126</s> 122

r=io.read;f=io.open(r())c=2+f:read():len()for i=1,r()do f:seek("set",c*math.random(0,f:seek("end")/c-1))print(f:read())end

Uses 2 bytes for line breaks. Change the 2 to a 1 for 1. I only have it as 2 because that's what my test file had.

Got myself under the PHP entry, but still 2nd place (currently). Curse you, Ruby entry!


答:
Ruby, 22 bytes

One of the few times where the Ruby 0 being truthy is a problem for byte count.

```<code>f=->n{n>0?f[n/=5]+n:0}
</code>```

Title: Zeroes at the end of a factorial

Body:
Ruby, 22 bytes

One of the few times where the Ruby 0 being truthy is a problem for byte count.

f=->n{n>0?f[n/=5]+n:0}


答:
Julia, <s>34</s> <s>31</s> 30 bytes

n->find(digits(prod(1:n)))[]-1
```

This is an anonymous function that accepts any signed integer type and returns an integer. To call it, assign it to a variable. The larger test cases require passing n as a larger type, such as a BigInt.

We compute the factorial of n (manually using prod is shorter than the built-in factorial), get an array of its digits in reverse order, find the indices of the nonzero elements, get the first such index, and subtract 1.

Try it online! (includes all but the last test case because the last takes too long)

Saved a byte thanks to Dennis!

Title: Zeroes at the end of a factorial

Body:
Julia, <s>34</s> <s>31</s> 30 bytes

n->find(digits(prod(1:n)))[]-1

This is an anonymous function that accepts any signed integer type and returns an integer. To call it, assign it to a variable. The larger test cases require passing n as a larger type, such as a BigInt.

We compute the factorial of n (manually using prod is shorter than the built-in factorial), get an array of its digits in reverse order, find the indices of the nonzero elements, get the first such index, and subtract 1.

Try it online! (includes all but the last test case because the last takes too long)

Saved a byte thanks to Dennis!


答:
Actually, 10 bytes

```<code>!$R;≈$l@l-
</code>```

Try it online!

Note that the last test case fails when running Seriously on CPython because math.factorial uses a C extension (which is limited to 64-bit integers). Running Seriously on PyPy works fine, though.

Explanation:

```<code>!$R;≈$l@l-
!           factorial of input
 $R         stringify, reverse
   ;≈$      make a copy, cast to int, then back to string (removes leading zeroes)
      l@l-  difference in lengths (the number of leading zeroes removed by the int conversion)
</code>```

Title: Zeroes at the end of a factorial

Body:
Actually, 10 bytes

!$R;≈$l@l-

Try it online!

Note that the last test case fails when running Seriously on CPython because math.factorial uses a C extension (which is limited to 64-bit integers). Running Seriously on PyPy works fine, though.

Explanation:

!$R;≈$l@l-
!           factorial of input
 $R         stringify, reverse
   ;≈$      make a copy, cast to int, then back to string (removes leading zeroes)
      l@l-  difference in lengths (the number of leading zeroes removed by the int conversion)


答:
Jelly, 5 bytes

```<code>!Æfċ5
</code>```

Uses the counterproductive approach of finding the factorial then factorising it again, checking for the exponent of 5 in the prime factorisation.

Try it online!

```<code>!              Factorial
 Æf            List of prime factors, e.g. 120 -> [2, 2, 2, 3, 5]
   ċ5          Count number of 5s
</code>```

Title: Zeroes at the end of a factorial

Body:
Jelly, 5 bytes

!Æfċ5

Uses the counterproductive approach of finding the factorial then factorising it again, checking for the exponent of 5 in the prime factorisation.

Try it online!

!              Factorial
 Æf            List of prime factors, e.g. 120 -> [2, 2, 2, 3, 5]
   ċ5          Count number of 5s


答:
Pyth, 6 bytes

```<code>/P.!Q5
</code>```

Try it here.

```<code>/    5   Count 5's in
 P        the prime factorization of
  .!Q      the factorial of the input.
</code>```

Alternative 7-byte:

```<code>st.u/N5
</code>```

The cumulative reduce .u/N5 repeatedly floor-divides by 5 until it gets a repeat, which in this case happens after it hits 0.

```<code>34 -> [34, 6, 1, 0]
</code>```

The first element is then removed (t) and the rest is summed (s).

Title: Zeroes at the end of a factorial

Body:
Pyth, 6 bytes

/P.!Q5

Try it here.

/    5   Count 5's in
 P        the prime factorization of
  .!Q      the factorial of the input.

Alternative 7-byte:

st.u/N5

The cumulative reduce .u/N5 repeatedly floor-divides by 5 until it gets a repeat, which in this case happens after it hits 0.

34 -> [34, 6, 1, 0]

The first element is then removed (t) and the rest is summed (s).


答:
Dyalog APL, 63 bytes

```<code>⎕NREAD¨t 82l∘,¨l×¯1+⎕?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍞⎕NTIE 0
</code>```

Prompts for file name, then for how many random lines are desired.

Explanation

⍞ Prompt for text input (file name)

⎕NTIE 0 Tie the file using next available tie number (-1 on a clean system)

t← Store the chosen tie number as t

83 80,⍨ Append [83,80] yielding [-1,83,80]

⎕NREAD Read the first 80 bytes of file -1 as 8-bit integers (conversion code 83)

10⍳⍨ Find the index of the first number 10 (LF)

l← Store the line length as l

(⎕NSIZE t)÷ Divide the size of file -1 with the line length

⎕ Prompt for numeric input (desired number of lines)

? X random selections (without replacement) out the first Y natural numbers

¯1+ Add -1 to get 0-origin line numbers*

l× Multiply by the line length to get the start bytes

t 82l∘,¨ Prepend [-1,82,LineLength] to each start byte (creates list of arguments for ⎕NREAD)

⎕NREAD¨ Read each line as 8-bit character (conversion code 82)

Practical example

File /tmp/records.txt contains:

```<code>Hello
Think
12345
Klaus
Nilad
</code>```

Make the program RandLines contain the above code verbatim by entering the following into the APL session:

```<code>∇RandLines
⎕NREAD¨t 82l∘,¨l×¯1+⎕?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍞⎕NTIE 0
∇
</code>```

In the APL session type RandLines and press Enter.

The system moves the cursor to the next line, which is a 0-length prompt for character data; enter /tmp/records.txt.

The system now outputs ⎕: and awaits numeric input; enter 4.

The system outputs four random lines.

Real life

In reality, you may want to give filename and count as arguments and receive the result as a table. This can be done by entering:

```<code>RandLs←{↑⎕NREAD¨t 82l∘,¨l×¯1+⍺?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍵⎕NTIE 0}
</code>```

Now you make MyLines contain three random lines with:

```<code>MyLines←3 RandLs'/tmp/records.txt'
</code>```

How about returning just a single random line if count is not specified:

```<code>RandL←{⍺←1 ⋄ ↑⎕NREAD¨t 82l∘,¨l×¯1+⍺?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍵⎕NTIE 0}
</code>```

Now you can do both:

```<code>MyLines←2 RandL'/tmp/records.txt'
</code>```

and (notice absence of left argument):

```<code>MyLine←RandL'/tmp/records.txt'
</code>```

Making code readable

Golfed APL one-liners are a bad idea. Here is how I would write in a production system:

```<code>RandL←{ ⍝ Read X random lines from file Y without reading entire file
    ⍺←1 ⍝ default count
    tie←⍵⎕NTIE 0 ⍝ tie file
    length←10⍳⍨⎕NREAD 83 80,⍨tie ⍝ find first NL
    size←⎕NSIZE tie ⍝ total file length
    starts←length×¯1+⍺?size÷length ⍝ beginning of each line
    ↑⎕NREAD¨tie 82length∘,¨starts ⍝ read each line as character and convert list to table
}
</code>```

*I could save a byte by running in 0-origin mode, which is standard on some APL systems: remove ¯1+ and insert 1+ before 10.

Title: Read n random lines from a potentially huge file

Body:
This challenge is about reading random lines from a potentially huge file without reading the whole file into memory.

Input

An integer n and the name of a text file.

Output

n lines of the text file chosen uniformly at random without replacement.

You can assume that n is in the range 1 to the number of lines in the file.

Be careful when sampling n numbers at random from the range that the answer you get is uniform. rand()%n in C is not uniform for example. Every outcome must be equally likely.

Rules and restrictions

Each line of the text file will have the same number of characters and that will be no more than 80.

Your code must not read any of the contents of text file except:

Those lines it outputs.

The first line to work out how many characters per line there are in the text file.

We can assume each character in the text file takes exactly one byte.

Line separators are assumed to be 1 byte long. Solutions may use 2 bytes long line separators only if they specify this need. You may also assume the last line is terminated by a line separator.

Your answer should be a complete program but you can specify the input in any way that is convenient.

Languages and libraries

You can use any language or library you like.

Notes

There was a concern about calculating the number of lines in the file. As nimi points out in the comments, you can infer this from the file size and the number of chars per line.

Motivation

In chat some people asked if this is really a "Do X without Y" question. I interpret this to ask if the restrictions are unusually artificial.

The task of randomly sampling lines from huge files is not uncommon and is in fact one I sometimes have to do. One way to do this is in bash:

shuf -n <num-lines>

This is however very slow for large files as it reads in the whole file.

Body:
Dyalog APL, 63 bytes

⎕NREAD¨t 82l∘,¨l×¯1+⎕?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍞⎕NTIE 0

Prompts for file name, then for how many random lines are desired.

Explanation

⍞ Prompt for text input (file name)

⎕NTIE 0 Tie the file using next available tie number (-1 on a clean system)

t← Store the chosen tie number as t

83 80,⍨ Append [83,80] yielding [-1,83,80]

⎕NREAD Read the first 80 bytes of file -1 as 8-bit integers (conversion code 83)

10⍳⍨ Find the index of the first number 10 (LF)

l← Store the line length as l

(⎕NSIZE t)÷ Divide the size of file -1 with the line length

⎕ Prompt for numeric input (desired number of lines)

? X random selections (without replacement) out the first Y natural numbers

¯1+ Add -1 to get 0-origin line numbers*

l× Multiply by the line length to get the start bytes

t 82l∘,¨ Prepend [-1,82,LineLength] to each start byte (creates list of arguments for ⎕NREAD)

⎕NREAD¨ Read each line as 8-bit character (conversion code 82)

Practical example

File /tmp/records.txt contains:

Hello
Think
12345
Klaus
Nilad

Make the program RandLines contain the above code verbatim by entering the following into the APL session:

∇RandLines
⎕NREAD¨t 82l∘,¨l×¯1+⎕?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍞⎕NTIE 0
∇

In the APL session type RandLines and press Enter.

The system moves the cursor to the next line, which is a 0-length prompt for character data; enter /tmp/records.txt.

The system now outputs ⎕: and awaits numeric input; enter 4.

The system outputs four random lines.

Real life

In reality, you may want to give filename and count as arguments and receive the result as a table. This can be done by entering:

RandLs←{↑⎕NREAD¨t 82l∘,¨l×¯1+⍺?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍵⎕NTIE 0}

Now you make MyLines contain three random lines with:

MyLines←3 RandLs'/tmp/records.txt'

How about returning just a single random line if count is not specified:

RandL←{⍺←1 ⋄ ↑⎕NREAD¨t 82l∘,¨l×¯1+⍺?(⎕NSIZE t)÷l←10⍳⍨⎕NREAD 83 80,⍨t←⍵⎕NTIE 0}

Now you can do both:

MyLines←2 RandL'/tmp/records.txt'

and (notice absence of left argument):

MyLine←RandL'/tmp/records.txt'

Making code readable

Golfed APL one-liners are a bad idea. Here is how I would write in a production system:

RandL←{ ⍝ Read X random lines from file Y without reading entire file
    ⍺←1 ⍝ default count
    tie←⍵⎕NTIE 0 ⍝ tie file
    length←10⍳⍨⎕NREAD 83 80,⍨tie ⍝ find first NL
    size←⎕NSIZE tie ⍝ total file length
    starts←length×¯1+⍺?size÷length ⍝ beginning of each line
    ↑⎕NREAD¨tie 82length∘,¨starts ⍝ read each line as character and convert list to table
}

*I could save a byte by running in 0-origin mode, which is standard on some APL systems: remove ¯1+ and insert 1+ before 10.


答:
Dyalog APL, 9 bytes

```<code>⊥⍨'0'=⍕!⎕
</code>```

⎕ prompt for number

! factorialize

⍕ stringify

'0'= check equality to character zero

⊥⍨ count trailing trues*

*Literally it is a mixed-base to base-10 conversion, using the boolean list as both number and base:

⊥⍨0 1 0 1 1 is the same as 0 1 0 1 1⊥⍨0 1 0 1 1 which is  0×(0×1×0×1×1) 1×(1×0×1×1) 0×(0×1×1) 1×(1×1) + 1×(1) which again is two (the number of trailing 1s).

Title: Zeroes at the end of a factorial

Body:
Dyalog APL, 9 bytes

⊥⍨'0'=⍕!⎕

⎕ prompt for number

! factorialize

⍕ stringify

'0'= check equality to character zero

⊥⍨ count trailing trues*

*Literally it is a mixed-base to base-10 conversion, using the boolean list as both number and base:

⊥⍨0 1 0 1 1 is the same as 0 1 0 1 1⊥⍨0 1 0 1 1 which is  0×(0×1×0×1×1) 1×(1×0×1×1) 0×(0×1×1) 1×(1×1) + 1×(1) which again is two (the number of trailing 1s).


答:
05AB1E, 5 bytes

Would be 4 bytes if we could guarantee n>4

Code:

```<code>Î!Ó7è
</code>```

Explanation:

```<code>Î        # push 0 then input
  !      # factorial of n: 10 -> 2628800
   Ó     # get primefactor exponents -> [8, 4, 2, 1]
    7è   # get list[7] (list is indexed as string) -> 2
         # implicit output of number of 5s or 0 if n < 5
</code>```

Alternate, much faster, 6 byte solution: Inspired by Luis Mendo's MATL answer

```<code>LÒ€`5QO
</code>```

Explanation:

```<code>L         # push range(1,n) inclusive, n=10 -> [1,2,3,4,5,6,7,8,9,10]
 Ò        # push prime factors of each number in list -> [[], [2], [3], [2, 2], [5], [2, 3], [7], [2, 2, 2], [3, 3], [2, 5]]
  €`      # flatten list of lists to list [2, 3, 2, 2, 5, 2, 3, 7, 2, 2, 2, 3, 3, 2, 5]
    5Q    # and compare each number to 5 -> [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
      O   # sum -> 2
</code>```

Edit: removed solutions using ¢ (count) as all primes containing 5 would be counted as 5 e.g. 53.

Edit 2: added a more efficient solution for higher input as comparison.

Title: Zeroes at the end of a factorial

Body:
05AB1E, 5 bytes

Would be 4 bytes if we could guarantee n>4

Code:

Î!Ó7è

Explanation:

Î        # push 0 then input
  !      # factorial of n: 10 -> 2628800
   Ó     # get primefactor exponents -> [8, 4, 2, 1]
    7è   # get list[7] (list is indexed as string) -> 2
         # implicit output of number of 5s or 0 if n < 5

Alternate, much faster, 6 byte solution: Inspired by Luis Mendo's MATL answer

LÒ€`5QO

Explanation:

L         # push range(1,n) inclusive, n=10 -> [1,2,3,4,5,6,7,8,9,10]
 Ò        # push prime factors of each number in list -> [[], [2], [3], [2, 2], [5], [2, 3], [7], [2, 2, 2], [3, 3], [2, 5]]
  €`      # flatten list of lists to list [2, 3, 2, 2, 5, 2, 3, 7, 2, 2, 2, 3, 3, 2, 5]
    5Q    # and compare each number to 5 -> [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
      O   # sum -> 2

Edit: removed solutions using ¢ (count) as all primes containing 5 would be counted as 5 e.g. 53.

Edit 2: added a more efficient solution for higher input as comparison.


答:
CJam, 9 bytes

```<code>l~m!mf5e=
</code>```

Try it online!

Just counting the 5's 5e= in the prime factorization mf of the factorial m! of the input l~.

Doesn't work for big factorials, since they don't fit into an integer.

Title: Zeroes at the end of a factorial

Body:
CJam, 9 bytes

l~m!mf5e=

Try it online!

Just counting the 5's 5e= in the prime factorization mf of the factorial m! of the input l~.

Doesn't work for big factorials, since they don't fit into an integer.


答:
MATL, 9 bytes

```<code>:"@Yf5=vs
</code>```

Try it online!

This works for very large numbers, as it avoids computing the factorial.

Like other answers, this exploits the fact that the number of times 2 appears as divisor of the factorial is greater or equal than the number of times 5 appears.

```<code>:     % Implicit input. Inclusive range from 1 to that
"     % For each
  @   %   Push that value
  Yf  %   Array of prime factors
  5=  %   True for 5, false otherwise
  v   %   Concatenate vertically all stack contents
  s   %   Sum
</code>```

Title: Zeroes at the end of a factorial

Body:
Write a program or function that finds the number of zeroes at the end of n! in base 10, where n is an input number (in any desired format).

It can be assumed that n is a positive integer, meaning that n! is also an integer. There are no zeroes after a decimal point in n!. Also, it can be assumed that your programming language can handle the value of n and n!.

Test cases

```<code>1
==> 0

5
==> 1

100
==> 24

666
==> 165

2016
==> 502

1234567891011121314151617181920
==> 308641972752780328537904295461
</code>```

This is code golf. Standard rules apply. The shortest code in bytes wins.

Body:
MATL, 9 bytes

:"@Yf5=vs

Try it online!

This works for very large numbers, as it avoids computing the factorial.

Like other answers, this exploits the fact that the number of times 2 appears as divisor of the factorial is greater or equal than the number of times 5 appears.

:     % Implicit input. Inclusive range from 1 to that
"     % For each
  @   %   Push that value
  Yf  %   Array of prime factors
  5=  %   True for 5, false otherwise
  v   %   Concatenate vertically all stack contents
  s   %   Sum


答:
Matlab  (59) (54)(39)

Hey dawg !!!! we heard you like maths ....

```<code>  @(n)sum(fix(n./5.^(1:fix(log(n)/1.6))))
</code>```

This is based on my created answer in code review.

further than what is mentioned in my answer in code review, the formula for number of zeros in factorial(n) is Sum(n/(5^k)) where k varies between 1 and log_5(n)

The only trivial reason why it cant get golfier is that log5 isnt available in matlab as a builtin , thus I replaced log(5) by 1.6, doesnt matter because it will be anyways floored.

Give it a try

Title: Zeroes at the end of a factorial

Body:
Matlab  (59) (54)(39)

Hey dawg !!!! we heard you like maths ....

  @(n)sum(fix(n./5.^(1:fix(log(n)/1.6))))

This is based on my created answer in code review.

further than what is mentioned in my answer in code review, the formula for number of zeros in factorial(n) is Sum(n/(5^k)) where k varies between 1 and log_5(n)

The only trivial reason why it cant get golfier is that log5 isnt available in matlab as a builtin , thus I replaced log(5) by 1.6, doesnt matter because it will be anyways floored.

Give it a try


答:
C# 259 bytes without duplicates

```<code>class Program{static void Main(string[]a){int c=Convert.ToInt32(a[1]);var h=File.ReadLines(a[0]);HashSet<int>n=new HashSet<int>();while(n.Count<c)n.Add(new Random().Next(0,h.Count()));for(;c>0;c--)Console.WriteLine(h.Skip(n.ElementAt(c-1)).Take(1).First());}}
</code>```

Ungolfed

```<code>class Program{static void Main(string[] a)
{
        int c = Convert.ToInt32(a[1]);
        var h = File.ReadLines(a[0]);
        HashSet<int> n = new HashSet<int>();
        while (n.Count < c)
            n.Add(new Random().Next(0, h.Count()));
        for (; c > 0; c--)
            Console.WriteLine(h.Skip(n.ElementAt(c-1)).Take(1).First());
    }
}
</code>```

File.ReadLines is Lazy.
This has the additional benefit that all lines can have different length.

Running it would be:

```<code>sample.exe a.txt 10000
</code>```

C# 206 bytes with duplicates

```<code>class Program{static void Main(string[]a){var n=new Random();int c=Convert.ToInt32(a[1]);var h=File.ReadLines(a[0]);for(;c>0;c--)Console.WriteLine(h.Skip((int)(n.NextDouble()*h.Count())).Take(1).First());}}
</code>```

Ungolfed

```<code>class Program
{
    static void Main(string[] a)
    {
        Random n = new Random();
        int c = Convert.ToInt32(a[1]);
        var h = File.ReadLines(a[0]);
        for (; c > 0; c--)
            Console.WriteLine(h.Skip((int)(n.NextDouble()*h.Count())).Take(1).First());
    }
}
</code>```

Body:
C# 259 bytes without duplicates

class Program{static void Main(string[]a){int c=Convert.ToInt32(a[1]);var h=File.ReadLines(a[0]);HashSet<int>n=new HashSet<int>();while(n.Count<c)n.Add(new Random().Next(0,h.Count()));for(;c>0;c--)Console.WriteLine(h.Skip(n.ElementAt(c-1)).Take(1).First());}}

Ungolfed

class Program{static void Main(string[] a)
{
        int c = Convert.ToInt32(a[1]);
        var h = File.ReadLines(a[0]);
        HashSet<int> n = new HashSet<int>();
        while (n.Count < c)
            n.Add(new Random().Next(0, h.Count()));
        for (; c > 0; c--)
            Console.WriteLine(h.Skip(n.ElementAt(c-1)).Take(1).First());
    }
}

File.ReadLines is Lazy.
This has the additional benefit that all lines can have different length.

Running it would be:

sample.exe a.txt 10000

C# 206 bytes with duplicates

class Program{static void Main(string[]a){var n=new Random();int c=Convert.ToInt32(a[1]);var h=File.ReadLines(a[0]);for(;c>0;c--)Console.WriteLine(h.Skip((int)(n.NextDouble()*h.Count())).Take(1).First());}}

Ungolfed

class Program
{
    static void Main(string[] a)
    {
        Random n = new Random();
        int c = Convert.ToInt32(a[1]);
        var h = File.ReadLines(a[0]);
        for (; c > 0; c--)
            Console.WriteLine(h.Skip((int)(n.NextDouble()*h.Count())).Take(1).First());
    }
}


答:
Mathematica, 20 bytes

```<code>IntegerExponent[#!]&
</code>```

IntegerExponent counts the zeros. For fun, here's a version that doesn't calculate the factorial:

```<code>Tr[#~IntegerExponent~5&~Array~#]&
</code>```

Title: Zeroes at the end of a factorial

Body:
Mathematica, 20 bytes

IntegerExponent[#!]&

IntegerExponent counts the zeros. For fun, here's a version that doesn't calculate the factorial:

Tr[#~IntegerExponent~5&~Array~#]&


答:
C, 53 bytes

 i,r;z(n){for(;i=n--;)for(;i=i%5?0:i/5;)r++;return r;}
```
<p>Counting 5s in the sequence that makes up the factorial, instead of calculating the factorial and then counting its 5s.</p>
<p>Full program:</p>
<pre class="lang-c prettyprint-override"><code>i,r;z(n){for(;i=n--;)for(;i=i%5?0:i/5;)r++;return r;}
#include <stdio.h>
int main(int argc, char **argv) {
    int n;
    sscanf(argv[1], "%d", &n);
    printf("%d -> %d\n", n, z(n));
    return 0;
}
</code>```

Title: Zeroes at the end of a factorial

Body:
C, 53 bytes

 i,r;z(n){for(;i=n--;)for(;i=i%5?0:i/5;)r++;return r;}

Counting 5s in the sequence that makes up the factorial, instead of calculating the factorial and then counting its 5s.

Full program:

i,r;z(n){for(;i=n--;)for(;i=i%5?0:i/5;)r++;return r;}
#include <stdio.h>
int main(int argc, char **argv) {
    int n;
    sscanf(argv[1], "%d", &n);
    printf("%d -> %d\n", n, z(n));
    return 0;
}


问:
Rotation-safe Latin squares
A Latin square is a square that has no repeated symbols in either the X or Y columns.  For example:

```<code>ABCD
DABC
CDAB
BCDA
</code>```

is one such square.  Notice how every column and row contains a permutation of the same 4 letters.

However, our Latin square has a problem:  If I were to rotate the second row (DABC) 1 to the left, I'd end up with ABCD, which is identical to the permutation above it.  If it is impossible to rotate any 1 column/row and obtain another column/row, then we consider the square to be rotation safe.

For example:

```<code>ABCD
BDAC
CADB
DCBA
</code>```

is rotation safe.  The grid has the following properties:

Point [0,N] uses the Nth symbol

Point [0,N] and [N,0] are always the same symbol.  (I'd like to also say that [x,y] and [y,x] are also always the same letter, but I can't prove it)

Your task is to print out 1 rotation-safe Latin square, when passed N.  I don't care if you output letters, numbers, a list, or a 2D array.  If you use numbers, the top column and row must be 0,1,2,3,... (in that order).  If you use letters, then it must be A,B,C,D,....

For example, if your input was 4, you should either print:

```<code>0,1,2,3            0,1,2,3
1,3,0,2     or     1,0,3,2
2,0,3,1            2,3,1,0
3,2,1,0            3,2,0,1
</code>```

There are no rotation-safe Latin squares of size less than 4.  I don't care what your program does if N is less than 4.  For the curious, the number of rotation-safe squares is (starting at 4):  2,5,5906,(too long to calculate)

This is a code-golf, so try to make answers as short as possible in your favorite language!

答:
Sqlserver 2012 - 918 bytes

On my box this runs for @k = 5, although it takes 16 seconds.

This is code building code(watch out Skynet, you have competition)

Is there a price for the longest script?

```<code>DECLARE @k int = 4;

DECLARE @t VARCHAR(max)='WITH C as(SELECT
top '+left(@k,1)+'row_number()over(order by 1/0)n
FROM sys.messages),D(nÆ)as(SELECT
concat(~),~
FROM Ø
WHERE |)SELECT top 1~ FROM Å
WHERE 1=1',@
varchar(999)=''SELECT @+=','+CHAR(x+65)FROM(values(0),(1),(2),(3),(4),(5))x(x)WHERE x<@k
SELECT
@t=REPLACE(REPLACE(REPLACE(REPLACE(@t,'Æ',@),'Ø',STUFF(REPLACE(@,',',',C '),1,1,'')),'Å',STUFF(REPLACE(@,',',',D
'),1,1,'')),'~',STUFF(REPLACE(@,',','.n,'),1,3,'')+'.n'),@='';WITH C as(SELECT top(@k)x
FROM(values(0),(1),(2),(3),(4),(5))x(x))SELECT @+=' AND
'+char(65+C.x)+'.n<>'+char(65+D.x)+'.n'FROM c,c d WHERE C.x<D.x
SELECT @t=REPLACE(@t,'|',STUFF(@,1,4,''));WITH A
as(SELECT top(@k)x
FROM(values(65),(66),(67),(68),(69),(70))x(x))SELECT @t+='AND
'+char(A.x)+'.'+char(C.x)+'<>'+CHAR(B.x)+'.'+char(C.x)+' AND
'+char(A.x)+'.n+'+char(A.x)+'.n'+'
not like''%''+'+char(B.x)+'.n+''%'''FROM A,A B,A C
WHERE A.x<>B.x and C.x<>B.x
EXEC(@t)
</code>```

Try online!

Title: Rotation-safe Latin squares

Body:
Sqlserver 2012 - 918 bytes

On my box this runs for @k = 5, although it takes 16 seconds.

This is code building code(watch out Skynet, you have competition)

Is there a price for the longest script?

DECLARE @k int = 4;

DECLARE @t VARCHAR(max)='WITH C as(SELECT
top '+left(@k,1)+'row_number()over(order by 1/0)n
FROM sys.messages),D(nÆ)as(SELECT
concat(~),~
FROM Ø
WHERE |)SELECT top 1~ FROM Å
WHERE 1=1',@
varchar(999)=''SELECT @+=','+CHAR(x+65)FROM(values(0),(1),(2),(3),(4),(5))x(x)WHERE x<@k
SELECT
@t=REPLACE(REPLACE(REPLACE(REPLACE(@t,'Æ',@),'Ø',STUFF(REPLACE(@,',',',C '),1,1,'')),'Å',STUFF(REPLACE(@,',',',D
'),1,1,'')),'~',STUFF(REPLACE(@,',','.n,'),1,3,'')+'.n'),@='';WITH C as(SELECT top(@k)x
FROM(values(0),(1),(2),(3),(4),(5))x(x))SELECT @+=' AND
'+char(65+C.x)+'.n<>'+char(65+D.x)+'.n'FROM c,c d WHERE C.x<D.x
SELECT @t=REPLACE(@t,'|',STUFF(@,1,4,''));WITH A
as(SELECT top(@k)x
FROM(values(65),(66),(67),(68),(69),(70))x(x))SELECT @t+='AND
'+char(A.x)+'.'+char(C.x)+'<>'+CHAR(B.x)+'.'+char(C.x)+' AND
'+char(A.x)+'.n+'+char(A.x)+'.n'+'
not like''%''+'+char(B.x)+'.n+''%'''FROM A,A B,A C
WHERE A.x<>B.x and C.x<>B.x
EXEC(@t)

Try online!


问:
Calculate the Fermat Point of a Triangle
This is somewhat similar to The centers of a triangle, but with a different point. The Fermat Point is the point P in triangle ABC such that the value of AP + BP + CP is minimized. There are two cases:

If there is an angle greater than 120 degrees, that vertex is the fermat point. Otherwise, draw equilateral triangles on each of the sides of ABC. Connect the far vertex of each equilateral triangle to the opposite vertex of triangle ABC. Doing this for each of the three equilateral triangles results in a single common point of intersection for all three lines, which is the Fermat Point.

It should run within 5 seconds on a reasonable machine.

Input: A set of 3 points, not necessarily integers. This can be taken as a nested array, string, list of tuples, etc. (whatever suits your language).

Output: The coordinates of the Fermat point, again, however your language best handles points. Floating point inaccuracies will not be counted against you.

Test Cases:

```<code>[[1, 1], [2, 2], [1, 2]] --> [1.2113248654051871, 1.788675134594813]
[[-1, -1], [-2, -1], [0, 0]] --> [-1, -1]
[[-1, -1], [1, -1], [0, 1]] --> [0, -0.42264973081037427]
[[0, 0], [0.5, 0.8660254037844386], [-5, 0]] --> [0, 0]
[[0, 0], [0, -5], [-0.8660254037844386, 0.5]] --> [0, 0]
</code>```

This is code golf so shortest code wins!

答:
Python, 475 448 440 bytes

Any help to golf further is appreciated.

from math import *
d=lambda x,y:((x[0]-y[0])**2+(x[1]-y[1])**2)**0.5
s=lambda A,B,C:(d(B,C), d(C,A), d(A,B))
j=lambda a,b,c:acos((b*b+c*c-a*a)/(2*b*c))
t=lambda a,b,c:1/cos(j(a,b,c)-pi/6)
b=lambda A,B,C,p,q,r:[(p*A[i]+q*B[i]+r*C[i])/(p+q+r) for i in [0,1]]
f=lambda A,B,C:A if j(*s(A,B,C)) >= 2*pi/3 else B if j(*s(B,C,A)) >= 2*pi/3 else C if j(*s(C,A,B)) >= 2*pi/3 else b(A,B,C,d(B,C)*t(*s(A,B,C)),d(C,A)*t(*s(B,C,A)),d(A,B)*t(*s(C,A,B)))
```

<p>Ungolfed:</p>

```from math import *
#distance between two points
d = lambda x,y: ((x[0]-y[0])**2+(x[1]-y[1])**2)**0.5

#given the points, returns the sides
s = lambda A,B,C : (d(B,C), d(C,A), d(A,B))

#given the sides, returns the angle
j = lambda a,b,c : acos((b*b+c*c-a*a)/(2*b*c))

#given the sides, returns secant of that angle
t = lambda a,b,c: 1/cos(j(a,b,c)-pi/6)

#given the sides and the Trilinear co-ordinates, returns the Cartesian co-ordinates
b = lambda A,B,C,p,q,r: [(p*A[i]+q*B[i]+r*C[i])/(p+q+r) for i in [0,1]]

#this one checks if any of the angle is >= 2π/3 returns that point else computes the point
f = lambda A,B,C: A if j(*s(A,B,C)) >= 2*pi/3 else B if j(*s(B,C,A)) >= 2*pi/3 else C if j(*s(C,A,B)) >= 2*pi/3 else b(A,B,C,d(B,C)*t(*s(A,B,C)),d(C,A)*t(*s(B,C,A)),d(A,B)*t(*s(C,A,B)))
```

<p>Input:</p>

```print('{}'.format(f([1, 1], [2, 2], [1, 2])))
print('{}'.format(f([-1, -1], [-2, -1], [0, 0])))
print('{}'.format(f([-1, -1], [1, -1], [0, 1])))
print('{}'.format(f([0, 0], [0.5, 0.8660254037844386], [-5, 0])))
print('{}'.format(f([0, 0], [0, -5], [-0.8660254037844386, 0.5])))
```

<p>Output:</p>

```[1.2113248652983113, 1.7886751347016887]
[-1, -1]
[0.0, -0.42264973086764884]
[0, 0]
[0, 0]
```

Body:
Python, 475 448 440 bytes

Any help to golf further is appreciated.

from math import *
d=lambda x,y:((x[0]-y[0])**2+(x[1]-y[1])**2)**0.5
s=lambda A,B,C:(d(B,C), d(C,A), d(A,B))
j=lambda a,b,c:acos((b*b+c*c-a*a)/(2*b*c))
t=lambda a,b,c:1/cos(j(a,b,c)-pi/6)
b=lambda A,B,C,p,q,r:[(p*A[i]+q*B[i]+r*C[i])/(p+q+r) for i in [0,1]]
f=lambda A,B,C:A if j(*s(A,B,C)) >= 2*pi/3 else B if j(*s(B,C,A)) >= 2*pi/3 else C if j(*s(C,A,B)) >= 2*pi/3 else b(A,B,C,d(B,C)*t(*s(A,B,C)),d(C,A)*t(*s(B,C,A)),d(A,B)*t(*s(C,A,B)))

Ungolfed:

from math import *
#distance between two points
d = lambda x,y: ((x[0]-y[0])**2+(x[1]-y[1])**2)**0.5

#given the points, returns the sides
s = lambda A,B,C : (d(B,C), d(C,A), d(A,B))

#given the sides, returns the angle
j = lambda a,b,c : acos((b*b+c*c-a*a)/(2*b*c))

#given the sides, returns secant of that angle
t = lambda a,b,c: 1/cos(j(a,b,c)-pi/6)

#given the sides and the Trilinear co-ordinates, returns the Cartesian co-ordinates
b = lambda A,B,C,p,q,r: [(p*A[i]+q*B[i]+r*C[i])/(p+q+r) for i in [0,1]]

#this one checks if any of the angle is >= 2π/3 returns that point else computes the point
f = lambda A,B,C: A if j(*s(A,B,C)) >= 2*pi/3 else B if j(*s(B,C,A)) >= 2*pi/3 else C if j(*s(C,A,B)) >= 2*pi/3 else b(A,B,C,d(B,C)*t(*s(A,B,C)),d(C,A)*t(*s(B,C,A)),d(A,B)*t(*s(C,A,B)))

Input:

print('{}'.format(f([1, 1], [2, 2], [1, 2])))
print('{}'.format(f([-1, -1], [-2, -1], [0, 0])))
print('{}'.format(f([-1, -1], [1, -1], [0, 1])))
print('{}'.format(f([0, 0], [0.5, 0.8660254037844386], [-5, 0])))
print('{}'.format(f([0, 0], [0, -5], [-0.8660254037844386, 0.5])))

Output:

[1.2113248652983113, 1.7886751347016887]
[-1, -1]
[0.0, -0.42264973086764884]
[0, 0]
[0, 0]


答:
Convex, 6 bytes

```<code>¡mf5e=
</code>```

Use Java interpreter or this alternate version that works on TIO: Try it online

This would be 4 bytes if I was finished getting rid of 2 char operators....

Title: Zeroes at the end of a factorial

Body:
Convex, 6 bytes

¡mf5e=

Use Java interpreter or this alternate version that works on TIO: Try it online

This would be 4 bytes if I was finished getting rid of 2 char operators....


答:
PowerShell v2+, 60 bytes (but see the NB below)

A completely different approach, doing exactly what is requested by the challenge. ;-)

```<code>$a=2..$args[0]-join'*'|iex;"$a".length-"$a".Trim('0').length
</code>```

Takes input $args and creates a dynamic range .., then -joins it together with * for multiplication, pipes that to iex (similar to eval) to compute the factorial. Store that in $a.

We then take the length of the string representation and subtract off the length of the string representation after we've passed it to .Trim('0') which will remove leading and trailing zeroes. Since there will never be leading zeroes, this gets us the result we want.

NB: The above will work for up to n=17 without a problem, as even though 17! is bigger than [Int]::MaxValue, since we didn't explicitly specify the casting for $a, PowerShell will dynamically convert it to [double] for us upon overflow. Yeah ... in PowerShell, [int] will overflow to [double] if not explicitly cast. No, I don't know why it goes to that rather than [int64].

However, at 18!, PowerShell will automatically convert the number to scientific notation when the implicit .ToString() is called (i.e., when encapsulating it within quotes), in order to preserve significant digits. We can get around that with explicit formatting instead -- $a="{0:0}"-f(2..$args[0]-join'*'|iex);$a.length-$a.Trim('0').length -- at 67 bytes. That will get us up to 20! before we start to run into loss of precision.

Thus, to handle an "arbitrary" input, we'll need to combine the above explicit formatting with the [bigint] datatype ...

PowerShell v2+, 80 bytes

```<code>$a="{0:0}"-f("[bigint]"+(2..$args[0]-join'*')|iex);$a.length-$a.Trim('0').length
</code>```

This will prepend an explicit cast of [bigint] to the first number in the range 2, and in PowerShell the datatype on the left of the operator is used for output, so that [bigint] datatype will continue through the rest of the factorial calculation.

An few examples of the three methods at some key points, with some additional output text showing what's happening in the background -- the first output is the top code, the middle is with the explicit string formatting, and the bottom is with the [bigint] datatype.

```<code>PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 17
(Normal) 355687428096000 = 3
(Format) 355687428096000 = 3
(BigInt) 355687428096000 = 3

PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 18
(Normal) 6.402373705728E+15 = 0
(Format) 6402373705728000 = 3
(BigInt) 6402373705728000 = 3

PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 21
(Normal) 5.10909421717094E+19 = 0
(Format) 51090942171709400000 = 5
(BigInt) 51090942171709440000 = 4

PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 100
(Normal) 9.33262154439441E+157 = 0
(Format) 933262154439441000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000 = 143
(BigInt) 933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000
00000000 = 24

PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 666
(Normal) Infinity = 0
(Format) Infinity = 0
(BigInt) 101063205684078149339082270812987645175758239832414541134042080735741380210369702298920280680149101204098980220355752703933970405713072930283454242384
016585642874066153029797241068282869939717688434251350949378748077490349338925526287834176188326189942648494465716169313138031111761957305152642332038964180541
081606760789306748325981681536460982866866274811038560365797328460484207809414155642770874534510059882948847250594907196772727091196506088520929434066550648022
642608335790150309778114083249701373807911277761571911620331754219999948922714475266708579675248268885046126373228453917614236582397369676453760327876932228670
885547506983568164371084614056976933006577541441308350104365957229945444651724282400214055514046429629100190143841467573055296491456926973403850076414055114364
283612861330473414734808609512385966092678846067118146921625221337465049955783174195059482714722569989641408869425126104519667256749553222882671938160611697400
311264211156133257350321296072971178199390387741639438171846476552757501425212904028323696392262434445697502405816736843180906854457725847298397943781807264821
360865009874936976105696120379126536366566469680224519996204004154443821032721047698220334845859609307929656956126740947391412413210205581149373619966878853487
232170536051130524871079644147921335454258357607659625021345466796883799602327316306909470042946710666392541958119313633986054565867362395523193239940480940410
876723200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000 = 165
</code>```

Title: Zeroes at the end of a factorial

Body:
PowerShell v2+, 60 bytes (but see the NB below)

A completely different approach, doing exactly what is requested by the challenge. ;-)

$a=2..$args[0]-join'*'|iex;"$a".length-"$a".Trim('0').length

Takes input $args and creates a dynamic range .., then -joins it together with * for multiplication, pipes that to iex (similar to eval) to compute the factorial. Store that in $a.

We then take the length of the string representation and subtract off the length of the string representation after we've passed it to .Trim('0') which will remove leading and trailing zeroes. Since there will never be leading zeroes, this gets us the result we want.

NB: The above will work for up to n=17 without a problem, as even though 17! is bigger than [Int]::MaxValue, since we didn't explicitly specify the casting for $a, PowerShell will dynamically convert it to [double] for us upon overflow. Yeah ... in PowerShell, [int] will overflow to [double] if not explicitly cast. No, I don't know why it goes to that rather than [int64].

However, at 18!, PowerShell will automatically convert the number to scientific notation when the implicit .ToString() is called (i.e., when encapsulating it within quotes), in order to preserve significant digits. We can get around that with explicit formatting instead -- $a="{0:0}"-f(2..$args[0]-join'*'|iex);$a.length-$a.Trim('0').length -- at 67 bytes. That will get us up to 20! before we start to run into loss of precision.

Thus, to handle an "arbitrary" input, we'll need to combine the above explicit formatting with the [bigint] datatype ...

PowerShell v2+, 80 bytes

$a="{0:0}"-f("[bigint]"+(2..$args[0]-join'*')|iex);$a.length-$a.Trim('0').length

This will prepend an explicit cast of [bigint] to the first number in the range 2, and in PowerShell the datatype on the left of the operator is used for output, so that [bigint] datatype will continue through the rest of the factorial calculation.

An few examples of the three methods at some key points, with some additional output text showing what's happening in the background -- the first output is the top code, the middle is with the explicit string formatting, and the bottom is with the [bigint] datatype.

PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 17
(Normal) 355687428096000 = 3
(Format) 355687428096000 = 3
(BigInt) 355687428096000 = 3

PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 18
(Normal) 6.402373705728E+15 = 0
(Format) 6402373705728000 = 3
(BigInt) 6402373705728000 = 3

PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 21
(Normal) 5.10909421717094E+19 = 0
(Format) 51090942171709400000 = 5
(BigInt) 51090942171709440000 = 4

PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 100
(Normal) 9.33262154439441E+157 = 0
(Format) 933262154439441000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000 = 143
(BigInt) 933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000
00000000 = 24

PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 666
(Normal) Infinity = 0
(Format) Infinity = 0
(BigInt) 101063205684078149339082270812987645175758239832414541134042080735741380210369702298920280680149101204098980220355752703933970405713072930283454242384
016585642874066153029797241068282869939717688434251350949378748077490349338925526287834176188326189942648494465716169313138031111761957305152642332038964180541
081606760789306748325981681536460982866866274811038560365797328460484207809414155642770874534510059882948847250594907196772727091196506088520929434066550648022
642608335790150309778114083249701373807911277761571911620331754219999948922714475266708579675248268885046126373228453917614236582397369676453760327876932228670
885547506983568164371084614056976933006577541441308350104365957229945444651724282400214055514046429629100190143841467573055296491456926973403850076414055114364
283612861330473414734808609512385966092678846067118146921625221337465049955783174195059482714722569989641408869425126104519667256749553222882671938160611697400
311264211156133257350321296072971178199390387741639438171846476552757501425212904028323696392262434445697502405816736843180906854457725847298397943781807264821
360865009874936976105696120379126536366566469680224519996204004154443821032721047698220334845859609307929656956126740947391412413210205581149373619966878853487
232170536051130524871079644147921335454258357607659625021345466796883799602327316306909470042946710666392541958119313633986054565867362395523193239940480940410
876723200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000 = 165


问:
LARGEST program to reverse a single line from stdin with no redundant code
The biggest program that reads a single line (terminated by your choice from NULL/CR/LF/CRLF) from stdin, reverses it, then prints it to stdout.

No redundant code [code which could safely be deleted] such as

```<code>return ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
</code>```

or redundant data that's used to stop code being redundant:

```<code>char* data = <kernel source code>;
if (md5sum(data) != <hash>) {
    return 1; //Fail for no good reason because it lets us add 1000000 lines of data
}
</code>```

Basically, the largest implementation of a string reverse, with no obvious attempt to game the question.

[edit]

I am tempted to say that the code must be finite for unbounded input length, but there have been some clever and interesting O(>1) length solutions.  I instead ask that people avoid posting simple brute-force lookup-list solutions as separate answers (comments are fine!).

答:
Mornington Crescent, <s>1480</s> 1587 bytes

+107 bytes thanks to Cloudy7

```<code>Take Northern Line to Moorgate
Take Metropolitan Line to Moorgate
Take Metropolitan Line to Wembley Park
Take Metropolitan Line to Wembley Park
Take Jubilee Line to West Ham
Take Hammersmith & City Line to West Ham
Take Hammersmith & City Line to Euston Square
Take Hammersmith & City Line to Euston Square
Take Circle Line to Liverpool Street
Take Central Line to Liverpool Street
Take Central Line to Oxford Circus
Take Victoria Line to Oxford Circus
Take Victoria Line to Victoria
Take Victoria Line to Victoria
Take District Line to Bank
Take Waterloo & City Line to Bank
Take Waterloo & City Line to Waterloo
Take Waterloo & City Line to Waterloo
Take Bakerloo Line to Piccadilly Circus
Take Piccadilly Line to Piccadilly Circus
Take Piccadilly Line to Turnpike Lane
Take Piccadilly Line to Turnpike Lane
Take Piccadilly Line to Piccadilly Circus
Take Piccadilly Line to Piccadilly Circus
Take Bakerloo Line to Waterloo
Take Waterloo & City Line to Waterloo
Take Waterloo & City Line to Bank
Take Waterloo & City Line to Bank
Take District Line to Victoria
Take District Line to Victoria
Take Victoria Line to Oxford Circus
Take Victoria Line to Oxford Circus
Take Central Line to Liverpool Street
Take Central Line to Liverpool Street
Take Circle Line to Euston Square
Take Hammersmith & City Line to Euston Square
Take Hammersmith & City Line to West Ham
Take Hammersmith & City Line to West Ham
Take Jubilee Line to Wembley Park
Take Metropolitan Line to Wembley Park
Take Metropolitan Line to Moorgate
Take Metropolitan Line to Moorgate
Take Northern Line to Mornington Crescent
</code>```

This code goes around in a huge loop using every single line but the Piccadilly Line, ending in Piccadilly Circus. Then it goes to Turnpike Lane, which reverses the string, before finally unwinding the loop and returning to Mornington Crescent.

Try it online!

Body:
Mornington Crescent, <s>1480</s> 1587 bytes

+107 bytes thanks to Cloudy7

Take Northern Line to Moorgate
Take Metropolitan Line to Moorgate
Take Metropolitan Line to Wembley Park
Take Metropolitan Line to Wembley Park
Take Jubilee Line to West Ham
Take Hammersmith & City Line to West Ham
Take Hammersmith & City Line to Euston Square
Take Hammersmith & City Line to Euston Square
Take Circle Line to Liverpool Street
Take Central Line to Liverpool Street
Take Central Line to Oxford Circus
Take Victoria Line to Oxford Circus
Take Victoria Line to Victoria
Take Victoria Line to Victoria
Take District Line to Bank
Take Waterloo & City Line to Bank
Take Waterloo & City Line to Waterloo
Take Waterloo & City Line to Waterloo
Take Bakerloo Line to Piccadilly Circus
Take Piccadilly Line to Piccadilly Circus
Take Piccadilly Line to Turnpike Lane
Take Piccadilly Line to Turnpike Lane
Take Piccadilly Line to Piccadilly Circus
Take Piccadilly Line to Piccadilly Circus
Take Bakerloo Line to Waterloo
Take Waterloo & City Line to Waterloo
Take Waterloo & City Line to Bank
Take Waterloo & City Line to Bank
Take District Line to Victoria
Take District Line to Victoria
Take Victoria Line to Oxford Circus
Take Victoria Line to Oxford Circus
Take Central Line to Liverpool Street
Take Central Line to Liverpool Street
Take Circle Line to Euston Square
Take Hammersmith & City Line to Euston Square
Take Hammersmith & City Line to West Ham
Take Hammersmith & City Line to West Ham
Take Jubilee Line to Wembley Park
Take Metropolitan Line to Wembley Park
Take Metropolitan Line to Moorgate
Take Metropolitan Line to Moorgate
Take Northern Line to Mornington Crescent

This code goes around in a huge loop using every single line but the Piccadilly Line, ending in Piccadilly Circus. Then it goes to Turnpike Lane, which reverses the string, before finally unwinding the loop and returning to Mornington Crescent.

Try it online!

ContentLicense: CC BY-SA 4.0


问:
Shortest program that throws StackOverflow Error
Write a program that throws a StackOverflow Error or the equivalent in the language used. For example, in java, the program should throw java.lang.StackOverflowError.

You are not allowed to define a function that calls itself or a new class(except the one containing main in java). It should use the classes of the selected programming language.

And it should not throw the error explicitly.

答:
Mornington Crescent, <s>139</s> 133

```<code>Take Northern Line to Bank
Take Circle Line to Temple
Take Circle Line to Temple
Take Circle Line to Bank
Take Northern Line to Angel
</code>```

Body:
Mornington Crescent, <s>139</s> 133

Take Northern Line to Bank
Take Circle Line to Temple
Take Circle Line to Temple
Take Circle Line to Bank
Take Northern Line to Angel


答:
Perl, <s>24</s> 22 + 1 (-p flag) = 23 bytes

```<code>$\+=$_=$_/5|0while$_}{
</code>```

Using:

```<code>> echo 2016 | perl -pe '$\+=$_=$_/5|0while$_}{'
</code>```

Full program:

while (<>) {
# code above added by -p
    while ($_) {
        $\ += $_ = int($_ / 5);
    }
} {
# code below added by -p
    print;  # prints $_ (undef here) and $\
}
```

Title: Zeroes at the end of a factorial

Body:
Perl, <s>24</s> 22 + 1 (-p flag) = 23 bytes

$\+=$_=$_/5|0while$_}{

Using:

> echo 2016 | perl -pe '$\+=$_=$_/5|0while$_}{'

Full program:

while (<>) {
# code above added by -p
    while ($_) {
        $\ += $_ = int($_ / 5);
    }
} {
# code below added by -p
    print;  # prints $_ (undef here) and $\
}


答:
C, 36

```<code>r;f(n){for(r=0;n/=5;)r+=n;return r;}
</code>```

Same method as @xnor's answer of counting 5s, but just using a simple for loop instead of recursion.

Ideone.

Title: Zeroes at the end of a factorial

Body:
C, 36

r;f(n){for(r=0;n/=5;)r+=n;return r;}

Same method as @xnor's answer of counting 5s, but just using a simple for loop instead of recursion.

Ideone.


问:
Find the remaining side of the tangential quadrilateral
(Taken from https://en.wikipedia.org/wiki/File:Tangential_quadrilateral.svg)

A tangential quadrilateral (see example above) is a quadrilateral in which a circle can be inscribed.

Your task is to find the possible value of d given a, b, and c.

Specs

a, b, c will all be positive integers.

If no possible value of d exists, output 0.

Scoring

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

Testcases

```<code>a b c d
3 4 4 3
1 2 3 2
1 5 3 0
</code>```

答:
Hexagony, 16

```<code>?{?>+'<'-{?/@.!<
</code>```

Try it online!

In expanded form:

```<code>  ? { ?
 > + ' <
' - { ? /
 @ . ! <
  . . .
</code>```

This is actually a fairly simple program. First, we always execute the instructions in this order: ?{?'-{?/<'+ which just reads some values and computes a-b+c. Now if the value is positive, the > sends us north west and we bounce to the lower right < and then print the number (!) and exit (@).

The only really fancy part of the program is how it handles if the result was negative. If this happens, we move south west and execute: '?`{ which actually attempts to read another integer after moving the memory pointer around a bit and we land back on the place where we read another integer. Since the read fails to find a value, it returns zero and because zero isn't positive we wrap to the upper edge of the hexagon in this configuration, so we hit /<!.@ to print out the zero and exit.

Body:
Hexagony, 16

?{?>+'<'-{?/@.!<

Try it online!

In expanded form:

  ? { ?
 > + ' <
' - { ? /
 @ . ! <
  . . .

This is actually a fairly simple program. First, we always execute the instructions in this order: ?{?'-{?/<'+ which just reads some values and computes a-b+c. Now if the value is positive, the > sends us north west and we bounce to the lower right < and then print the number (!) and exit (@).

The only really fancy part of the program is how it handles if the result was negative. If this happens, we move south west and execute: '?`{ which actually attempts to read another integer after moving the memory pointer around a bit and we land back on the place where we read another integer. Since the read fails to find a value, it returns zero and because zero isn't positive we wrap to the upper edge of the hexagon in this configuration, so we hit /<!.@ to print out the zero and exit.


问:
Code-Golf: Lattice Points inside a Circle
The following picture shows the problem:

Write a function that, given an integer as the circle radius, calculates the number of lattice points inside the centered circle (including the boundary).

The image shows:

```<code>f[1] = 5  (blue points)
f[2] = 13 (blue + red points)
</code>```

other values for your checking/debugging:

```<code>f[3]    = 29
f[10]   = 317
f[1000] = 3,141,549
f[2000] = 12,566,345
</code>```

Should have a reasonable performance. Let's say less than a minute for f[1000].

Shortest code wins. Usual Code-Golf rules apply.

Please post the calculation and timing of f[1001] as an example.

答:
Haskell, 41 bytes

f n=1+4*sum[floor$sqrt$n*n-x*x|x<-[0..n]]
```

Counts points in the quadrant x>=0, y>0, multiplies by 4, adds 1 for the center point.

ContentLicense: CC BY-SA 2.5

Body:
Haskell, 41 bytes

f n=1+4*sum[floor$sqrt$n*n-x*x|x<-[0..n]]

Counts points in the quadrant x>=0, y>0, multiplies by 4, adds 1 for the center point.


问:
Showcase of Languages

Notes

This thread is open and unlocked only because the community decided to make an exception. Please do not use this question as evidence that you can ask similar questions here. Please do not create additional showcase questions.

This is no longer a popularity-contest, nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.

This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.

How this works

All answers should include the name of the programming language at the top of the post, prefixed by a #.

Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.

Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.

The snippets do not need to be related. In fact, snippets that are too related may be redundant.

Since this is not a contest, all programming languages are welcome, whenever they were created.

Answers that contain more than a handful of code snippets should use a Stack Snippet to collapse everything except the factoid and one of the snippets.

Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a Stack Snippet for compressing posts, which should mitigate the effect of the 30,000 character limit.

Answers that predate these guidelines should be edited. Please help updating them as needed.

Current answers, sorted alphabetically by language name

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('
' + temp.innerText || temp.textContent + '');}}})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul></code>```

答:
Tellurium

Factoid

Tellurium is an esoteric, tape-based programming language written by me in Python. It's mainly intended for use in code-golf challenges, but it pretty much failed at that task.

Length 1 snippet

```<code>^
</code>```

^ is the output/print command. It outputs whatever is in the selected cell, which, in the above snippet, is 0. (0 is the default value)

Length 2 snippet

```<code>i^
</code>```

This is a simple cat program (a program that copies its input to its output). i takes input and puts it in the selected cell. As you probably remember, ^ outputs whatever is in the selected cell.

(I promise that there will be more interesting snippets later on. There's not much you can do with two commands)

Length 3 snippet

```<code>I§^
</code>```

This snippet calculates the factorial of the input and displays it.

I gets input and converts it to an integer. § calculates the factorial, and stores the result in the selected cell.

There are numerous other math-related one character builtins, for example:

I½^ calculates the exponent of the input

Iq^ calculates the square root of the input

Length 4 snippet

```<code>{p}f
</code>```

This is an anonymous function that does... nothing.

In Tellurium, you can create an anonymous function by using the syntax {code}f. The function can then be called using the command ä.

p is a placeholder command, the equivalent to the Python statement pass.

Length 5 snippet

```<code>[I|^;
</code>```

This snippet uses a loop to output 0 n times. The syntax for a loop in Tellurium is [times|code;. If I is in the times section, it will run the code input times.

Length 6 snippet

```<code>µHi!~^
</code>```

Finally, something more interesting. This snippet outputs Hi!. The syntax for inserting text into the selected cell is a bit strange: µ(text)~.

Length 7 snippet

```<code>¤h|Hey]
</code>```

This snippet showcases variables. Again, the syntax is a bit strange: ¤(name)|(value)]. In this case, it stores "Hey" in the variable h.

To display that variable, use ;h.^.

Title: Showcase of Languages

Body:
Tellurium

Factoid

Tellurium is an esoteric, tape-based programming language written by me in Python. It's mainly intended for use in code-golf challenges, but it pretty much failed at that task.

Length 1 snippet

^

^ is the output/print command. It outputs whatever is in the selected cell, which, in the above snippet, is 0. (0 is the default value)

Length 2 snippet

i^

This is a simple cat program (a program that copies its input to its output). i takes input and puts it in the selected cell. As you probably remember, ^ outputs whatever is in the selected cell.

(I promise that there will be more interesting snippets later on. There's not much you can do with two commands)

Length 3 snippet

I§^

This snippet calculates the factorial of the input and displays it.

I gets input and converts it to an integer. § calculates the factorial, and stores the result in the selected cell.

There are numerous other math-related one character builtins, for example:

I½^ calculates the exponent of the input

Iq^ calculates the square root of the input

Length 4 snippet

{p}f

This is an anonymous function that does... nothing.

In Tellurium, you can create an anonymous function by using the syntax {code}f. The function can then be called using the command ä.

p is a placeholder command, the equivalent to the Python statement pass.

Length 5 snippet

[I|^;

This snippet uses a loop to output 0 n times. The syntax for a loop in Tellurium is [times|code;. If I is in the times section, it will run the code input times.

Length 6 snippet

µHi!~^

Finally, something more interesting. This snippet outputs Hi!. The syntax for inserting text into the selected cell is a bit strange: µ(text)~.

Length 7 snippet

¤h|Hey]

This snippet showcases variables. Again, the syntax is a bit strange: ¤(name)|(value)]. In this case, it stores "Hey" in the variable h.

To display that variable, use ;h.^.


Title: Zeroes at the end of a factorial

Body:
Write a program or function that finds the number of zeroes at the end of n! in base 10, where n is an input number (in any desired format).

It can be assumed that n is a positive integer, meaning that n! is also an integer. There are no zeroes after a decimal point in n!. Also, it can be assumed that your programming language can handle the value of n and n!.

Test cases

```<code>1
==> 0

5
==> 1

100
==> 24

666
==> 165

2016
==> 502

1234567891011121314151617181920
==> 308641972752780328537904295461
</code>```

This is code golf. Standard rules apply. The shortest code in bytes wins.

Body:
dc, 26

?[5/dd0<m]dsmx[+z1<m]dsmxp


问:
Finish a symmetrical map
You are given one-quarter of a map that is symmetrical over the x- and y-axes as input. The program should print the complete map.

The map can contain the following characters: -+/\|., and they should be turned as expected. The in data is always rectangular and small.

Example

```<code>$ cat in
+---
|./.
|/..

$ ./solution < in
+------+
|./..\.|
|/....\|
|\..../|
|.\../.|
+------+
</code>```

Shortest code wins.

答:
Shell Scripting!!

```<code>#!/bin/sh

rm temp
touch temp
file=$1
for STRING in `cat $1`
do
   printf $STRING >> temp
   for ((COUNT=0; COUNT<${#STRING}; COUNT++))
   do
      RECORD[$COUNT]=${STRING:$COUNT:1}
   done
   for ((REV_COUNT=${#STRING}; REV_COUNT>=0; REV_COUNT--))
      do
        if [ "${RECORD[$REV_COUNT]}" = "\\" ]; then
            printf "/" >> temp
        elif [ "${RECORD[$REV_COUNT]}" = "/" ]; then
            printf "\\" >> temp
        else
           printf "${RECORD[$REV_COUNT]}" >> temp
        fi
      done
   echo >> temp
done
cat temp
tac temp > temp2
for STRING in `cat temp2`
do
   for ((COUNT=0; COUNT<${#STRING}; COUNT++))
   do
      RECORD[$COUNT]=${STRING:$COUNT:1}
   if [ "${RECORD[$COUNT]}" = "\\" ]; then
            printf "/"
   elif [ "${RECORD[$COUNT]}" = "/" ]; then
            printf "\\"
   else
           printf "${RECORD[$COUNT]}"
   fi
   done
echo
done
</code>```

I/O

```<code>./solution in

+------+
|./..\.|
|/....\|
|\..../|
|.\../.|
+------+
</code>```

Title: Finish a symmetrical map

Body:
Shell Scripting!!

#!/bin/sh

rm temp
touch temp
file=$1
for STRING in `cat $1`
do
   printf $STRING >> temp
   for ((COUNT=0; COUNT<${#STRING}; COUNT++))
   do
      RECORD[$COUNT]=${STRING:$COUNT:1}
   done
   for ((REV_COUNT=${#STRING}; REV_COUNT>=0; REV_COUNT--))
      do
        if [ "${RECORD[$REV_COUNT]}" = "\\" ]; then
            printf "/" >> temp
        elif [ "${RECORD[$REV_COUNT]}" = "/" ]; then
            printf "\\" >> temp
        else
           printf "${RECORD[$REV_COUNT]}" >> temp
        fi
      done
   echo >> temp
done
cat temp
tac temp > temp2
for STRING in `cat temp2`
do
   for ((COUNT=0; COUNT<${#STRING}; COUNT++))
   do
      RECORD[$COUNT]=${STRING:$COUNT:1}
   if [ "${RECORD[$COUNT]}" = "\\" ]; then
            printf "/"
   elif [ "${RECORD[$COUNT]}" = "/" ]; then
            printf "\\"
   else
           printf "${RECORD[$COUNT]}"
   fi
   done
echo
done

I/O

./solution in

+------+
|./..\.|
|/....\|
|\..../|
|.\../.|
+------+


答:
Python 2, 48 bytes

f=lambda n,i=0:i>n or(n*n-i*i)**.5//1*4+f(n,i+1)
```
<p>Like fR0DDY's solution, but recursive, and returns a float. Returning an int is 51 bytes:</p>
<pre class="lang-python prettyprint-override"><code>f=lambda n,i=0:i>n or 4*int((n*n-i*i)**.5)+f(n,i+1)
</code>```

Title: Code-Golf: Lattice Points inside a Circle

Body:
The following picture shows the problem:

Write a function that, given an integer as the circle radius, calculates the number of lattice points inside the centered circle (including the boundary).

The image shows:

```<code>f[1] = 5  (blue points)
f[2] = 13 (blue + red points)
</code>```

other values for your checking/debugging:

```<code>f[3]    = 29
f[10]   = 317
f[1000] = 3,141,549
f[2000] = 12,566,345
</code>```

Should have a reasonable performance. Let's say less than a minute for f[1000].

Shortest code wins. Usual Code-Golf rules apply.

Please post the calculation and timing of f[1001] as an example.

Body:
Python 2, 48 bytes

f=lambda n,i=0:i>n or(n*n-i*i)**.5//1*4+f(n,i+1)

Like fR0DDY's solution, but recursive, and returns a float. Returning an int is 51 bytes:

f=lambda n,i=0:i>n or 4*int((n*n-i*i)**.5)+f(n,i+1)


答:
Pyke, 5 bytes

```<code>SBP5/
</code>```

Try it here!

```<code>S     -    range(1,input()+1)
 B    -   product(^)
  P   -  prime_factors(^)
   5/ - count(^, 5)
</code>```

Title: Zeroes at the end of a factorial

Body:
Pyke, 5 bytes

SBP5/

Try it here!

S     -    range(1,input()+1)
 B    -   product(^)
  P   -  prime_factors(^)
   5/ - count(^, 5)


答:
rs, 95 bytes

```<code>(\d+)/(_)^^(\1)
_(_+)/_\1 \1
+_(_+) _(_+)$/(_\1)^^((^^_\2)) \2
 _$/
(_+)/(^^\1)
.*?(0*)$/(^^\1)
</code>```

Live demo.

Note that I can't test this with large inputs such as 100. Feel free to try it, but you'd need over 8.486e145 TB of RAM...

An explanation of the first 5 lines is available here.  The last line just counts the zeroes at the end.

Title: Zeroes at the end of a factorial

Body:
rs, 95 bytes

(\d+)/(_)^^(\1)
_(_+)/_\1 \1
+_(_+) _(_+)$/(_\1)^^((^^_\2)) \2
 _$/
(_+)/(^^\1)
.*?(0*)$/(^^\1)

Live demo.

Note that I can't test this with large inputs such as 100. Feel free to try it, but you'd need over 8.486e145 TB of RAM...

An explanation of the first 5 lines is available here.  The last line just counts the zeroes at the end.


问:
Fake Marquee Text
In this challenge fake marquee text is text that is shown part by part, in a scrolling-like fashion.

Some examples:

```<code>testing 4

   t
  te
 tes
test
esti
stin
ting
ing
ng
g

hello 2

 h
he
el
ll
lo
o

foobarz 3

  f
 fo
foo
oob
oba
bar
arz
rz
z

Something a bit longer 10

         S
        So
       Som
      Some
     Somet
    Someth
   Somethi
  Somethin
 Something
Something
omething a
mething a
ething a b
thing a bi
hing a bit
ing a bit
ng a bit l
g a bit lo
 a bit lon
a bit long
 bit longe
bit longer
it longer
t longer
 longer
longer
onger
nger
ger
er
r

small 15

              s
             sm
            sma
           smal
          small
         small
        small
       small
      small
     small
    small
   small
  small
 small
small
mall
all
ll
l

aaa 3

  a
 aa
aaa
aa
a

brace yourself 6

     b
    br
   bra
  brac
 brace
brace
race y
ace yo
ce you
e your
 yours
yourse
oursel
urself
rself
self
elf
lf
f
</code>```

You have to write a program or a function that takes in two input and prints the output as described above. You may or may not output trailing spaces in your output. This is code-golf so shortest code in bytes wins.

If your program is standalone (i.e. when run actually prints the lines) (Input can be hard-coded but easy to change) and sleeps a bit between each line of output you get a -10 bonus.

答:
Lua, 79 bytes

```<code>r=io.read;t=r()w=r()s=" "t=s:rep(w)..t;for i=1,t:len()do print(t:sub(i,i+w))end
</code>```

Title: Fake Marquee Text

Body:
Lua, 79 bytes

r=io.read;t=r()w=r()s=" "t=s:rep(w)..t;for i=1,t:len()do print(t:sub(i,i+w))end


答:
Jelly, 8 bytes

```<code>Ṫṗ2+µ€f/
</code>```

Input is the nested list [[x1, y1, k1], [x2, y2, k2]], output is the list of all incremented coordinates of points with integer coordinates that are common to both squares (falsy if empty, truthy if not).

Try it online! or verify all test cases.

How it works

```<code>Ṫṗ2+µ€f/  Main link. Argument: [[x1, y1, k1], [x2, y2, k2]]

    µ     Combine the chain to the left into a link.
     €    Apply it to each list [xi, yi, ki].
Ṫ           Tail; pop and yield ki.
 ṗ2         Second Cartesian power; yield the list of all pairs [a, b] such that
            1 ≤ a ≤ ki and 1 ≤ b ≤ ki.
   +        Add [xi, yi] to each pair, yielding the list of all pairs [c, d] such
            that xi + 1 ≤ c ≤ xi + ki and yi + 1 ≤ d ≤ yi + ki.
      f/  Reduce by filter, intersecting the resulting lists of pairs.
</code>```

Title: Do these squares overlap?

Body:
Given the coordinates of the upper left corners of two squares and their side lengths, determine whether the squares overlap. A square includes the top and left lines, but not the bottom and right lines. That is, a point (a,b) is inside a square with side length k that starts at (x,y) if and only if x <= a < x+k and y <= b < y+k. A square with side length 0 is degenerate and will not be considered here, thus, k will be positive.

As usual, all standard rules apply. Input and output may be in whatever form is convenient, so long as it's human readable and there is no precomputation. Be sure to specify what input format you use. Your code should take six numbers and output truthy if the squares overlap and falsy otherwise.

Test Cases

```<code>x1 y1 k1  x2 y2 k2  overlap?
 1  1  1   0  1  1  false
 0  0  3   1  1  1  true
 1  1  1   0  0  3  true
 0  0  3   2  1  2  true
 0  0  2   1  1  2  true
 1  1  2   0  0  2  true
 0  1  2   1  0  2  true
 1  0  2   0  1  2  true
 2  0  2   0  2  2  false
 1  0  3   0  1  1  false
 0  2  3   0  0  2  false
</code>```

All inputs will be non-negative integers. That said, I expect that many or most solutions will also be able to handle negatives and floats.

Body:
Jelly, 8 bytes

Ṫṗ2+µ€f/

Input is the nested list [[x1, y1, k1], [x2, y2, k2]], output is the list of all incremented coordinates of points with integer coordinates that are common to both squares (falsy if empty, truthy if not).

Try it online! or verify all test cases.

How it works

Ṫṗ2+µ€f/  Main link. Argument: [[x1, y1, k1], [x2, y2, k2]]

    µ     Combine the chain to the left into a link.
     €    Apply it to each list [xi, yi, ki].
Ṫ           Tail; pop and yield ki.
 ṗ2         Second Cartesian power; yield the list of all pairs [a, b] such that
            1 ≤ a ≤ ki and 1 ≤ b ≤ ki.
   +        Add [xi, yi] to each pair, yielding the list of all pairs [c, d] such
            that xi + 1 ≤ c ≤ xi + ki and yi + 1 ≤ d ≤ yi + ki.
      f/  Reduce by filter, intersecting the resulting lists of pairs.


问:
How many steps does it take from n to 1 by subtracting the greatest divisor?
Inspired by this question over at Mathematics.

The Problem

Let n be a natural number ≥ 2. Take the biggest divisor of n – which is different from n itself – and subtract it from n. Repeat until you get 1.

The Question

How many steps does it take to reach 1 for a given number n ≥ 2.

Detailed Example

Let n = 30.

The greatest divisor of:

```<code>1.   30 is 15  -->  30 - 15 = 15
2.   15 is  5  -->  15 -  5 = 10
3.   10 is  5  -->  10 -  5 =  5
4.    5 is  1  -->   5 -  1 =  4
5.    4 is  2  -->   4 -  2 =  2
6.    2 is  1  -->   2 -  1 =  1
</code>```

It takes 6 steps to reach 1.

Input

Input is an integer n, where n ≥ 2.

Your program should support input up to the language's maximum integer value.

Output

Simply output the number of steps, like 6.

Leading/trailing whitespaces or newlines are fine.

Examples

```<code>f(5)        --> 3
f(30)       --> 6
f(31)       --> 7
f(32)       --> 5
f(100)      --> 8
f(200)      --> 9
f(2016^155) --> 2015
</code>```

Requirements

You can get input from STDIN, command line arguments, as function parameters or from the closest equivalent.

You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it.

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

Standard loopholes are disallowed.

This series can be found on OEIS as well: A064097

A quasi-logarithm defined inductively by a(1) = 0 and a(p) = 1 + a(p-1) if p is prime and a(n*m) = a(n) + a(m) if m,n > 1.

Body:
Perl, 57 + 1 (-p flag) = 58 bytes

$n=$_;$n-=$n/(grep!($n%$_),2..$n/2,$n)[0],$\++while$n>1}{

Usage:

> echo 31 | perl -pe '$n=$_;$n-=$n/(grep!($n%$_),2..$n/2,$n)[0],$\++while$n>1}{'

Ungolfed:

while (<>) {
# code above added by -p
    # $_ has input value
    # $\ has undef (or 0)
    my $n = $_;
    while ($n > 1) {
        my $d = 1;
        for (2 .. ($n / 2)) {
            if ($n % $_ == 0) {
                $d = $n / $_;
                last;
            }
        }
        $n -= $d;
        $\++;
    }
} {
# code below added by -p
    print;  # prints $_ (undef here) and $\
}


问:
Columnar Transposition Cipher

Columnar Transposition Cipher

While I have plenty of programs I have written for more advanced ciphers, I just realised I don't actually have one for one of the simplest: Columnar Transposition. The cipher, in case you don't know, works as follows:

First, you take the key, and write it as numbers. The numbers are made by replacing the letter which comes first in the alphabet with 1, the letter that comes next 2 and so on, ignoring duplicates (the key GOAT would become 2314). These numbers are the headers of the columns.

```<code>2314
----
</code>```

Next, you write your message under the columns.

```<code>2314
----
Hell
o Wo
rld!
</code>```

Finally, rearrange the columns into the numerical order in which they would fall, and read the ciphertext across.

```<code>1234
----
lHel
Wo o
drl!
</code>```

Which will result in your encoded text: lHelWo odrl!

Rules

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

There must be a free interpreter/compiler available for your language.

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

Your program must not write anything to STDERR.

Your program should take input as an argument or from STDIN (or the closest alternative in your language).

Standard loopholes are forbidden.

Requirements

Case must be preserved.

Your cipher should be 'irregular', that is, if there are any spaces left after you have written out your message, it is treated as if it were a normal space character.

Only encryption is required, decryption may come in a later challenge.

Input should be taken from STDIN with the key on the first line, and the plaintext on the second. If you are taking input as an argument, please specify how this is done for your language.

The key can be in any case.

Duplicates in the key should be ignored - that is, ABCDB would become ABCD. Duplicates also apply in any case.

Trailing whitespace is included.

Test Cases

```<code>CBABD, Duplicates are ignored. ==> puDlacit sea eriongr.de
bDaEc, Key can be in multicase! ==> yKce  aenbn mi tucliea s!
</code>```

Full example, with 'surplus space' rule.

```<code>ADCB
----
"Goo
d Mo
rnin
g!"
he c
alle
d.

ABCD
----
"ooG
dom
rnin
g "!
hc e
aell
d  .

Message: "ooGdom rning "!hc eaelld  .
</code>```

Scoring

code-golf is how we score this challenge!

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Python 3, 188 bytes.

There's gotta be a saner way to do this.

```<code>from itertools import*
def f(a,b):a,c,s=a.upper(),''.join,sorted;return c(map(c,zip_longest(*[v for k,v in s([(v,b[i::len({*a})])for i,v in enumerate(s({*a},key=a.find))])],fillvalue='')))
</code>```

Test cases:

```<code>assert f('goat', 'Hello World!') == 'lHelWo odrl!'
assert f('GOAT', 'Hello World!') == 'lHelWo odrl!'
assert f('GOAATAT', 'Hello World!') == 'lHelWo odrl!'
assert f('CBABD', 'Duplicates are ignored.') == 'puDlacit sea eriongr.de'
</code>```

Well that was a fun journey back to square one.

Title: Columnar Transposition Cipher

Body:
Python 3, 188 bytes.

There's gotta be a saner way to do this.

from itertools import*
def f(a,b):a,c,s=a.upper(),''.join,sorted;return c(map(c,zip_longest(*[v for k,v in s([(v,b[i::len({*a})])for i,v in enumerate(s({*a},key=a.find))])],fillvalue='')))

Test cases:

assert f('goat', 'Hello World!') == 'lHelWo odrl!'
assert f('GOAT', 'Hello World!') == 'lHelWo odrl!'
assert f('GOAATAT', 'Hello World!') == 'lHelWo odrl!'
assert f('CBABD', 'Duplicates are ignored.') == 'puDlacit sea eriongr.de'

Well that was a fun journey back to square one.