问:
Compute the Discrete Fourier Transform
Implement the Discrete Fourier Transform (DFT) for a sequence of any length. This may implemented as either a function or a program and the sequence can be given as either an argument or using standard input.

The algorithm will compute a result based on standard DFT in the forward direction. The input sequence has length N and consists of [x(0), x(1), ..., x(N-1)]. The output sequence will have the same length and consists of [X(0), X(1), ..., X(N-1)] where each X(k) is defined by the relation below.

$$X_k\overset{\text{def}}{=}\sum_{n=0}^{N-1}x_n\cdot e^{-2\pi ikn/N}$$

Rules

This is code-golf so the shortest solution wins.

Builtins that compute the DFT in forward or backward (also known as inverse) directions are not allowed.

Floating-point inaccuracies will not be counted against you.

Test Cases

```<code>DFT([1, 1, 1, 1]) = [4, 0, 0, 0]
DFT([1, 0, 2, 0, 3, 0, 4, 0]) = [10, -2+2j, -2, -2-2j, 10, -2+2j, -2, -2-2j]
DFT([1, 2, 3, 4, 5]) = [15, -2.5+3.44j, -2.5+0.81j, -2.5-0.81j, -2.5-3.44j]
DFT([5-3.28571j, -0.816474-0.837162j, 0.523306-0.303902j, 0.806172-3.69346j, -4.41953+2.59494j, -0.360252+2.59411j, 1.26678+2.93119j] = [2, -3j, 5, -7j, 11, -13j, 17]
</code>```

Help

There was a previous challenge for finding the DFT using a FFT algorithm for sequences with lengths equal to a power of 2. You may find some tricks there that might help you here. Keep in mind that this challenge does not limit you to any complexity and also requires your solution to work for sequences of any length.

答:
Pyth, 30

```<code>ms.e*b^.n1****c_2lQk.n0d.j0)QU
</code>```

Test Suite

Very naive approach, just an implementation of the formula. Runs into various minor floating point issues with values which should be additive inverses adding to result in values that are slightly off of zero.

Oddly .j doesn't seem to work with no arguments, but I'm not sure if I'm using it correctly.

Title: Compute the Discrete Fourier Transform

Body:
Pyth, 30

ms.e*b^.n1****c_2lQk.n0d.j0)QU

Test Suite

Very naive approach, just an implementation of the formula. Runs into various minor floating point issues with values which should be additive inverses adding to result in values that are slightly off of zero.

Oddly .j doesn't seem to work with no arguments, but I'm not sure if I'm using it correctly.


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

```<code>-1yn:qt!Gn/E*^/s
</code>```

Input is a column vector, i.e. use semicolon as separator:

```<code>[1; 1; 1; 1]
[1; 0; 2; 0; 3; 0; 4; 0]
[1; 2; 3; 4; 5]
[5-3.28571j; -0.816474-0.837162j; 0.523306-0.303902j; 0.806172-3.69346j; -4.41953+2.59494j; -0.360252+2.59411j; 1.26678+2.93119j]
</code>```

This uses the formula in Leaky Nun's answer, based on the facts that exp(iπ) = −1, and that MATL's power operaton with non-integer exponent produces (as in most programming languages) the principal branch result.

Try it online!

Due to Octave's weird spacing when displaying complex numbers, the real and imaginary parts in each entry of the output are separated by a space, as are consecutive entries. If that looks too ugly, add a ! at the end of the code (17 bytes) to have each entry of the output on a different line.

Explanation

```<code>-1      % Push -1
y       % Get input implicitly. Push a copy below and one on top of -1
n:q     % Row vector [0 1 ... N-1] where N is implicit input length
t!      % Duplicate and transpose: column vector
Gn      % Push input length
/       % Divide
E       % Multiply by 2
*       % Multiply, element-wise with broadcast. Gives the exponent as a matrix
^       % Power (base is -1), element-wise. Gives a matrix
/       % Divide matrix by input (column vector), element-wise with broadcast
s       % Sum
</code>```

ContentLicense: CC BY-SA 4.0

Title: Compute the Discrete Fourier Transform

Body:
Implement the Discrete Fourier Transform (DFT) for a sequence of any length. This may implemented as either a function or a program and the sequence can be given as either an argument or using standard input.

The algorithm will compute a result based on standard DFT in the forward direction. The input sequence has length N and consists of [x(0), x(1), ..., x(N-1)]. The output sequence will have the same length and consists of [X(0), X(1), ..., X(N-1)] where each X(k) is defined by the relation below.

$$X_k\overset{\text{def}}{=}\sum_{n=0}^{N-1}x_n\cdot e^{-2\pi ikn/N}$$

Rules

This is code-golf so the shortest solution wins.

Builtins that compute the DFT in forward or backward (also known as inverse) directions are not allowed.

Floating-point inaccuracies will not be counted against you.

Test Cases

```<code>DFT([1, 1, 1, 1]) = [4, 0, 0, 0]
DFT([1, 0, 2, 0, 3, 0, 4, 0]) = [10, -2+2j, -2, -2-2j, 10, -2+2j, -2, -2-2j]
DFT([1, 2, 3, 4, 5]) = [15, -2.5+3.44j, -2.5+0.81j, -2.5-0.81j, -2.5-3.44j]
DFT([5-3.28571j, -0.816474-0.837162j, 0.523306-0.303902j, 0.806172-3.69346j, -4.41953+2.59494j, -0.360252+2.59411j, 1.26678+2.93119j] = [2, -3j, 5, -7j, 11, -13j, 17]
</code>```

Help

There was a previous challenge for finding the DFT using a FFT algorithm for sequences with lengths equal to a power of 2. You may find some tricks there that might help you here. Keep in mind that this challenge does not limit you to any complexity and also requires your solution to work for sequences of any length.

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

-1yn:qt!Gn/E*^/s

Input is a column vector, i.e. use semicolon as separator:

[1; 1; 1; 1]
[1; 0; 2; 0; 3; 0; 4; 0]
[1; 2; 3; 4; 5]
[5-3.28571j; -0.816474-0.837162j; 0.523306-0.303902j; 0.806172-3.69346j; -4.41953+2.59494j; -0.360252+2.59411j; 1.26678+2.93119j]

This uses the formula in Leaky Nun's answer, based on the facts that exp(iπ) = −1, and that MATL's power operaton with non-integer exponent produces (as in most programming languages) the principal branch result.

Try it online!

Due to Octave's weird spacing when displaying complex numbers, the real and imaginary parts in each entry of the output are separated by a space, as are consecutive entries. If that looks too ugly, add a ! at the end of the code (17 bytes) to have each entry of the output on a different line.

Explanation

-1      % Push -1
y       % Get input implicitly. Push a copy below and one on top of -1
n:q     % Row vector [0 1 ... N-1] where N is implicit input length
t!      % Duplicate and transpose: column vector
Gn      % Push input length
/       % Divide
E       % Multiply by 2
*       % Multiply, element-wise with broadcast. Gives the exponent as a matrix
^       % Power (base is -1), element-wise. Gives a matrix
/       % Divide matrix by input (column vector), element-wise with broadcast
s       % Sum


问:
Dot Product of Diagonals
This challenge is very simple. You are given as input a square matrix, represented in any sane way, and you have to output the dot product of the diagonals of the matrix.

The diagonals in specific are the diagonal running from top-left to bottom-right and from top-right to bottom-left.

Test Cases

```<code>[[-1, 1], [-2, 1]]  ->  -3
[[824, -65], [-814, -741]]  ->  549614
[[-1, -8, 4], [4, 0, -5], [-3, 5, 2]]  ->  -10
[[0, -1, 0], [1, 0, 2], [1, 0, 1]]  ->  1
</code>```

答:
Python, 47 bytes

lambda x:sum(r[i]*r[~i]for i,r in enumerate(x))
```

Test it on Ideone.

ContentLicense: CC BY-SA 3.0

Title: Dot Product of Diagonals

Body:
Python, 47 bytes

lambda x:sum(r[i]*r[~i]for i,r in enumerate(x))

Test it on Ideone.


问:
Write a program that reverses the name of its source file
In a single file, write a program that requires no input and produces no output. When run it should reverse the name of the file it is contained in, regardless of what the name is, without altering the code or producing other lasting side effects.

Any way of achieving this is fine. It only matters that once the program is run the only lasting change is that its file name has been reversed. e.g. no new files should be in the directory.

Running the program again should reverse the name back. Indeed, the program should be able to be run arbitrarily many times.

For the purposes of this challenge:

You may assume filenames are always strings of lowercase letters (a-z) between 1 and 127 characters long. (If your language requires files to have extensions to run then just reverse the part before the extension, e.g. mycode.bat → edocym.bat.)

You may assume the code file is in a directory by itself so it will not have naming conflicts (except with itself).

You may not assume the filename is not a palindrome, i.e. the same when reversed. Filenames that are palindromes should work just as well as those that aren't.

You may read your file's contents or metadata. There are no quine restrictions here.

You may assume your program will be run on a particular, modern, commonplace operating system (e.g. Windows/Linux), since not all shells have the same command set.

As a concrete example, say you have a Python program in a file called
  mycode in its own directory. Running

```<code>python mycode
</code>```

in the terminal should result in the filename being reversed to
  edocym. The file edocym should be alone in its directory - no file
  named mycode should exist anymore. Running

```<code>python edocym
</code>```

will reverse the name back to mycode, at which point the process can
  be repeated indefinitely.

If the same Python file was renamed racecar (without changing the code) and then run

```<code>python racecar
</code>```

nothing should visibly change since "racecar" is a palindrome.
  That same goes if the filename were, say, a or xx.

The shortest code in bytes wins. Tiebreaker is higher voted answer.

答:
MATLAB, <s>50</s> 46 bytes

```<code>e='.m';x=mfilename;movefile([x e],[flip(x) e])
</code>```

Thanks to @Suever for removing 4 bytes and for the testing!

Tested on OS X El Capitan and Debian Jessie, both with Matlab version R2014a.

On Windows a flag 'f' is needed (    e='.m';x=mfilename;movefile([x e],[flip(x) e]),'f')  to change file name while the file is being used.

How it works

```<code>e='.m';                       % Store file extension '.m' in variable `e`
x=mfilename;                  % Get name of file being run, without the extension
movefile([x e],[flip(x) e])   % Move (rename) file. `flip` is used for reversing the
                              % name without extension. [...] is (string) concatenation
</code>```

Body:
MATLAB, <s>50</s> 46 bytes

e='.m';x=mfilename;movefile([x e],[flip(x) e])

Thanks to @Suever for removing 4 bytes and for the testing!

Tested on OS X El Capitan and Debian Jessie, both with Matlab version R2014a.

On Windows a flag 'f' is needed (    e='.m';x=mfilename;movefile([x e],[flip(x) e]),'f')  to change file name while the file is being used.

How it works

e='.m';                       % Store file extension '.m' in variable `e`
x=mfilename;                  % Get name of file being run, without the extension
movefile([x e],[flip(x) e])   % Move (rename) file. `flip` is used for reversing the
                              % name without extension. [...] is (string) concatenation


答:
Julia, 51 bytes

d,f=splitdir(@__FILE__)
cd(d)do
mv(f,reverse(f))end
```

<p>This program should be operating system agnostic, though it was only tested on OS X.</p>

<p>Ungolfed:</p>

<pre class="lang-default prettyprint-override"><code># Get the directory and file name of the current source file
d, f = splitdir(@__FILE__)

# Change the working directory temporarily to d
cd(d) do
    # Overwrite the file with the reverse of its name
    mv(f, reverse(f))
end
</code>```

Title: Write a program that reverses the name of its source file

Body:
In a single file, write a program that requires no input and produces no output. When run it should reverse the name of the file it is contained in, regardless of what the name is, without altering the code or producing other lasting side effects.

Any way of achieving this is fine. It only matters that once the program is run the only lasting change is that its file name has been reversed. e.g. no new files should be in the directory.

Running the program again should reverse the name back. Indeed, the program should be able to be run arbitrarily many times.

For the purposes of this challenge:

You may assume filenames are always strings of lowercase letters (a-z) between 1 and 127 characters long. (If your language requires files to have extensions to run then just reverse the part before the extension, e.g. mycode.bat → edocym.bat.)

You may assume the code file is in a directory by itself so it will not have naming conflicts (except with itself).

You may not assume the filename is not a palindrome, i.e. the same when reversed. Filenames that are palindromes should work just as well as those that aren't.

You may read your file's contents or metadata. There are no quine restrictions here.

You may assume your program will be run on a particular, modern, commonplace operating system (e.g. Windows/Linux), since not all shells have the same command set.

As a concrete example, say you have a Python program in a file called
  mycode in its own directory. Running

```<code>python mycode
</code>```

in the terminal should result in the filename being reversed to
  edocym. The file edocym should be alone in its directory - no file
  named mycode should exist anymore. Running

```<code>python edocym
</code>```

will reverse the name back to mycode, at which point the process can
  be repeated indefinitely.

If the same Python file was renamed racecar (without changing the code) and then run

```<code>python racecar
</code>```

nothing should visibly change since "racecar" is a palindrome.
  That same goes if the filename were, say, a or xx.

The shortest code in bytes wins. Tiebreaker is higher voted answer.

Body:
Julia, 51 bytes

d,f=splitdir(@__FILE__)
cd(d)do
mv(f,reverse(f))end

This program should be operating system agnostic, though it was only tested on OS X.

Ungolfed:

# Get the directory and file name of the current source file
d, f = splitdir(@__FILE__)

# Change the working directory temporarily to d
cd(d) do
    # Overwrite the file with the reverse of its name
    mv(f, reverse(f))
end


问:
Approximation of e
We all know that the Euler's number, denoted by \$e\$, to the power of some variable \$x\$, can be approximated by using the Maclaurin Series expansion:

$$e^x=\sum_{k=0}^{\infty}{\frac{x^k}{k!}}=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\dots$$

By letting \$x\$ equal \$1\$, we obtain

$$\sum_{k=0}^{\infty}{\frac{1}{k!}{=\frac{1}{0!}+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\dots\\=1+1+\frac{1}{2}+\frac{1}{6}+\frac{1}{24}+\dots}}$$

Challenge

Write a program in any language which approximates Euler's number by taking in an input \$n\$ and calculates the series to the \$n\$th term. Note that the first term has denominator \$0!\$, not \$1!\$, i.e. \$n=1\$ corresponds to \$\frac{1}{0!}\$.

Scoring

Program with least amount of bytes wins.

答:
CJam, 11

```<code>r~,:m!Wf#:+
</code>```

or

```<code>r~{m!W#}%:+
</code>```

Try it online: first version and second version

Explanation:

r~ = read and evaluate

m! = factorial

W# = raise to the -1 power (W = -1)

:+ = sum of array

First version constructs the [0…N-1] array and applies factorial and inverse to all its elements; 2nd version does factorial and inverse for each number then puts them in an array.

Title: Approximation of e

Body:
CJam, 11

r~,:m!Wf#:+

or

r~{m!W#}%:+

Try it online: first version and second version

Explanation:

r~ = read and evaluate

m! = factorial

W# = raise to the -1 power (W = -1)

:+ = sum of array

First version constructs the [0…N-1] array and applies factorial and inverse to all its elements; 2nd version does factorial and inverse for each number then puts them in an array.


答:
Python 3, 105 bytes

```<code>import os;a=__file__.split('\\')[::-1][0].split('.');os.rename('.'.join(a),'.'.join([a[0][::-1],a[1]]))
</code>```

-Alex.A removed 1 byte.

-Digital Trauma showed me os.rename() which took away 62 bytes.

-muddyfish removed 7 bytes.

Body:
Python 3, 105 bytes

import os;a=__file__.split('\\')[::-1][0].split('.');os.rename('.'.join(a),'.'.join([a[0][::-1],a[1]]))

-Alex.A removed 1 byte.

-Digital Trauma showed me os.rename() which took away 62 bytes.

-muddyfish removed 7 bytes.


答:
TI-84 BASIC, 12 15 14

```<code>Input N
Σ(A!⁻¹,A,0,N
</code>```

TI is a tokenized language (bytes are counted via tokens, not individual characters).

Title: Approximation of e

Body:
We all know that the Euler's number, denoted by \$e\$, to the power of some variable \$x\$, can be approximated by using the Maclaurin Series expansion:

$$e^x=\sum_{k=0}^{\infty}{\frac{x^k}{k!}}=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\dots$$

By letting \$x\$ equal \$1\$, we obtain

$$\sum_{k=0}^{\infty}{\frac{1}{k!}{=\frac{1}{0!}+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\dots\\=1+1+\frac{1}{2}+\frac{1}{6}+\frac{1}{24}+\dots}}$$

Challenge

Write a program in any language which approximates Euler's number by taking in an input \$n\$ and calculates the series to the \$n\$th term. Note that the first term has denominator \$0!\$, not \$1!\$, i.e. \$n=1\$ corresponds to \$\frac{1}{0!}\$.

Scoring

Program with least amount of bytes wins.

Body:
TI-84 BASIC, 12 15 14

Input N
Σ(A!⁻¹,A,0,N

TI is a tokenized language (bytes are counted via tokens, not individual characters).


答:
J, <s>30</s> 20 bytes

3 bytes thanks to @miles.

Uses the fact that e^ipi = -1.

The formula becomes X_k = sum(x_n / ((-1)^(2nk/N))).

```<code>+/@:%_1^2**/~@i.@#%#
</code>```

Usage

```<code>>> DCT =: +/@:%_1^2**/~@i.@#%#
>> DCT 1 2 3 4 5
<< 15 _2.5j3.44095 _2.5j0.812299 _2.5j_0.812299 _2.5j_3.44095
</code>```

where >> is STDIN and << is STDOUT.

"Floating-point inaccuracies will not be counted against you."

Title: Compute the Discrete Fourier Transform

Body:
J, <s>30</s> 20 bytes

3 bytes thanks to @miles.

Uses the fact that e^ipi = -1.

The formula becomes X_k = sum(x_n / ((-1)^(2nk/N))).

+/@:%_1^2**/~@i.@#%#

Usage

>> DCT =: +/@:%_1^2**/~@i.@#%#
>> DCT 1 2 3 4 5
<< 15 _2.5j3.44095 _2.5j0.812299 _2.5j_0.812299 _2.5j_3.44095

where >> is STDIN and << is STDOUT.

"Floating-point inaccuracies will not be counted against you."


答:
JavaScript (Node), <s>108</s> <s>104</s> 68 bytes

36 bytes saved, thanks to Downgoat!

Windows version:

```<code>require("fs").rename(F=__filename,F.split(/.*\\|/).reverse().join``)
</code>```

Other version:

```<code>require("fs").rename(F=__filename,F.split(/.*\/|/).reverse().join``)
</code>```

Body:
JavaScript (Node), <s>108</s> <s>104</s> 68 bytes

36 bytes saved, thanks to Downgoat!

Windows version:

require("fs").rename(F=__filename,F.split(/.*\\|/).reverse().join``)

Other version:

require("fs").rename(F=__filename,F.split(/.*\/|/).reverse().join``)


答:
Actually, 6 bytes

```<code>r♂!♂ìΣ
</code>```

Try it online!

Explanation:

```<code>r♂!♂ìΣ
r       range(N) ([0, N-1])
 ♂!     factorial of each element
   ♂ì   reciprocal of each element
     Σ  sum
</code>```

Title: Approximation of e

Body:
Actually, 6 bytes

r♂!♂ìΣ

Try it online!

Explanation:

r♂!♂ìΣ
r       range(N) ([0, N-1])
 ♂!     factorial of each element
   ♂ì   reciprocal of each element
     Σ  sum


答:
PHP, 84, 70, 54 bytes

```<code>rename($f=__FILE__,strrev(basename($f,$e='.php')).$e);
</code>```

EDIT: removed 14 bytes thanks to insertusernamehere in the comments

EDIT: removed 16 bytes thanks to Martijn in the comments

Body:
PHP, 84, 70, 54 bytes

rename($f=__FILE__,strrev(basename($f,$e='.php')).$e);

EDIT: removed 14 bytes thanks to insertusernamehere in the comments

EDIT: removed 16 bytes thanks to Martijn in the comments


答:
Pyth, 18 bytes

Uses the fact that e^ipi = -1.

The formula becomes X_k = sum(x_n / ((-1)^(2nk/N))).

```<code>ms.ecb^_1*cyklQdQU
</code>```

Test suite.

Title: Compute the Discrete Fourier Transform

Body:
Pyth, 18 bytes

Uses the fact that e^ipi = -1.

The formula becomes X_k = sum(x_n / ((-1)^(2nk/N))).

ms.ecb^_1*cyklQdQU

Test suite.


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

```<code>LR’µ×'÷L-*²³÷S€
</code>```

Try it online!

How it works

```<code>LR’µ×'÷L-*²³÷S€  Main link. Argument [x(0), ..., x(N-1)].

L                Length; yield N.
 R               Range; yield [1, ..., N].
  ’              Decrement; yield [0, ..., N-1].
   µ             Begin a new, monadic chain. Argument: [0, ..., N-1]
    ×'           Spawned multiply [0, ..., N-1] with itself, yielding the matrix
                 of all possible products k×n.
      ÷L         Divide each product by N.
        -*       Compute (-1)**(kn÷L) for each kn.
          ²      Square each result, computing (-1)**(2kn÷L).
           ³÷    Divide [x(0), ..., x(N-1)] by the results.
             S€  Compute the sum for each row, i.e., each X(k).
</code>```

Title: Compute the Discrete Fourier Transform

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

LR’µ×'÷L-*²³÷S€

Try it online!

How it works

LR’µ×'÷L-*²³÷S€  Main link. Argument [x(0), ..., x(N-1)].

L                Length; yield N.
 R               Range; yield [1, ..., N].
  ’              Decrement; yield [0, ..., N-1].
   µ             Begin a new, monadic chain. Argument: [0, ..., N-1]
    ×'           Spawned multiply [0, ..., N-1] with itself, yielding the matrix
                 of all possible products k×n.
      ÷L         Divide each product by N.
        -*       Compute (-1)**(kn÷L) for each kn.
          ²      Square each result, computing (-1)**(2kn÷L).
           ³÷    Divide [x(0), ..., x(N-1)] by the results.
             S€  Compute the sum for each row, i.e., each X(k).


答:
Python 2, 89 bytes

Uses the fact that e^ipi = -1.

The formula becomes X_k = sum(x_n / ((-1)^(2nk/N))).

```<code>lambda a:[sum(a[x]/(-1+0j)**(x*y*2./len(a))for x in range(len(a)))for y in range(len(a))]
</code>```

Ideone it!

Title: Compute the Discrete Fourier Transform

Body:
Python 2, 89 bytes

Uses the fact that e^ipi = -1.

The formula becomes X_k = sum(x_n / ((-1)^(2nk/N))).

lambda a:[sum(a[x]/(-1+0j)**(x*y*2./len(a))for x in range(len(a)))for y in range(len(a))]

Ideone it!


答:
Bash + common linux utils, 13 bytes

My method is similar to @DigitalTrauma's but a bit shorter due to the pipe with ls:

```<code>mv * `ls|rev`
</code>```

Body:
Bash + common linux utils, 13 bytes

My method is similar to @DigitalTrauma's but a bit shorter due to the pipe with ls:

mv * `ls|rev`


答:
Python 3, 77 bytes

lambda x,e=enumerate:[sum(t/1j**(4*k*n/len(x))for n,t in e(x))for k,_ in e(x)]
```

Test it on Ideone.

The code uses the equivalent formula

Title: Compute the Discrete Fourier Transform

Body:
Implement the Discrete Fourier Transform (DFT) for a sequence of any length. This may implemented as either a function or a program and the sequence can be given as either an argument or using standard input.

The algorithm will compute a result based on standard DFT in the forward direction. The input sequence has length N and consists of [x(0), x(1), ..., x(N-1)]. The output sequence will have the same length and consists of [X(0), X(1), ..., X(N-1)] where each X(k) is defined by the relation below.

$$X_k\overset{\text{def}}{=}\sum_{n=0}^{N-1}x_n\cdot e^{-2\pi ikn/N}$$

Rules

This is code-golf so the shortest solution wins.

Builtins that compute the DFT in forward or backward (also known as inverse) directions are not allowed.

Floating-point inaccuracies will not be counted against you.

Test Cases

```<code>DFT([1, 1, 1, 1]) = [4, 0, 0, 0]
DFT([1, 0, 2, 0, 3, 0, 4, 0]) = [10, -2+2j, -2, -2-2j, 10, -2+2j, -2, -2-2j]
DFT([1, 2, 3, 4, 5]) = [15, -2.5+3.44j, -2.5+0.81j, -2.5-0.81j, -2.5-3.44j]
DFT([5-3.28571j, -0.816474-0.837162j, 0.523306-0.303902j, 0.806172-3.69346j, -4.41953+2.59494j, -0.360252+2.59411j, 1.26678+2.93119j] = [2, -3j, 5, -7j, 11, -13j, 17]
</code>```

Help

There was a previous challenge for finding the DFT using a FFT algorithm for sequences with lengths equal to a power of 2. You may find some tricks there that might help you here. Keep in mind that this challenge does not limit you to any complexity and also requires your solution to work for sequences of any length.

Body:
Python 3, 77 bytes

lambda x,e=enumerate:[sum(t/1j**(4*k*n/len(x))for n,t in e(x))for k,_ in e(x)]

Test it on Ideone.

The code uses the equivalent formula


答:
V, <s>29</s> 26 bytes

```<code>:se ri
izyw:!mv z "
dd
</code>```

Since this contains unprintables, here is a hex dump:

```<code>00000000: 3a73 6520 7269 0a69 127a 1b79 773a 216d  :se ri.i.z.yw:!m
00000010: 7620 127a 2012 220a 6464                 v .z .".dd
</code>```

Note: this will not run  on v.tryitonline.net since TIO does not allow file access.

Explanation:

```<code>:se ri            "Turn on 'reverse mode' (all text is inserted backwards)
i<C-r>z<esc>      "Enter the path to the file in reverse
yw                "Yank a word. This first word is the name we will save the new file as

"Run an "mv" in the terminal with the contents of register 'z' (the path to the file)
"And the contents of register '"' (the word we yanked)
:!mv <C-r>z <C-r>"

dd                "Delete a line so that we don't have any text printed.
</code>```

Body:
V, <s>29</s> 26 bytes

:se ri
izyw:!mv z "
dd

Since this contains unprintables, here is a hex dump:

00000000: 3a73 6520 7269 0a69 127a 1b79 773a 216d  :se ri.i.z.yw:!m
00000010: 7620 127a 2012 220a 6464                 v .z .".dd

Note: this will not run  on v.tryitonline.net since TIO does not allow file access.

Explanation:

:se ri            "Turn on 'reverse mode' (all text is inserted backwards)
i<C-r>z<esc>      "Enter the path to the file in reverse
yw                "Yank a word. This first word is the name we will save the new file as

"Run an "mv" in the terminal with the contents of register 'z' (the path to the file)
"And the contents of register '"' (the word we yanked)
:!mv <C-r>z <C-r>"

dd                "Delete a line so that we don't have any text printed.


答:
Ruby, 24 bytes

```<code>File.rename$0,$0.reverse
</code>```

Fairly self-explanatory. ($0 is the name of the file being executed.)

Run with ruby whatever with a working directory of the directory that contains the file.

Body:
In a single file, write a program that requires no input and produces no output. When run it should reverse the name of the file it is contained in, regardless of what the name is, without altering the code or producing other lasting side effects.

Any way of achieving this is fine. It only matters that once the program is run the only lasting change is that its file name has been reversed. e.g. no new files should be in the directory.

Running the program again should reverse the name back. Indeed, the program should be able to be run arbitrarily many times.

For the purposes of this challenge:

You may assume filenames are always strings of lowercase letters (a-z) between 1 and 127 characters long. (If your language requires files to have extensions to run then just reverse the part before the extension, e.g. mycode.bat → edocym.bat.)

You may assume the code file is in a directory by itself so it will not have naming conflicts (except with itself).

You may not assume the filename is not a palindrome, i.e. the same when reversed. Filenames that are palindromes should work just as well as those that aren't.

You may read your file's contents or metadata. There are no quine restrictions here.

You may assume your program will be run on a particular, modern, commonplace operating system (e.g. Windows/Linux), since not all shells have the same command set.

As a concrete example, say you have a Python program in a file called
  mycode in its own directory. Running

```<code>python mycode
</code>```

in the terminal should result in the filename being reversed to
  edocym. The file edocym should be alone in its directory - no file
  named mycode should exist anymore. Running

```<code>python edocym
</code>```

will reverse the name back to mycode, at which point the process can
  be repeated indefinitely.

If the same Python file was renamed racecar (without changing the code) and then run

```<code>python racecar
</code>```

nothing should visibly change since "racecar" is a palindrome.
  That same goes if the filename were, say, a or xx.

The shortest code in bytes wins. Tiebreaker is higher voted answer.

Body:
Ruby, 24 bytes

File.rename$0,$0.reverse

Fairly self-explanatory. ($0 is the name of the file being executed.)

Run with ruby whatever with a working directory of the directory that contains the file.


问:
Ain't there nothing up my sleeves

Note: reference to Nothing up my sleeve number.

Your task is to take no input and generate this exact output:

d76aa478 e8c7b756 242070db c1bdceee f57c0faf 4787c62a a8304613 fd469501
698098d8 8b44f7af ffff5bb1 895cd7be 6b901122 fd987193 a679438e 49b40821
f61e2562 c040b340 265e5a51 e9b6c7aa d62f105d 02441453 d8a1e681 e7d3fbc8
21e1cde6 c33707d6 f4d50d87 455a14ed a9e3e905 fcefa3f8 676f02d9 8d2a4c8a
fffa3942 8771f681 6d9d6122 fde5380c a4beea44 4bdecfa9 f6bb4b60 bebfbc70
289b7ec6 eaa127fa d4ef3085 04881d05 d9d4d039 e6db99e5 1fa27cf8 c4ac5665
f4292244 432aff97 ab9423a7 fc93a039 655b59c3 8f0ccc92 ffeff47d 85845dd1
6fa87e4f fe2ce6e0 a3014314 4e0811a1 f7537e82 bd3af235 2ad7d2bb eb86d391
```
<p>A trailing newline is optional.</p>
<p>The MD5 hash for the version <strong>with</strong> trailing newline is:</p>
<ul>
<li><code>FC1D37B5295177E7F28509EC9197688F</code></li>
</ul>
<p>The MD5 hash for the version <strong>without</strong> trailing newline is:</p>
<ul>
<li><code>FAC194EC5EFD2E5A5AC07C2A4925699B</code></li>
</ul>
<h3>How the string is generated</h3>
<p>Those 64 strings are actually the 64 hexadecimal numbers used in the MD5 hash.</p>
<p>The pseudocode for them:</p>
<pre class="lang-python prettyprint-override"><code>numbers = floor(2^32 × abs(sin(i))) for i in [1,2,...,64]
</code>```

The reference Python code:

from math import*
for i in range(8):print" ".join("{:08x}".format(int(abs(2**32*sin(-~j))))for j in range(8*i,8*i+8))
```
<p>Ungolfed:</p>
<pre class="lang-python prettyprint-override"><code>from math import*
for i in range(8):
    temp = []
    for j in range(8*i,8*i+8):
        temp += ["{:08x}".format(int(abs(2**32*sin(j+1))))]
    print " ".join(temp)
</code>```

答:
Jelly, <s>26</s> <s>24</s> 23 bytes

```<code>64RÆSA‘æ«32Ḟb⁴Ḋ€‘ịØhs8G
</code>```

Try it online!

How it works

```<code>64RÆSA‘æ«32Ḟb⁴Ḋ€‘ịØhs8G  Main link. No arguments.

64R                      Yield [1, ..., 64].
   ÆS                    Apply sine to each.
     A                   Take absolute values.
      ‘                  Increment.
                         This avoid padding the hex strings to 8 characters.
       æ«32              Left-shift by 32 units.
           Ḟ             Floor.
            b⁴           Convert to base 16 (list of integers).
              Ḋ€         Remove the first digit of each, undoing the increment.
                ‘        Increment each base 16 digit (for 1-based indexing).
                 ịØh     Index into "0123456789abcdef".
                    s8   Split into chunks of length 8.
                      G  Grid; separate columns by spaces, rows by linefeeds.
</code>```

Title: Ain't there nothing up my sleeves

Body:
Jelly, <s>26</s> <s>24</s> 23 bytes

64RÆSA‘æ«32Ḟb⁴Ḋ€‘ịØhs8G

Try it online!

How it works

64RÆSA‘æ«32Ḟb⁴Ḋ€‘ịØhs8G  Main link. No arguments.

64R                      Yield [1, ..., 64].
   ÆS                    Apply sine to each.
     A                   Take absolute values.
      ‘                  Increment.
                         This avoid padding the hex strings to 8 characters.
       æ«32              Left-shift by 32 units.
           Ḟ             Floor.
            b⁴           Convert to base 16 (list of integers).
              Ḋ€         Remove the first digit of each, undoing the increment.
                ‘        Increment each base 16 digit (for 1-based indexing).
                 ịØh     Index into "0123456789abcdef".
                    s8   Split into chunks of length 8.
                      G  Grid; separate columns by spaces, rows by linefeeds.


答:
Pyth, <s>31</s> 27 bytes

Thanks to @Dennis for saving 4 bytes!

```<code>jjL;c8mt.Hs*^2 32h.a.tdZS64
</code>```

Try it here!

Explanation

```
jjL;c8mt.Hs*^2 32h.a.tdZS64

      m                 S64   # map over [1...64]
          s*^2 32h.a.tdZ      # floor(2^32 * abs(sin(d))+1)
       t.H                    # convert to hex-string and discard the first digit
    c8                        # split into 8 parts
jjL;                          # join on whitespaces and then on newlines
```

Title: Ain't there nothing up my sleeves

Body:
Note: reference to Nothing up my sleeve number.

Your task is to take no input and generate this exact output:

d76aa478 e8c7b756 242070db c1bdceee f57c0faf 4787c62a a8304613 fd469501
698098d8 8b44f7af ffff5bb1 895cd7be 6b901122 fd987193 a679438e 49b40821
f61e2562 c040b340 265e5a51 e9b6c7aa d62f105d 02441453 d8a1e681 e7d3fbc8
21e1cde6 c33707d6 f4d50d87 455a14ed a9e3e905 fcefa3f8 676f02d9 8d2a4c8a
fffa3942 8771f681 6d9d6122 fde5380c a4beea44 4bdecfa9 f6bb4b60 bebfbc70
289b7ec6 eaa127fa d4ef3085 04881d05 d9d4d039 e6db99e5 1fa27cf8 c4ac5665
f4292244 432aff97 ab9423a7 fc93a039 655b59c3 8f0ccc92 ffeff47d 85845dd1
6fa87e4f fe2ce6e0 a3014314 4e0811a1 f7537e82 bd3af235 2ad7d2bb eb86d391
```
<p>A trailing newline is optional.</p>
<p>The MD5 hash for the version <strong>with</strong> trailing newline is:</p>
<ul>
<li><code>FC1D37B5295177E7F28509EC9197688F</code></li>
</ul>
<p>The MD5 hash for the version <strong>without</strong> trailing newline is:</p>
<ul>
<li><code>FAC194EC5EFD2E5A5AC07C2A4925699B</code></li>
</ul>
<h3>How the string is generated</h3>
<p>Those 64 strings are actually the 64 hexadecimal numbers used in the MD5 hash.</p>
<p>The pseudocode for them:</p>
<pre class="lang-python prettyprint-override"><code>numbers = floor(2^32 × abs(sin(i))) for i in [1,2,...,64]
</code>```

The reference Python code:

from math import*
for i in range(8):print" ".join("{:08x}".format(int(abs(2**32*sin(-~j))))for j in range(8*i,8*i+8))
```
<p>Ungolfed:</p>
<pre class="lang-python prettyprint-override"><code>from math import*
for i in range(8):
    temp = []
    for j in range(8*i,8*i+8):
        temp += ["{:08x}".format(int(abs(2**32*sin(j+1))))]
    print " ".join(temp)
</code>```

Body:
Pyth, <s>31</s> 27 bytes

Thanks to @Dennis for saving 4 bytes!

jjL;c8mt.Hs*^2 32h.a.tdZS64

Try it here!

Explanation

jjL;c8mt.Hs*^2 32h.a.tdZS64

      m                 S64   # map over [1...64]
          s*^2 32h.a.tdZ      # floor(2^32 * abs(sin(d))+1)
       t.H                    # convert to hex-string and discard the first digit
    c8                        # split into 8 parts
jjL;                          # join on whitespaces and then on newlines


答:
PHP, <s>131</s> 81 bytes

```<code>for(;++$i<65;){echo str_pad(dechex(2**32*abs(sin($i))),8,"0",0).($i%8?" ":"\n");}
</code>```

This is a pretty straight-forward loop with a few conditions for spacing.

@insertusernamehere's shortcuts cut it down by 50 bytes.

Title: Ain't there nothing up my sleeves

Body:
PHP, <s>131</s> 81 bytes

for(;++$i<65;){echo str_pad(dechex(2**32*abs(sin($i))),8,"0",0).($i%8?" ":"\n");}

This is a pretty straight-forward loop with a few conditions for spacing.

@insertusernamehere's shortcuts cut it down by 50 bytes.


答:
Julia, <s>69</s> <s>63</s> 58 bytes

[@printf "%08x%c"√sin(n)^2÷.5^32 n%8>0?32:10for n=1:64]
```

Try it online!

How it works

For each n between 1 and 64, we compute √sin(n)^2÷.5^32 and n%8>0?32:10, apply string formatting with "%08x%c" and print to STDOUT.

√sin(n)^2 computes the absolute value of sin(n). abs(sin(n)) is equally short (in bytes), but it would require a space to separate it from the format string.

÷.5^32 divides the previous result by 0.532 = 1 / 232, effectively multiplying it by 232. However, ÷ performs integer divsion, so the result is truncated.

n%8>0?32:10 returns 32 (the code point of a space) whenever n is not divisible by 8 and 10 (the code point of a linefeed) otherwise.

"%08x%c" turns the first result into lowercase hexadecimal representation, left-padded with zeroes to length 8; and the second result into a character.

Finally, the array comprehension returns an array of 64 instances of Nothing, the return value of @printf. Outside a REPL, this does not affect output.

Title: Ain't there nothing up my sleeves

Body:
Julia, <s>69</s> <s>63</s> 58 bytes

[@printf "%08x%c"√sin(n)^2÷.5^32 n%8>0?32:10for n=1:64]

Try it online!

How it works

For each n between 1 and 64, we compute √sin(n)^2÷.5^32 and n%8>0?32:10, apply string formatting with "%08x%c" and print to STDOUT.

√sin(n)^2 computes the absolute value of sin(n). abs(sin(n)) is equally short (in bytes), but it would require a space to separate it from the format string.

÷.5^32 divides the previous result by 0.532 = 1 / 232, effectively multiplying it by 232. However, ÷ performs integer divsion, so the result is truncated.

n%8>0?32:10 returns 32 (the code point of a space) whenever n is not divisible by 8 and 10 (the code point of a linefeed) otherwise.

"%08x%c" turns the first result into lowercase hexadecimal representation, left-padded with zeroes to length 8; and the second result into a character.

Finally, the array comprehension returns an array of 64 instances of Nothing, the return value of @printf. Outside a REPL, this does not affect output.


答:
PHP, 31 bytes

Nothing much to explain I guess:

```<code>rename($x=$argv[0],strrev($x));
</code>```

Body:
PHP, 31 bytes

Nothing much to explain I guess:

rename($x=$argv[0],strrev($x));


答:
Julia, 45 bytes

```<code>~=endof
!x=sum(x./im.^(4(r=0:~x-1).*r'/~x),1)
</code>```

Try it online!

The code uses the equivalent formula

Title: Compute the Discrete Fourier Transform

Body:
Julia, 45 bytes

~=endof
!x=sum(x./im.^(4(r=0:~x-1).*r'/~x),1)

Try it online!

The code uses the equivalent formula


问:
Is my emoji dry?
This is my pet emoji, Billy:

```<code>-_-
</code>```

Emojis don't like to be in the rain, so Billy is sad... Let's draw him an umbrella to make him feel better!

```<code>  /\
 /  \
/    \

  -_-
</code>```

This is good, he is entirely covered by his umbrella! Here is an example where only part of him is covered:

```<code>  /\
 /  \
/    \

     -_-
</code>```

In this case, sections 2 and 3 of his body are exposed to the rain.

Umbrellas come in many shapes and sizes, but they're always made up from a series of ascending slashes / followed by a series of descending backslashes \. For example, these are all valid umbrellas:

```<code>  /\
 /  \
/    \

/\

    /\
   /  \
  /    \
 /      \
/        \
</code>```

And these are not:

```<code>/   \

\/

  \
 / \
/   \

 0\
/  \

//\\
/  \
</code>```

You need to determine which parts of my emoji are exposed to the rain.

Clarifications

Your program (or function) will take a 2d string as input. This can be in whatever format is most convenient or natural to your language. An array of strings, an array of arrays of characters, a string with newlines in it etc.

You must output which sections of the emoji are exposed to the rain. This can be zero-indexed or one-indexed, as long as you make this clear. Output can be in any reasonable format. If the entire emoji is protected from the rain, output nothing (or an empty array).

You can assume that all inputs will have a valid umbrella, and the same emoji: -_-. The emoji will always be on the last line of the input, however their might be several empty lines between the umbrella and the emoji.

Everything that isn't part of the umbrella or the emoji will be a space   character or newline.

The input will be padded with spaces so that the length of each line is the same.

Standard loopholes apply, and the shortest answer in bytes wins!

Test IO:

All of the sample cases will use one-indexing.

```<code>  /\
 /  \
/    \

  -_-

Outputs: []

----------------

   /\
  /  \

     -_-

Outputs: [2, 3]

----------------

    /\
   -_-

Outputs: [1]

----------------

     /\
    /  \
   /    \
  /      \
 /        \
/          \

               -_-

Outputs: [1, 2, 3]
</code>```

答:
Pyth, <s>27</s> 23 bytes

0-indexed.

```<code>-m.xsd;.T:R"-_-"s`M3.zd
</code>```

Try it online!

Explanation

```<code>-m.xsd;.T:R"-_-"s`M3.zd

                    .z   all lines of input, as a list
         :R"-_-"s`M3     replace "-_-" by "012"
                         "012" is generated by s`M3
       .T                transpose, return all columns
                         The sample input becomes:
                           0
                           1
                          /2
                         /
                         \
                         \
 m   d                   for each line:
  .xs                        attempt to convert to integer.
      ;                      if errors, replace to space
-                     d  remove all spaces
</code>```

History

27 bytes: sM:#"^ *\d"0.T:R"-_-"s`M3.z (Try it online!)

Title: Is my emoji dry?

Body:
Pyth, <s>27</s> 23 bytes

0-indexed.

-m.xsd;.T:R"-_-"s`M3.zd

Try it online!

Explanation

-m.xsd;.T:R"-_-"s`M3.zd

                    .z   all lines of input, as a list
         :R"-_-"s`M3     replace "-_-" by "012"
                         "012" is generated by s`M3
       .T                transpose, return all columns
                         The sample input becomes:
                           0
                           1
                          /2
                         /
                         \
                         \
 m   d                   for each line:
  .xs                        attempt to convert to integer.
      ;                      if errors, replace to space
-                     d  remove all spaces

History

27 bytes: sM:#"^ *\d"0.T:R"-_-"s`M3.z (Try it online!)


答:
JavaScript (ES6), 95 bytes

a=>[...a[n=0]].map((_,i)=>a.map(s=>(c=s[i])>"-"&c<"_"?p=1:n+=!++c,p=0)|p<!c&&o.push(n),o=[])&&o
```

<p>Input should be an array of strings, with each line padded with spaces to form a square. Output is an array of 1-indexed numbers.</p>

<h2>Explanation</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var solution =

a=>
  [...a[n=0]].map((_,i)=>  // n = current index of emoji, for each column i of input
    a.map(s=>              // for each line s
      (c=s[i])             // c = character in column
      >"-"&c<"_"?p=1       // p = 1 if column is protected from rain
      :n+=!++c,            // increment n if emoji character found, c = 1 if last line
                           // contained a space in the current column
      p=0
    )
    |p<!c&&o.push(n),      // if the emoji is not protected in the current column
    o=[]
  )
  &&o</code>```

<textarea id="input" rows="6" cols="40">   /\
  /  \

     -_-</textarea>

<button onclick="result.textContent=solution(input.value.split('\n'))">Go</button>

```</code>```

Title: Is my emoji dry?

Body:
This is my pet emoji, Billy:

```<code>-_-
</code>```

Emojis don't like to be in the rain, so Billy is sad... Let's draw him an umbrella to make him feel better!

```<code>  /\
 /  \
/    \

  -_-
</code>```

This is good, he is entirely covered by his umbrella! Here is an example where only part of him is covered:

```<code>  /\
 /  \
/    \

     -_-
</code>```

In this case, sections 2 and 3 of his body are exposed to the rain.

Umbrellas come in many shapes and sizes, but they're always made up from a series of ascending slashes / followed by a series of descending backslashes \. For example, these are all valid umbrellas:

```<code>  /\
 /  \
/    \

/\

    /\
   /  \
  /    \
 /      \
/        \
</code>```

And these are not:

```<code>/   \

\/

  \
 / \
/   \

 0\
/  \

//\\
/  \
</code>```

You need to determine which parts of my emoji are exposed to the rain.

Clarifications

Your program (or function) will take a 2d string as input. This can be in whatever format is most convenient or natural to your language. An array of strings, an array of arrays of characters, a string with newlines in it etc.

You must output which sections of the emoji are exposed to the rain. This can be zero-indexed or one-indexed, as long as you make this clear. Output can be in any reasonable format. If the entire emoji is protected from the rain, output nothing (or an empty array).

You can assume that all inputs will have a valid umbrella, and the same emoji: -_-. The emoji will always be on the last line of the input, however their might be several empty lines between the umbrella and the emoji.

Everything that isn't part of the umbrella or the emoji will be a space   character or newline.

The input will be padded with spaces so that the length of each line is the same.

Standard loopholes apply, and the shortest answer in bytes wins!

Test IO:

All of the sample cases will use one-indexing.

```<code>  /\
 /  \
/    \

  -_-

Outputs: []

----------------

   /\
  /  \

     -_-

Outputs: [2, 3]

----------------

    /\
   -_-

Outputs: [1]

----------------

     /\
    /  \
   /    \
  /      \
 /        \
/          \

               -_-

Outputs: [1, 2, 3]
</code>```

Body:
JavaScript (ES6), 95 bytes

a=>[...a[n=0]].map((_,i)=>a.map(s=>(c=s[i])>"-"&c<"_"?p=1:n+=!++c,p=0)|p<!c&&o.push(n),o=[])&&o

Input should be an array of strings, with each line padded with spaces to form a square. Output is an array of 1-indexed numbers.

Explanation

var solution =

a=>
  [...a[n=0]].map((_,i)=>  // n = current index of emoji, for each column i of input
    a.map(s=>              // for each line s
      (c=s[i])             // c = character in column
      >"-"&c<"_"?p=1       // p = 1 if column is protected from rain
      :n+=!++c,            // increment n if emoji character found, c = 1 if last line
                           // contained a space in the current column
      p=0
    )
    |p<!c&&o.push(n),      // if the emoji is not protected in the current column
    o=[]
  )
  &&o

<textarea id="input" rows="6" cols="40">   /\
  /  \

     -_-</textarea><br />
<button onclick="result.textContent=solution(input.value.split('\n'))">Go</button>
<pre id="result"></pre>


答:
V, <s>20</s> 19 bytes (non-competing)

```<code>G^R123?/
f\GddHÍó
</code>```

Alternate, competing version (21 bytes):

```<code>G^R123?/
f\òjòddHÍó
</code>```

Try it online! (Note, tryitonline.net uses a slightly old version of V. To compensate for this, it uses this slightly longer version)

Explanation:

```<code>G^          "Move to the first non-whitespace character on the last column
  R123<esc> "Replace the emojii with '123'

?/          "Move backwards to the last '/' character
  <C-v>     "Start a blockwise selection
       f\G  "Move the selection to the next '\', and then to the last line
d           "Delete the block selection
 dH         "Delete the umbrella

</code>```

This alone produces the correct result in 17 bytes. However, it also creates some extra whitespace. I don't mind it, but I don't want to give myself an unfair advantage, so I'm adding two bytes:

```<code>Íó          "Remove all whitespace
</code>```

Title: Is my emoji dry?

Body:
V, <s>20</s> 19 bytes (non-competing)

G^R123?/
f\GddHÍó

Alternate, competing version (21 bytes):

G^R123?/
f\òjòddHÍó

Try it online! (Note, tryitonline.net uses a slightly old version of V. To compensate for this, it uses this slightly longer version)

Explanation:

G^          "Move to the first non-whitespace character on the last column
  R123<esc> "Replace the emojii with '123'

?/          "Move backwards to the last '/' character
  <C-v>     "Start a blockwise selection
       f\G  "Move the selection to the next '\', and then to the last line
d           "Delete the block selection
 dH         "Delete the umbrella

This alone produces the correct result in 17 bytes. However, it also creates some extra whitespace. I don't mind it, but I don't want to give myself an unfair advantage, so I'm adding two bytes:

Íó          "Remove all whitespace


问:
Stack Exchange Vote Counter
Write a program/function that returns the vote count of its own Stack Exchange answer at the time of its execution.

Your program/function may access this page (codegolf.stackexchange.com/questions/82609) off the internet, however:

Your program/function may not accept any user input and

The use of URL shorteners is not allowed

Your program/function may use only its own source as a reference point to its vote count (for example: no referencing strings of text in its contained answer but not in its own source)

Your program/function must output its own vote count and only its own vote count (for example: no returning all vote counts on this page)

This is code-golf, shortest code wins.

答:
JavaScript ES6, 107 bytes

fetch`//api.stackexchange.com/posts/82672?site=codegolf`.then(r=>r.json()).then(b=>alert(b.items[0].score))```

Real programmers don't use XMLHttpRequest. Real programmers use the Fetch API.

Title: Stack Exchange Vote Counter

Body:
JavaScript ES6, 107 bytes

fetch`//api.stackexchange.com/posts/82672?site=codegolf`.then(r=>r.json()).then(b=>alert(b.items[0].score))

Real programmers don't use XMLHttpRequest. Real programmers use the Fetch API.


答:
JavaScript (ES7), 115 bytes

```<code>_=>`_ _ _ _ _ _ _ _
`.repeat(8).replace(/_/g,_=>(0+(Math.abs(Math.sin(++n))*2**32>>>0).toString(16)).slice(-8),n=0)
</code>```

Includes the trailing newline.

Title: Ain't there nothing up my sleeves

Body:
JavaScript (ES7), 115 bytes

_=>`_ _ _ _ _ _ _ _
`.repeat(8).replace(/_/g,_=>(0+(Math.abs(Math.sin(++n))*2**32>>>0).toString(16)).slice(-8),n=0)

Includes the trailing newline.


答:
Python 2, 78 bytes

l=input();p=1
for _ in l:print reduce(lambda a,b:a*p+b,l)*p;p*=1j**(4./len(l))
```
<p>The polynomial is evaluated for each power <code>p</code> of <code>1j**(4./len(l))</code>.</p>
<p>The expression <code>reduce(lambda a,b:a*p+b,l)</code> evaluates the polynomial given by <code>l</code> on the value <code>p</code> via Horner's method:</p>
<pre class="lang-python prettyprint-override"><code>reduce(lambda a,b:a*10+b,[1,2,3,4,5])
=> 12345
</code>```

Except, out input list is reversed, with constant term at the end. We could reverse it, but because p**len(l)==1 for Fourier coefficients, we can use a hack of inverting p and multiplying the whole result by p.

Some equal-length attempts:

l=input();i=0
for _ in l:print reduce(lambda a,b:(a+b)*1j**i,l,0);i+=4./len(l)

l=input();i=0
for _ in l:print reduce(lambda a,b:a*1j**i+b,l+[0]);i+=4./len(l)
```
<p>As a function for 1 byte more (79):</p>
<pre class="lang-python prettyprint-override"><code>lambda l:[reduce(lambda a,b:a*1j**(i*4./len(l))+b,l+[0])for i in range(len(l))]
</code>```

An attempt at recursion (80):

f=lambda l,i=0:l[i:]and[reduce(lambda a,b:(a+b)*1j**(i*4./len(l)),l,0)]+f(l,i+1)
```
<p>Iteratively simulating <code>reduce</code> (80):</p>
<pre class="lang-python prettyprint-override"><code>l=input();p=1;N=len(l)
exec"s=0\nfor x in l:s=s*p+x\nprint s*p;p*=1j**(4./N);"*N
</code>```

Title: Compute the Discrete Fourier Transform

Body:
Implement the Discrete Fourier Transform (DFT) for a sequence of any length. This may implemented as either a function or a program and the sequence can be given as either an argument or using standard input.

The algorithm will compute a result based on standard DFT in the forward direction. The input sequence has length N and consists of [x(0), x(1), ..., x(N-1)]. The output sequence will have the same length and consists of [X(0), X(1), ..., X(N-1)] where each X(k) is defined by the relation below.

$$X_k\overset{\text{def}}{=}\sum_{n=0}^{N-1}x_n\cdot e^{-2\pi ikn/N}$$

Rules

This is code-golf so the shortest solution wins.

Builtins that compute the DFT in forward or backward (also known as inverse) directions are not allowed.

Floating-point inaccuracies will not be counted against you.

Test Cases

```<code>DFT([1, 1, 1, 1]) = [4, 0, 0, 0]
DFT([1, 0, 2, 0, 3, 0, 4, 0]) = [10, -2+2j, -2, -2-2j, 10, -2+2j, -2, -2-2j]
DFT([1, 2, 3, 4, 5]) = [15, -2.5+3.44j, -2.5+0.81j, -2.5-0.81j, -2.5-3.44j]
DFT([5-3.28571j, -0.816474-0.837162j, 0.523306-0.303902j, 0.806172-3.69346j, -4.41953+2.59494j, -0.360252+2.59411j, 1.26678+2.93119j] = [2, -3j, 5, -7j, 11, -13j, 17]
</code>```

Help

There was a previous challenge for finding the DFT using a FFT algorithm for sequences with lengths equal to a power of 2. You may find some tricks there that might help you here. Keep in mind that this challenge does not limit you to any complexity and also requires your solution to work for sequences of any length.

Body:
Python 2, 78 bytes

l=input();p=1
for _ in l:print reduce(lambda a,b:a*p+b,l)*p;p*=1j**(4./len(l))

The polynomial is evaluated for each power p of 1j**(4./len(l)).

The expression reduce(lambda a,b:a*p+b,l) evaluates the polynomial given by l on the value p via Horner's method:

reduce(lambda a,b:a*10+b,[1,2,3,4,5])
=> 12345

Except, out input list is reversed, with constant term at the end. We could reverse it, but because p**len(l)==1 for Fourier coefficients, we can use a hack of inverting p and multiplying the whole result by p.

Some equal-length attempts:

l=input();i=0
for _ in l:print reduce(lambda a,b:(a+b)*1j**i,l,0);i+=4./len(l)

l=input();i=0
for _ in l:print reduce(lambda a,b:a*1j**i+b,l+[0]);i+=4./len(l)

As a function for 1 byte more (79):

lambda l:[reduce(lambda a,b:a*1j**(i*4./len(l))+b,l+[0])for i in range(len(l))]

An attempt at recursion (80):

f=lambda l,i=0:l[i:]and[reduce(lambda a,b:(a+b)*1j**(i*4./len(l)),l,0)]+f(l,i+1)

Iteratively simulating reduce (80):

l=input();p=1;N=len(l)
exec"s=0\nfor x in l:s=s*p+x\nprint s*p;p*=1j**(4./N);"*N


答:
MATL, 28 bytes

```<code>64:Y,|32W*k16YAkZ{Zc72e!3LZ)
</code>```

Try it online!

Pretty straightforward computation. Getting the required output format takes almost half the byte count.

Title: Ain't there nothing up my sleeves

Body:
MATL, 28 bytes

64:Y,|32W*k16YAkZ{Zc72e!3LZ)

Try it online!

Pretty straightforward computation. Getting the required output format takes almost half the byte count.


问:
Generalized Birthday Problem
Tonight, my fiancée took me out to dinner to celebrate my birthday. While we were out, I heard Happy Birthday sung to 5 different guests (including myself), in a restaurant full of 50 people. This got me wondering - the original birthday problem (finding the probability that 2 people in a room of N people share the same birthday) is very simple and straightforward. But what about calculating the probability that at least k people out of N people share the same birthday?

In case you're wondering, the probability of at least 5 people out of 50 total people sharing the same birthday is about 1/10000.

The Challenge

Given two integers N and k, where N >= k > 0, output the probability that at least k people in a group of N people share the same birthday. To keep things simple, assume that there are always 365 possible birthdays, and that all days are equally likely.

For k = 2, this boils down to the original birthday problem, and the probability is 1 - P(365, N)/(365)**N (where P(n,k) is the number of k-length permutations formed from n elements). For larger values of k, this Wolfram MathWorld article may prove useful.

Rules

Output must be deterministic, and as accurate as possible for your chosen language. This means no Monte Carlo estimation or Poisson approximation.

N and k will be no larger than the largest representable integer in your chosen language. If your chosen language has no hard maximum on integers (aside from memory constraints), then N and k may be arbitrarily large.

Accuracy errors stemming from floating-point inaccuracies may be ignored - your solution should assume perfectly-accurate, infinite-precision floats.

Test Cases

Format: k, N -> exact fraction (float approximation)

```<code>2, 4 -> 795341/48627125 (0.016355912466550306)
2, 10 -> 2689423743942044098153/22996713557917153515625 (0.11694817771107766)
2, 23 -> 38093904702297390785243708291056390518886454060947061/75091883268515350125426207425223147563269805908203125 (0.5072972343239854)
3, 3 -> 1/133225 (7.5060987051979735e-06)
3, 15 -> 99202120236895898424238531990273/29796146005797507000413918212890625 (0.0033293607910766013)
3, 23 -> 4770369978858741874704938828021312421544898229270601/375459416342576750627131037126115737816349029541015625 (0.01270542106874784)
3, 88 -> 121972658600365952270507870814168157581992420315979376776734831989281511796047744560525362056937843069780281314799508374037334481686749665057776557164805212647907376598926392555810192414444095707428833039241/238663638085694198987526661236008945231785263891283516149752738222327030518604865144748956653519802030443538582564040039437134064787503711547079611163210009542953054552383296282869196147657930850982666015625 (0.5110651106247305)
4, 5 -> 1821/17748900625 (1.0259790386313012e-07)
4, 25 -> 2485259613640935164402771922618780423376797142403469821/10004116148447957520459906484225353834116619892120361328125 (0.0002484237064787077)
5, 50 -> 786993779912104445948839077141385547220875807924661029087862889286553262259306606691973696493529913926889614561937/7306010813549515310358093277059651246342214174497508156711617142094873581852472030624097938198246993124485015869140625 (0.00010771867165219201)
10, 11 -> 801/8393800448639761033203125 (9.542757239717371e-23)
10, 20 -> 7563066516919731020375145315161/4825745614492126958810682272575693836212158203125 (1.5672327389589693e-18)
10, 100 -> 122483733913713880468912433840827432571103991156207938550769934255186675421169322116627610793923974214844245486313555179552213623490113886544747626665059355613885669915058701717890707367972476863138223808168550175885417452745887418265215709/1018100624231385241853189999481940942382873878399046008966742039665259133127558338726075853312698838815389196105495212915667272376736512436519973194623721779480597820765897548554160854805712082157001360774761962446621765820964355953037738800048828125 (1.2030611807765361e-10)
10, 200 -> 46037609834855282194444796809612644889409465037669687935667461523743071657580101605348193810323944369492022110911489191609021322290505098856358912879677731966113966723477854912238177976801306968267513131490721538703324306724303400725590188016199359187262098021797557231190080930654308244474302621083905460764730976861073112110503993354926967673128790398832479866320227003479651999296010679699346931041199162583292649095888379961533947862695990956213767291953359129132526574405705744727693754517/378333041587022747413582050553902956219347236460887942751654696440740074897712544982385679244606727641966213694207954095750881417642309033313110718881314425431789802709136766451022222829015561216923212248085160525409958950556460005591372098706995468877542448525403291516015085653857006548005361106043070914396018461580475651719152455730181412523297836008507156692430467118523245584181582255037664477857149762078637248959905010608686740872875726844702607085395469621591502118462813086807727813720703125 (1.21685406174776e-07)
</code>```

答:
J, <s>41</s> 36 bytes

```<code>(+/%#)@(<:365&(#~>./@(#/.~)@#:i.@^))
</code>```

Straight-forward approach similar to the others. Runs into memory issues at n > 3.

Usage

Takes the value of k on the LHS and n on the RHS.

```<code>   f =: (+/%#)@(<:365&(#~>./@(#/.~)@#:i.@^))
   0 f 0
0
   0 f 1
1
   1 f 1
1
   0 f 2
1
   1 f 2
1
   2 f 2
0.00273973
   0 f 3
1
   1 f 3
1
   2 f 3
0.00820417
   3 f 3
7.5061e_6
</code>```

On my pc, using an i7-4770k and the timer foreign 6!:2, computing for n = 3 requires about 25 seconds.

```<code>   timer =: 6!:2
   timer '2 f 3'
24.7893
   timer '3 f 3'
24.896
</code>```

Explanation

```<code>(+/%#)@(<:365&(#~>./@(#/.~)@#:i.@^)) Input: k on LHS, n on RHS
          365&                       The number 365
               #~                    Create n copies of 365
                                 ^   Calculate 365^n
                              i.@    The range [0, 1, ..., 365^n-1]
                            #:       Convert each value in the range to base-n and pad
                                     with zeroes to the right so that each has n digits
                     (#/.~)@         Find the size of each set of identical values
                 >./@                Find the max size of each
        <:                           Test each if greater than or equal to k
(+/%#)@                              Apply to the previous result
 +/                                  Find the sum of the values
    #                                Count the number of values
   %                                 Divide the sum by the count and return
</code>```

Title: Generalized Birthday Problem

Body:
J, <s>41</s> 36 bytes

(+/%#)@(<:365&(#~>./@(#/.~)@#:i.@^))

Straight-forward approach similar to the others. Runs into memory issues at n > 3.

Usage

Takes the value of k on the LHS and n on the RHS.

   f =: (+/%#)@(<:365&(#~>./@(#/.~)@#:i.@^))
   0 f 0
0
   0 f 1
1
   1 f 1
1
   0 f 2
1
   1 f 2
1
   2 f 2
0.00273973
   0 f 3
1
   1 f 3
1
   2 f 3
0.00820417
   3 f 3
7.5061e_6

On my pc, using an i7-4770k and the timer foreign 6!:2, computing for n = 3 requires about 25 seconds.

   timer =: 6!:2
   timer '2 f 3'
24.7893
   timer '3 f 3'
24.896

Explanation

(+/%#)@(<:365&(#~>./@(#/.~)@#:i.@^)) Input: k on LHS, n on RHS
          365&                       The number 365
               #~                    Create n copies of 365
                                 ^   Calculate 365^n
                              i.@    The range [0, 1, ..., 365^n-1]
                            #:       Convert each value in the range to base-n and pad
                                     with zeroes to the right so that each has n digits
                     (#/.~)@         Find the size of each set of identical values
                 >./@                Find the max size of each
        <:                           Test each if greater than or equal to k
(+/%#)@                              Apply to the previous result
 +/                                  Find the sum of the values
    #                                Count the number of values
   %                                 Divide the sum by the count and return


答:
Python, 36 bytes

Python 2:

f=lambda n,i=1:n/i and 1.+f(n,i+1)/i
```
<p><strong>Python 3:</strong></p>
<pre class="lang-python prettyprint-override"><code>f=lambda n,i=1:i<=n and 1+f(n,i+1)/i
</code>```

Title: Approximation of e

Body:
We all know that the Euler's number, denoted by \$e\$, to the power of some variable \$x\$, can be approximated by using the Maclaurin Series expansion:

$$e^x=\sum_{k=0}^{\infty}{\frac{x^k}{k!}}=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\dots$$

By letting \$x\$ equal \$1\$, we obtain

$$\sum_{k=0}^{\infty}{\frac{1}{k!}{=\frac{1}{0!}+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\dots\\=1+1+\frac{1}{2}+\frac{1}{6}+\frac{1}{24}+\dots}}$$

Challenge

Write a program in any language which approximates Euler's number by taking in an input \$n\$ and calculates the series to the \$n\$th term. Note that the first term has denominator \$0!\$, not \$1!\$, i.e. \$n=1\$ corresponds to \$\frac{1}{0!}\$.

Scoring

Program with least amount of bytes wins.

Body:
Python, 36 bytes

Python 2:

f=lambda n,i=1:n/i and 1.+f(n,i+1)/i

Python 3:

f=lambda n,i=1:i<=n and 1+f(n,i+1)/i


答:
k (13 bytes)

Subject to overflows for N>20

```<code>{+/%*\1,1+!x}
</code>```

Title: Approximation of e

Body:
k (13 bytes)

Subject to overflows for N>20

{+/%*\1,1+!x}


答:
R, 26 bytes

```<code>sum(diag(A*A[,ncol(A):1]))
</code>```

Title: Dot Product of Diagonals

Body:
This challenge is very simple. You are given as input a square matrix, represented in any sane way, and you have to output the dot product of the diagonals of the matrix.

The diagonals in specific are the diagonal running from top-left to bottom-right and from top-right to bottom-left.

Test Cases

```<code>[[-1, 1], [-2, 1]]  ->  -3
[[824, -65], [-814, -741]]  ->  549614
[[-1, -8, 4], [4, 0, -5], [-3, 5, 2]]  ->  -10
[[0, -1, 0], [1, 0, 2], [1, 0, 1]]  ->  1
</code>```

Body:
R, 26 bytes

sum(diag(A*A[,ncol(A):1]))


问:
Super speedy totient function
The goal is simple: calculate the totient function for as many numbers as you can in 10 seconds and sum the numbers.

You must print your result at the end and you must actually calculate it. No automated totient function is allowed, but bignum libraries are. You have to start at 1 and count up all the integers consecutively. You are not allowed to skip numbers.

Your score is how many numbers your program can calculate on your machine / how many my program can calculate on your machine. My code is a simple program in C++ (optimizations off), hopefully you can run it.

Important properties you could use!

if gcd(m,n) = 1, phi(mn) = phi(m) * phi(n)

if p is prime, phi(p) = p - 1 (for p < 10^20)

if n is even, phi(2n) = 2 phi(n)

others listed in first link

My code

#include <iostream>
using namespace std;

int gcd(int a, int b)
{
    while (b != 0)
    {
        int c = a % b;
        a = b;
        b = c;
    }
    return a;
}

int phi(int n)
{
    int x = 0;
    for (int i=1; i<=n; i++)
    {
        if (gcd(n, i) == 1)
            x++;
    }
    return x;
}

int main()
{
    unsigned int sum = 0;
    for (int i=1; i<19000; i++) // Change this so it runs in 10 seconds
    {
        sum += phi(i);
    }
        cout << sum << endl;
        return 0;
}
```

答:
C#: 49,000 (980,000,000 / 20,000)

https://codegolf.stackexchange.com/a/26800 "Howard's code".

But modified, phi values are computed for odd integers.

using System;
using sw = System.Diagnostics.Stopwatch;
class Program
{
    static void Main()
    {
        sw sw = sw.StartNew();
        Console.Write(sumPhi(980000000) + " " + sw.Elapsed);
        sw.Stop(); Console.Read();
    }

    static long sumPhi(int n)  // sum phi[i] , 1 <= i <= n
    {
        long s = 0; int[] phi;
        if (n < 1) return 0; phi = buildPhi(n + 1);
        for (int i = 1; i <= n; i++) s += getPhi(i, phi);
        return s;
    }

    static int getPhi(int i, int[] phi)
    {
        if ((i & 1) > 0) return phi[i >> 1];
        if ((i & 3) > 0) return phi[i >> 2];
        int z = ntz(i); return phi[i >> z >> 1] << z - 1;
    }

    static int[] buildPhi(int n)  // phi[i >> 1] , i odd , i < n
    {
        int i, j, y, x, q, r, f; int[] phi;
        if (n < 2) return new int[] { 0 };
        phi = new int[n / 2]; phi[0] = 1;
        for (j = 2, i = 3; i < n; i *= 3, j *= 3) phi[i >> 1] = j;
        for (x = 4, i = 5; i <= n >> 1; i += x ^= 6)
        {
            if (phi[i >> 1] > 0) continue; phi[i >> 1] = i ^ 1;
            for (j = 3, y = 3 * i; y < n; y += i << 1, j += 2)
            {
                if (phi[j >> 1] == 0) continue; q = j; f = i ^ 1;
                while ((r = q) == i * (q /= i)) f *= i;
                phi[y >> 1] = f * phi[r >> 1];
            }
        }
        for (; i < n; i += x ^= 6)  // primes > n / 2
            if (phi[i >> 1] == 0)
                phi[i >> 1] = i ^ 1;
        return phi;
    }

    static int ntz(int i)  // number of trailing zeros
    {
        int z = 1;
        if ((i & 0xffff) == 0) { z += 16; i >>= 16; }
        if ((i & 0x00ff) == 0) { z += 08; i >>= 08; }
        if ((i & 0x000f) == 0) { z += 04; i >>= 04; }
        if ((i & 0x0003) == 0) { z += 02; i >>= 02; }
        return z - (i & 1);
    }
}
```

<p>New score: <strong>61,000</strong> (1,220,000,000 / 20,000)<br>
In "App.config" I had to add "gcAllowVeryLargeObjects enabled=true".</p>

<pre class="lang-cs prettyprint-override"><code>    static long sumPhi(int n)
    {
        int i1, i2, i3, i4, z; long s1, s2, s3, s4; int[] phi;
        if (n < 1) return 0; phi = buildPhi(n + 1); n -= 4; z = 2;
        i1 = 1; i2 = 2; i3 = 3; i4 = 4; s1 = s2 = s3 = s4 = 0;
        if (n > 0)
            for (; ; )
            {
                s1 += phi[i1 >> 1];
                s2 += phi[i2 >> 2];
                s3 += phi[i3 >> 1];
                s4 += phi[i4 >> z >> 1] << z - 1;
                i1 += 4; i2 += 4; i3 += 4; i4 += 4;
                n -= 4; if (n < 0) break;
                if (z == 2)
                {
                    z = 3; i4 >>= 3;
                    while ((i4 & 3) == 0) { i4 >>= 2; z += 2; }
                    z += i4 & 1 ^ 1;
                    i4 = i3 + 1;
                }
                else z = 2;
            }
        if (n > -4) s1 += phi[i1 >> 1];
        if (n > -3) s2 += phi[i2 >> 2];
        if (n > -2) s3 += phi[i3 >> 1];
        if (n > -1) s4 += phi[i4 >> z >> 1] << z - 1;
        return s1 + s2 + s3 + s4;
    }

    static int[] buildPhi(int n)
    {
        int i, j, y, x, q0, q1, f; int[] phi;
        if (n < 2) return new int[] { 0 };
        phi = new int[n / 2]; phi[0] = 1;
        for (uint u = 2, v = 3; v < n; v *= 3, u *= 3) phi[v >> 1] = (int)u;
        for (x = 4, i = 5; i <= n >> 1; i += x ^= 6)
        {
            if (phi[i >> 1] > 0) continue; phi[i >> 1] = i ^ 1;
            for (j = 3, y = 3 * i; y < n; y += i << 1, j += 2)
            {
                if (phi[j >> 1] == 0) continue; q0 = j; f = i ^ 1;
                while ((q1 = q0) == i * (q0 /= i)) f *= i;
                phi[y >> 1] = f * phi[q1 >> 1];
            }
        }
        for (; i < n; i += x ^= 6)
            if (phi[i >> 1] == 0)
                phi[i >> 1] = i ^ 1;
        return phi;
    }
</code>```

Title: Super speedy totient function

Body:
C#: 49,000 (980,000,000 / 20,000)

https://codegolf.stackexchange.com/a/26800 "Howard's code".

But modified, phi values are computed for odd integers.

using System;
using sw = System.Diagnostics.Stopwatch;
class Program
{
    static void Main()
    {
        sw sw = sw.StartNew();
        Console.Write(sumPhi(980000000) + " " + sw.Elapsed);
        sw.Stop(); Console.Read();
    }

    static long sumPhi(int n)  // sum phi[i] , 1 <= i <= n
    {
        long s = 0; int[] phi;
        if (n < 1) return 0; phi = buildPhi(n + 1);
        for (int i = 1; i <= n; i++) s += getPhi(i, phi);
        return s;
    }

    static int getPhi(int i, int[] phi)
    {
        if ((i & 1) > 0) return phi[i >> 1];
        if ((i & 3) > 0) return phi[i >> 2];
        int z = ntz(i); return phi[i >> z >> 1] << z - 1;
    }

    static int[] buildPhi(int n)  // phi[i >> 1] , i odd , i < n
    {
        int i, j, y, x, q, r, f; int[] phi;
        if (n < 2) return new int[] { 0 };
        phi = new int[n / 2]; phi[0] = 1;
        for (j = 2, i = 3; i < n; i *= 3, j *= 3) phi[i >> 1] = j;
        for (x = 4, i = 5; i <= n >> 1; i += x ^= 6)
        {
            if (phi[i >> 1] > 0) continue; phi[i >> 1] = i ^ 1;
            for (j = 3, y = 3 * i; y < n; y += i << 1, j += 2)
            {
                if (phi[j >> 1] == 0) continue; q = j; f = i ^ 1;
                while ((r = q) == i * (q /= i)) f *= i;
                phi[y >> 1] = f * phi[r >> 1];
            }
        }
        for (; i < n; i += x ^= 6)  // primes > n / 2
            if (phi[i >> 1] == 0)
                phi[i >> 1] = i ^ 1;
        return phi;
    }

    static int ntz(int i)  // number of trailing zeros
    {
        int z = 1;
        if ((i & 0xffff) == 0) { z += 16; i >>= 16; }
        if ((i & 0x00ff) == 0) { z += 08; i >>= 08; }
        if ((i & 0x000f) == 0) { z += 04; i >>= 04; }
        if ((i & 0x0003) == 0) { z += 02; i >>= 02; }
        return z - (i & 1);
    }
}

New score: 61,000 (1,220,000,000 / 20,000)

In "App.config" I had to add "gcAllowVeryLargeObjects enabled=true".

    static long sumPhi(int n)
    {
        int i1, i2, i3, i4, z; long s1, s2, s3, s4; int[] phi;
        if (n < 1) return 0; phi = buildPhi(n + 1); n -= 4; z = 2;
        i1 = 1; i2 = 2; i3 = 3; i4 = 4; s1 = s2 = s3 = s4 = 0;
        if (n > 0)
            for (; ; )
            {
                s1 += phi[i1 >> 1];
                s2 += phi[i2 >> 2];
                s3 += phi[i3 >> 1];
                s4 += phi[i4 >> z >> 1] << z - 1;
                i1 += 4; i2 += 4; i3 += 4; i4 += 4;
                n -= 4; if (n < 0) break;
                if (z == 2)
                {
                    z = 3; i4 >>= 3;
                    while ((i4 & 3) == 0) { i4 >>= 2; z += 2; }
                    z += i4 & 1 ^ 1;
                    i4 = i3 + 1;
                }
                else z = 2;
            }
        if (n > -4) s1 += phi[i1 >> 1];
        if (n > -3) s2 += phi[i2 >> 2];
        if (n > -2) s3 += phi[i3 >> 1];
        if (n > -1) s4 += phi[i4 >> z >> 1] << z - 1;
        return s1 + s2 + s3 + s4;
    }

    static int[] buildPhi(int n)
    {
        int i, j, y, x, q0, q1, f; int[] phi;
        if (n < 2) return new int[] { 0 };
        phi = new int[n / 2]; phi[0] = 1;
        for (uint u = 2, v = 3; v < n; v *= 3, u *= 3) phi[v >> 1] = (int)u;
        for (x = 4, i = 5; i <= n >> 1; i += x ^= 6)
        {
            if (phi[i >> 1] > 0) continue; phi[i >> 1] = i ^ 1;
            for (j = 3, y = 3 * i; y < n; y += i << 1, j += 2)
            {
                if (phi[j >> 1] == 0) continue; q0 = j; f = i ^ 1;
                while ((q1 = q0) == i * (q0 /= i)) f *= i;
                phi[y >> 1] = f * phi[q1 >> 1];
            }
        }
        for (; i < n; i += x ^= 6)
            if (phi[i >> 1] == 0)
                phi[i >> 1] = i ^ 1;
        return phi;
    }


答:
Mathematica, 17 bytes

```<code>Tr[#~Reverse~2#]&
</code>```

Title: Dot Product of Diagonals

Body:
Mathematica, 17 bytes

Tr[#~Reverse~2#]&


答:
Perl 6, <s> 70 </s> 27 bytes

If it needed to work in a different working directory you would need something like this:

$_=$*PROGRAM;.rename: .basename.flip.IO.absolute: .absolute.IO.dirname
```

<p>Since the working directory will be the same directory as the program it can be simplified to just:</p>

<pre class="lang-perl6 prettyprint-override"><code>$_=$*PROGRAM;.rename: .flip
</code>```

Explanation:

$_ = $*PROGRAM;  # IO::Path object

$_.rename:
    $_.basename
      .flip      # reverse characters
      .IO        # turn into an IO object (IO::Path)
      .absolute: # turn it into an absolute path Str in the following dir
        $_.absolute.IO.dirname
```

Body:
In a single file, write a program that requires no input and produces no output. When run it should reverse the name of the file it is contained in, regardless of what the name is, without altering the code or producing other lasting side effects.

Any way of achieving this is fine. It only matters that once the program is run the only lasting change is that its file name has been reversed. e.g. no new files should be in the directory.

Running the program again should reverse the name back. Indeed, the program should be able to be run arbitrarily many times.

For the purposes of this challenge:

You may assume filenames are always strings of lowercase letters (a-z) between 1 and 127 characters long. (If your language requires files to have extensions to run then just reverse the part before the extension, e.g. mycode.bat → edocym.bat.)

You may assume the code file is in a directory by itself so it will not have naming conflicts (except with itself).

You may not assume the filename is not a palindrome, i.e. the same when reversed. Filenames that are palindromes should work just as well as those that aren't.

You may read your file's contents or metadata. There are no quine restrictions here.

You may assume your program will be run on a particular, modern, commonplace operating system (e.g. Windows/Linux), since not all shells have the same command set.

As a concrete example, say you have a Python program in a file called
  mycode in its own directory. Running

```<code>python mycode
</code>```

in the terminal should result in the filename being reversed to
  edocym. The file edocym should be alone in its directory - no file
  named mycode should exist anymore. Running

```<code>python edocym
</code>```

will reverse the name back to mycode, at which point the process can
  be repeated indefinitely.

If the same Python file was renamed racecar (without changing the code) and then run

```<code>python racecar
</code>```

nothing should visibly change since "racecar" is a palindrome.
  That same goes if the filename were, say, a or xx.

The shortest code in bytes wins. Tiebreaker is higher voted answer.

Body:
Perl 6, <s> 70 </s> 27 bytes

If it needed to work in a different working directory you would need something like this:

$_=$*PROGRAM;.rename: .basename.flip.IO.absolute: .absolute.IO.dirname

Since the working directory will be the same directory as the program it can be simplified to just:

$_=$*PROGRAM;.rename: .flip

Explanation:

$_ = $*PROGRAM;  # IO::Path object

$_.rename:
    $_.basename
      .flip      # reverse characters
      .IO        # turn into an IO object (IO::Path)
      .absolute: # turn it into an absolute path Str in the following dir
        $_.absolute.IO.dirname


答:
JavaScript (Node.js + Unirest), 123 bytes

```<code>require("unirest").get("http://api.stackexchange.com/posts/82683?site=codegolf").end(x=>console.log(x.body.items[0].score))
</code>```

I like this library, because it automatically parses JSON.

Title: Stack Exchange Vote Counter

Body:
Write a program/function that returns the vote count of its own Stack Exchange answer at the time of its execution.

Your program/function may access this page (codegolf.stackexchange.com/questions/82609) off the internet, however:

Your program/function may not accept any user input and

The use of URL shorteners is not allowed

Your program/function may use only its own source as a reference point to its vote count (for example: no referencing strings of text in its contained answer but not in its own source)

Your program/function must output its own vote count and only its own vote count (for example: no returning all vote counts on this page)

This is code-golf, shortest code wins.

Body:
JavaScript (Node.js + Unirest), 123 bytes

require("unirest").get("http://api.stackexchange.com/posts/82683?site=codegolf").end(x=>console.log(x.body.items[0].score))

I like this library, because it automatically parses JSON.


问:
Cat goes "Meow"

cat goes  "Meow"

We are all familiar with the concept of a cat program. The user types something in, it is echoed back to the user. Easy. But all cat programs I've seen so far have missed one fact: a cat goes "Meow". So your task is to write a program that copies all STDIN to STDOUT UNLESS the input is cat, in which case your program should output cat goes "Meow".

Scoring

This is code-golf, so your score is your byte count, with a few modifiers:

If your program works for any additional animals other than cat (e.g. cow: cow goes "Moo"), for each additional animal: -10

If your program doesn't use the word "cat": -15

If your program responds to fox with "What does the fox say": -25

Animals and sounds that go together:

cow goes moo
duck goes quack
sheep goes baa
bees go buzz
frogs go croak

Anything else on this list is allowed.

Rules

Standard loopholes apply

You must not write anything to STDERR

You can use single quotes/no quotes instead of double quotes.

Leaderboard

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Pyke, 391 -595 = -204 bytes

-58*10 extra animals, -15 for no "cat" string

```<code>"goes"Q.dt偮晪ꅢὐὥ墵셞᳙ᄷ쟿䁔漲ᬰ䵙ꄨ塋튖თ᠞鮔૪爟㍅爟⼱]꣟勒〥鴞᫠⬻䋥ュ⣹邦㺓堚퀦잓號漲ქ䦙ᔯ漲ᠥ쏔っ鮔牔鶇Ƒ䂝雥⬻⯎偮燩巺䯥봽鮔튖➒゗ᨼ䄇嚕㮷鮏ᘽ挳ᖘ漲睴윿꒲⬻鼤㨂ᘽdc2cY@]3J
</code>```

Try it here!

Uses dictionary-based compression to store the words. Pyke is older than the question.

Animals it knows:

```<code>{'seals': 'bark', 'turkeys': 'gobble', 'mosquitos': 'whine', 'curlews': 'pipe', 'dogs': 'howl', 'sheep': 'bleat', 'elephants': 'trumpet', 'eagles': 'scream', 'raccoons': 'trill', 'goats': 'bleat', 'donkeys': 'bray', 'monkey': 'whoop', 'snakes': 'hiss', 'wolves': 'howl', 'grasshoppers': 'chirp', 'ferrets': 'dook', 'geese': 'honk', 'ducks': 'quack', 'chinchillas': 'squeak', 'oxen': 'low', 'pigs': 'snort', 'lions': 'snarl', 'antelopes': 'snort', 'crows': 'caw', 'hamsters': 'squeak', 'ravens': 'croak', 'leopards': 'snarl', 'tapirs': 'squeak', 'lambs': 'bleat', 'horses': 'neigh', 'jaguars': 'snarl', 'crickets': 'chirp', 'moose': 'bellow', 'cattle': 'moo', 'deer': 'bellow', 'rooks': 'caw', 'dolphins': 'click', 'whales': 'sing', 'owls': 'hoot', 'walruses': 'groan', 'cicadas': 'chirp', 'tigers': 'snarl', 'chickens': 'cluck', 'giraffes': 'bleat', 'mice': 'squeak', 'peacocks': 'scream', 'songbirds': 'sing', 'geckos': 'croak', 'frogs': 'croak', 'pigeons': 'coo', 'swans': 'cry', 'bitterns': 'boom', 'rhinoceros': 'bellow', 'cats': 'purr', 'badgers': 'growl', 'magpies': 'chatter', 'vultures': 'scream', 'elk': 'bleat'}
</code>```

Title: Cat goes "Meow"

Body:
Pyke, 391 -595 = -204 bytes

-58*10 extra animals, -15 for no "cat" string

"goes"Q.dt偮晪ꅢὐὥ墵셞᳙ᄷ쟿䁔漲ᬰ䵙ꄨ塋튖თ᠞鮔૪爟㍅爟⼱]꣟勒〥鴞᫠⬻䋥ュ⣹邦㺓堚퀦잓號漲ქ䦙ᔯ漲ᠥ쏔っ鮔牔鶇Ƒ䂝雥⬻⯎偮燩巺䯥봽鮔튖➒゗ᨼ䄇嚕㮷鮏ᘽ挳ᖘ漲睴윿꒲⬻鼤㨂ᘽdc2cY@]3J

<a href="http://pyke.catbus.co.uk/?code=%22goes%22Q.dt%F0%9B%A7%B7%E5%81%AE%E6%99%AA%EA%85%A2%E1%BD%90%F0%91%88%B6%E1%BD%A5%F0%91%88%B6%E5%A2%B5%F0%91%88%B6%EC%85%9E%F0%91%88%B6%F0%B8%A3%8C%E1%B3%99%E1%84%B7%EC%9F%BF%E4%81%94%F0%94%A3%A9%F0%95%95%84%E6%BC%B2%F0%94%B5%B8%EE%AF%87%E1%AC%B0%E4%B5%99%EA%84%A8%EE%AF%87%E5%A1%8B%ED%8A%96%F0%B4%8F%B5%E1%83%97%E1%A0%9E%E9%AE%94%E0%AB%AA%E7%88%9F%E3%8D%85%E7%88%9F%E2%BC%B1%5D%EA%A3%9F%E5%8B%92%E3%80%A5%E9%B4%9E%E1%AB%A0%E2%AC%BB%E4%8B%A5%E3%83%A5%E2%A3%B9%F0%93%AB%8C%E9%82%A6%F0%B4%BD%A9%E3%BA%93%F0%92%80%BD%EE%91%8E%F0%93%AB%8C%E5%A0%9A%ED%80%A6%EC%9E%93%EE%AF%87%E8%99%9F%E6%BC%B2%E1%83%A5%EF%B8%86%F0%90%8A%B7%E4%A6%99%E1%94%AF%E6%BC%B2%E1%A0%A5%EC%8F%94%E3%81%A3%E9%AE%94%F0%90%A9%81%E7%89%94%E9%B6%87%C6%91%E4%82%9D%E9%9B%A5%F0%90%BB%B3%E2%AC%BB%E2%AF%8E%E5%81%AE%E7%87%A9%E5%B7%BA%EE%A9%9B%F0%91%B3%A6%E4%AF%A5%F0%92%80%BD%EB%B4%BD%E9%AE%94%EE%BF%A0%ED%8A%96%E2%9E%92%E3%82%97%E1%A8%BC%F0%93%AB%8C%E4%84%87%F0%93%AB%8C%E5%9A%95%F0%93%AB%8C%E3%AE%B7%E9%AE%8F%F0%90%93%A7%E1%98%BD%E6%8C%B3%E1%96%98%F0%AF%83%AE%E6%BC%B2%F0%91%99%8C%F0%92%80%BD%E7%9D%B4%EC%9C%BF%EA%92%B2%E2%AC%BB%F0%A6%BC%8E%E9%BC%A4%E3%A8%82%E1%98%BDdc2cY%40%5D3J&input=hamsters" rel="nofollow noreferrer">Try it here!

Uses dictionary-based compression to store the words. Pyke is older than the question.

Animals it knows:

{'seals': 'bark', 'turkeys': 'gobble', 'mosquitos': 'whine', 'curlews': 'pipe', 'dogs': 'howl', 'sheep': 'bleat', 'elephants': 'trumpet', 'eagles': 'scream', 'raccoons': 'trill', 'goats': 'bleat', 'donkeys': 'bray', 'monkey': 'whoop', 'snakes': 'hiss', 'wolves': 'howl', 'grasshoppers': 'chirp', 'ferrets': 'dook', 'geese': 'honk', 'ducks': 'quack', 'chinchillas': 'squeak', 'oxen': 'low', 'pigs': 'snort', 'lions': 'snarl', 'antelopes': 'snort', 'crows': 'caw', 'hamsters': 'squeak', 'ravens': 'croak', 'leopards': 'snarl', 'tapirs': 'squeak', 'lambs': 'bleat', 'horses': 'neigh', 'jaguars': 'snarl', 'crickets': 'chirp', 'moose': 'bellow', 'cattle': 'moo', 'deer': 'bellow', 'rooks': 'caw', 'dolphins': 'click', 'whales': 'sing', 'owls': 'hoot', 'walruses': 'groan', 'cicadas': 'chirp', 'tigers': 'snarl', 'chickens': 'cluck', 'giraffes': 'bleat', 'mice': 'squeak', 'peacocks': 'scream', 'songbirds': 'sing', 'geckos': 'croak', 'frogs': 'croak', 'pigeons': 'coo', 'swans': 'cry', 'bitterns': 'boom', 'rhinoceros': 'bellow', 'cats': 'purr', 'badgers': 'growl', 'magpies': 'chatter', 'vultures': 'scream', 'elk': 'bleat'}


答:
MATL, 6 bytes

```<code>q_t1Zh
</code>```

This computes the sum using the hypergeometric function 1F1(a;b;z):

Works on Octave and on the online compiler, but not on Matlab, due to a difference in how the hypergeometric function is defined (which will be corrected).

Try it online!

Explanation

```<code>q_    % Take N implicitly. Compute -N+1
t     % Duplicate
1     % Push 1
Zh    % Hypergeometric function 1F1(-N+1;-N+1;1). Implicitly display
</code>```

Title: Approximation of e

Body:
MATL, 6 bytes

q_t1Zh

This computes the sum using the hypergeometric function 1F1(a;b;z):

Works on Octave and on the online compiler, but not on Matlab, due to a difference in how the hypergeometric function is defined (which will be corrected).

Try it online!

Explanation

q_    % Take N implicitly. Compute -N+1
t     % Duplicate
1     % Push 1
Zh    % Hypergeometric function 1F1(-N+1;-N+1;1). Implicitly display


Title: Approximation of e

Body:
05AB1E, 6 bytes

$L<!/O

Explained

$           # push 1 and input: N = 5
 L<         # range [0..N-1]: [0,1,2,3,4]
   !        # factorial over range [1,1,2,6,24]
    /       # divide 1/range: [1.0, 1.0, 0.5, 0.16666666666666666, 0.041666666666666664]
     O      # sum: 2.708333333333333

Try it online


答:
05AB1E, <s>18</s> <s>17</s> 15 bytes

Code:

```<code>|…-_-123:)ø€J€ï
</code>```

Explanation:

```<code>|                  # Take all input as a list of strings.
 …-_-              # 3-char string, which results into "-_-".
     123:)         # Replace "-_-" with 123.
          ø        # Zip, resulting into the columns of the 2D array.
           €J      # Join each of them.
             €ï    # For each, convert to integer. If this is not possible, it will ignore
                     the result.
                   # Implicitly output the array.
</code>```

Uses the CP-1252 encoding. Try it online! (make sure to pad all lines with spaces to the same length..

Title: Is my emoji dry?

Body:
This is my pet emoji, Billy:

```<code>-_-
</code>```

Emojis don't like to be in the rain, so Billy is sad... Let's draw him an umbrella to make him feel better!

```<code>  /\
 /  \
/    \

  -_-
</code>```

This is good, he is entirely covered by his umbrella! Here is an example where only part of him is covered:

```<code>  /\
 /  \
/    \

     -_-
</code>```

In this case, sections 2 and 3 of his body are exposed to the rain.

Umbrellas come in many shapes and sizes, but they're always made up from a series of ascending slashes / followed by a series of descending backslashes \. For example, these are all valid umbrellas:

```<code>  /\
 /  \
/    \

/\

    /\
   /  \
  /    \
 /      \
/        \
</code>```

And these are not:

```<code>/   \

\/

  \
 / \
/   \

 0\
/  \

//\\
/  \
</code>```

You need to determine which parts of my emoji are exposed to the rain.

Clarifications

Your program (or function) will take a 2d string as input. This can be in whatever format is most convenient or natural to your language. An array of strings, an array of arrays of characters, a string with newlines in it etc.

You must output which sections of the emoji are exposed to the rain. This can be zero-indexed or one-indexed, as long as you make this clear. Output can be in any reasonable format. If the entire emoji is protected from the rain, output nothing (or an empty array).

You can assume that all inputs will have a valid umbrella, and the same emoji: -_-. The emoji will always be on the last line of the input, however their might be several empty lines between the umbrella and the emoji.

Everything that isn't part of the umbrella or the emoji will be a space   character or newline.

The input will be padded with spaces so that the length of each line is the same.

Standard loopholes apply, and the shortest answer in bytes wins!

Test IO:

All of the sample cases will use one-indexing.

```<code>  /\
 /  \
/    \

  -_-

Outputs: []

----------------

   /\
  /  \

     -_-

Outputs: [2, 3]

----------------

    /\
   -_-

Outputs: [1]

----------------

     /\
    /  \
   /    \
  /      \
 /        \
/          \

               -_-

Outputs: [1, 2, 3]
</code>```

Body:
05AB1E, <s>18</s> <s>17</s> 15 bytes

Code:

|…-_-123:)ø€J€ï

Explanation:

|                  # Take all input as a list of strings.
 …-_-              # 3-char string, which results into "-_-".
     123:)         # Replace "-_-" with 123.
          ø        # Zip, resulting into the columns of the 2D array.
           €J      # Join each of them.
             €ï    # For each, convert to integer. If this is not possible, it will ignore
                     the result.
                   # Implicitly output the array.

Uses the CP-1252 encoding. Try it online! (make sure to pad all lines with spaces to the same length..


问:
Return the integers with square digit-sums

Introduction and Credit

We all know and love our awesome rules to test whether a number is divisble by 11 or 3, which is just some clever sum over the digits of the number. Now this challenge takes this to a new level, by requiring you to compute the sum of the digits and then checking whether the result is a perfect integer square, neither of which operations usually can be done very short. As this property is also very hard to see when looking at a number, we want this to be done for entire lists of numbers so we can save human work. So this is your challenge now!

This was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitely).

Specification

Input

Your input is a list of non-negative integers, in any standard I/O format.

You may choose the list format as your language needs it

Output

The output is a list of integers, in any standard I/O format.

What to do?

Filter out every integer from the input list for which the sum of the digits is not a a square (of an integer).

The order of the elements may not be changed, e.g. if you get [1,5,9] you may not return [9,1]

Potential corner cases

0 is a non-negative integer and thus a valid input and 0 is also a valid integer root, e.g. 0 counts as an integer square.

The empty list is a valid input and output as well.

Who wins?

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

Standard rules apply of course.

Test Cases

```<code>[1,4,9,16,25,1111] -> [1,4,9,1111]
[1431,2,0,22,999999999] -> [1431,0,22,999999999]
[22228,4,113125,22345] -> [22228,4,22345]
[] -> []
[421337,99,123456789,1133557799] -> []
</code>```

Step-by-Step Example

```<code>Example input: [1337,4444]
Handling first number:
Sum of the digits of 1337: 1+3+3+7=14
14 is not an integer square, thus will be dropped!
Handling second number:
Sum of the digits of 4444: 4+4+4+4=16
16 is an integer square because 4*4=16, can get into the output list!
Example output: [4444]
</code>```

答:
C#, 103 bytes

```<code>int[] f(int[] a){return a.Where(n=>Math.Sqrt((n+"").Select(m=>int.Parse(m+"")).Sum())%1==0).ToArray();}
</code>```

Its really sad i have to turn chars and ints into strings all the time to work on them, i wish there was a better solution than adding an empty literal "" to cast into string.

any help on golfing this down appreciated

Body:
C#, 103 bytes

int[] f(int[] a){return a.Where(n=>Math.Sqrt((n+"").Select(m=>int.Parse(m+"")).Sum())%1==0).ToArray();}

Its really sad i have to turn chars and ints into strings all the time to work on them, i wish there was a better solution than adding an empty literal "" to cast into string.

any help on golfing this down appreciated


答:
MATLAB / Octave, 22 bytes

```<code>@(x)sum(1./gamma(1:x))
</code>```

Creates an anonymous function named ans that can be called using ans(N).

This solution computes gamma(x) for each element in the array [1 ... N] which is equal to factorial(x-1). We then take the inverse of each element and sum all elements.

Online Demo

Title: Approximation of e

Body:
MATLAB / Octave, 22 bytes

@(x)sum(1./gamma(1:x))

Creates an anonymous function named ans that can be called using ans(N).

This solution computes gamma(x) for each element in the array [1 ... N] which is equal to factorial(x-1). We then take the inverse of each element and sum all elements.

Online Demo


答:
Hoon, 78 bytes

```<code>|*
*
%+
skim
+<
|=
@ui
=(0 q:(sqt (roll (scan (slag 2 <+<>) (star dit)) add)))
</code>```

++skim only keeps the elements of the list that the function returns yes for. We cast all the atoms in the list to @ui in the sample, for the sole reason that Urbit's integers have mandatory group seperators: if you try to cast 1.000 to a string, it will return "1.000" instead of "1000". <@ui1.000>, however, gives "0i1000", so we cast and then cut off the first two letters of the string.

We then parse the string with the parser combinator (star dit), which is like the [0-9]* regex but also converts the character to an atom. We fold over the resulting list with add.

We call sqt on the number. In Hoon, the only data types are atoms or tuples, so it returns two atoms intead of a float: the nearest perfect square root, and the remainder. We can then just test if the remainder is 0.

Title: Return the integers with square digit-sums

Body:
Introduction and Credit

We all know and love our awesome rules to test whether a number is divisble by 11 or 3, which is just some clever sum over the digits of the number. Now this challenge takes this to a new level, by requiring you to compute the sum of the digits and then checking whether the result is a perfect integer square, neither of which operations usually can be done very short. As this property is also very hard to see when looking at a number, we want this to be done for entire lists of numbers so we can save human work. So this is your challenge now!

This was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitely).

Specification

Input

Your input is a list of non-negative integers, in any standard I/O format.

You may choose the list format as your language needs it

Output

The output is a list of integers, in any standard I/O format.

What to do?

Filter out every integer from the input list for which the sum of the digits is not a a square (of an integer).

The order of the elements may not be changed, e.g. if you get [1,5,9] you may not return [9,1]

Potential corner cases

0 is a non-negative integer and thus a valid input and 0 is also a valid integer root, e.g. 0 counts as an integer square.

The empty list is a valid input and output as well.

Who wins?

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

Standard rules apply of course.

Test Cases

```<code>[1,4,9,16,25,1111] -> [1,4,9,1111]
[1431,2,0,22,999999999] -> [1431,0,22,999999999]
[22228,4,113125,22345] -> [22228,4,22345]
[] -> []
[421337,99,123456789,1133557799] -> []
</code>```

Step-by-Step Example

```<code>Example input: [1337,4444]
Handling first number:
Sum of the digits of 1337: 1+3+3+7=14
14 is not an integer square, thus will be dropped!
Handling second number:
Sum of the digits of 4444: 4+4+4+4=16
16 is an integer square because 4*4=16, can get into the output list!
Example output: [4444]
</code>```

Body:
Hoon, 78 bytes

|*
*
%+
skim
+<
|=
@ui
=(0 q:(sqt (roll (scan (slag 2 <+<>) (star dit)) add)))

++skim only keeps the elements of the list that the function returns yes for. We cast all the atoms in the list to @ui in the sample, for the sole reason that Urbit's integers have mandatory group seperators: if you try to cast 1.000 to a string, it will return "1.000" instead of "1000". <@ui1.000>, however, gives "0i1000", so we cast and then cut off the first two letters of the string.

We then parse the string with the parser combinator (star dit), which is like the [0-9]* regex but also converts the character to an atom. We fold over the resulting list with add.

We call sqt on the number. In Hoon, the only data types are atoms or tuples, so it returns two atoms intead of a float: the nearest perfect square root, and the remainder. We can then just test if the remainder is 0.