问:
Rotate a hypercube

Introduction

A hypercube/tesseract is the 4 dimensional equivalent of a normal cube. It's made by taking a cube net, extending it to the 3rd dimension, then – using the 4th dimension – folding it into a hypercube. It's basically a cube, where each side is a cube.

To create a hypercube, you need 16 4d vectors (a vector with an x, a y, a z and a w component). These vectors are the following:

```<code>A(0, 0, 0, 0); B(1, 0, 0, 0); C(1, 0, 1, 0); D(0, 0, 1, 0); E(0, 1, 0, 0); F(1, 1, 0, 0); G(1, 1, 1, 0); H(0, 1, 1, 0);
I(0, 0, 0, 1); J(1, 0, 0, 1); K(1, 0, 1, 1); L(0, 0, 1, 1); M(0, 1, 0, 1); N(1, 1, 0, 1); O(1, 1, 1, 1); P(0, 1, 1, 1);
</code>```

The hypercube has 24 faces. The following list contains all of them (every group marks a quad):

```<code>ABFE, CDHG, BCGF, DAEH, DCBA, FEHG
IJNM, KLPO, JKON, LIMP, LKJI, PMNO
ABJI, DCKL, BCKJ, DAIL, FEMN, GHPO, FGON, EHPM, EAIM, BFNJ, CGOK, HDLP
</code>```

With all this information, you technically have a hypercube in code. To rotate this, you need 6 different matrices for each rotational plane, one for the YZ, XZ, XY, XW, YW and ZW planes. After you have every matrix, you need to multiply the cube's vertices with them.

The following images show the structure of each matrix:

For the rotation on the YZ plane:

For the rotation on the XZ plane:

For the rotation on the XY plane:

For the rotation on the XW plane:

For the rotation on the YW plane:

For the rotation on the ZW plane:

The rotations get applied in this order.

After all this, you have a rotated hypercube. Now you need to draw it. You should use an orthogonal projection combined with a perspective projection to send (x, y, z, w) to (2x/(2+z), 2y/(2+z)).

Input

Your input is 6 integers between 0 (inclusively) and 360 (exclusively). These represent the rotations in degrees on the different rotational planes of the hypercube.

Output

Your output should be a single image containing the hypercube. The display can be a rasterized image, a vector image or an ASCII art. The output image should be at least 100 * 100 pixels, and the cube needs to take up at least 50% of the screen. Any default image output format is allowed.

Test cases

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

```<code>0 0 0 0 0 30
</code>```

```<code>30 0 0 0 0 30
</code>```

```<code>0 0 0 30 30 30
</code>```

```<code>45 45 45 0 0 0
</code>```

```<code>45 45 45 45 45 45
</code>```

Open the images in a new tab, to see them in full size.

Rules

Default rules apply

Standard loopholes are forbidden

Shortest code in bytes wins

Title: Rotate a hypercube

Body:
Octave, <s>474</s> <s>433</s> 429 bytes

function H(a,b,c,d,e,f) C=@cosd;S=@sind;R=[1,0,0,0;0,C(e),0,-S(e);0,-S(e)*S(f),C(f),-C(e)*S(f);0,S(e)*C(f),S(f),C(e)*C(f)]*[C(c)*C(d),-S(c)*C(d),0,S(d);S(c),C(c),0,0;0,0,1,0;-C(c)*S(d),S(c)*S(d),0,C(d)]*[C(b),S(a)*S(b),C(a)*S(b),0;0,C(a),-S(a),0;-S(b),S(a)*C(b),C(a)*C(b),0;0,0,0,1]*(dec2bin(0:15)'-48.5);Z=R(3,:)+2;R=2*R./Z;Q=[1,2,10,12,11,9,10,14,16,12,4,8,16,15,11,3,7,15,13,9,1,5,13,14,6,8,7,5,6,2,4,3,1];plot(R(1,Q),R(2,Q));

Rotated:

function H(a,b,c,d,e,f)
C=@cosd;S=@sind;
R=[1,0,0,0;0,C(e),0,-S(e);0,-S(e)*S(f),C(f),-C(e)*S(f);0,S(e)*C(f),S(f),C(e)*C(f)]*
  [C(c)*C(d),-S(c)*C(d),0,S(d);S(c),C(c),0,0;0,0,1,0;-C(c)*S(d),S(c)*S(d),0,C(d)]*
  [C(b),S(a)*S(b),C(a)*S(b),0;0,C(a),-S(a),0;-S(b),S(a)*C(b),C(a)*C(b),0;0,0,0,1]*
  (dec2bin(0:15)'-48.5);
Z=R(3,:)+2;
R=2*R./Z;
Q=[1,2,10,12,11,9,10,14,16,12,4,8,16,15,11,3,7,15,13,9,1,5,13,14,6,8,7,5,6,2,4,3,1];
plot(R(1,Q),R(2,Q));

The rotation matrices still consume a lot of bytes, but the Eulerian cycle worked out quite well, reducing the number of vertices visited from <s>96</s> 120 down to 33.

Vertices are generated by taking the 4-bit binary representation of [0:15] and considering the msb to be the x-coordinate and the lsb the w-coordinate.

Edit: Pre-multiplying all of the rotation matrices was a nightmare, which is why I didn't use it initially, but pre-multiplying them in pairs saved 41 bytes. <s>Now to look for the optimum combination. :)</s> Multiplying the matrices by threes was worse than no pre-multiplication at all, so I'll be happy with the pair-wise approach.

Output:

H(0,0,0,0,0,0)

H(0,0,0,0,0,30)

H(30,0,0,0,0,30)

H(0,0,0,30,30,30)

H(45,45,45,0,0,0)

H(45,45,45,45,45,45)


问:
Alternating sign matrix verification
An alternating sign matrix is an n by n matrix consisting of the numbers -1, 0, 1, such that:

The sum of each row and column is 1

The nonzero entries in each row and column alternate in sign

These matrices generalise permutation matrices, and the number of such matrices for a given n was of interest for some time. They occur naturally during the Dodgson condensation method of computing matrix determinants (named after Charles Dodgson, better known as Lewis Carroll).

Here are some examples of 4 by 4 alternating sign matrices:

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

And here are some examples of 4 by 4 matrices which aren't alternating sign matrices:

```<code> 0  1  0  0
 0  0  0  1
 1  0  0  0
 0  0  1 -1    (last row and last column don't add to 1)

 0  0  0  1
 1  0  0  0
-1  1  1  0
 1  0  0  0    (third row does not alternate correctly)
</code>```

Your program or function will be given an n by n matrix (n >= 1) of -1s, 0s and 1s — output a truthy value if the given matrix is an alternating sign matrix, otherwise output a falsy value.

This is code-golf, so the goal is to minimise the number of bytes used.

Test cases

The following test cases are given in a Python-like 2D list format.

Truthy:

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

Falsy:

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

答:
Julia, 36 bytes

```<code>!x=[x^0 x^0;-x -x'][:]|>cumsum⊆0:1
</code>```

Try it online!

ContentLicense: CC BY-SA 3.0

Title: Alternating sign matrix verification


问:
Tips for golfing in dc
What general tips do you have for golfing in dc?

dc is a calculator utility for UNIX/Linux that predates the C language. I am interested in how to make my dc programs (calculations?) shorter. I'm looking for ideas that can be applied to general code-golf that are at least a little bit specific to dc (eg. removing comments is not a helpful answer)

Please post one tip per answer.

答:
Arrays

Although they're a headache for beginners, dc offers arrays. They work like this:

```<code>value index :a    # store `value' in array linked to top of stack `a', with index `index'
      index ;a    # push a[index] on (main) stack
</code>```

As usual, the first element has the index 0. Arrays can be useful when working with sequences, like in the SUDSI sequence, especially in combination with counters. Arrays can reduce the amount of number-shuffling you need to do (and the number of counters and comparisons) if you want to select a particular element without destroying your environment. For example, if you want to move a stackful of numbers into an array, you could write a recursive function that uses z (stack depth) or z 1- as the index, stores the element, and checks whether z == 0 to terminate itself.

```<code>[z 1- :a z 0 !=F]dsFx    # or I could just write such a function for you :)
</code>```

Be aware of the following:

Arrays are associated with instances on named stacks. If you push a new value on a stack that has an array associated with it, that array will also be "pushed back", and a "new" array will take its place. The old array won't be usable until the corresponding value on the named stack is also usable (i.e., on top of its stack). This is a complicated concept that would be better explained with a good animation, which is beyond me.

You can store stuff in a named array without actually pushing a value into the corresponding named register. However, if you do this, you cannot access the stack/register with that name for the rest of the session. dc will crash.

If you pop a value off a named stack, any values in the corresponding array will be lost—no warnings, no safeguards, nothing. Just gone (which can also be useful).

Title: Tips for golfing in dc

Body:
Arrays

Although they're a headache for beginners, dc offers arrays. They work like this:

value index :a    # store `value' in array linked to top of stack `a', with index `index'
      index ;a    # push a[index] on (main) stack

As usual, the first element has the index 0. Arrays can be useful when working with sequences, like in the SUDSI sequence, especially in combination with counters. Arrays can reduce the amount of number-shuffling you need to do (and the number of counters and comparisons) if you want to select a particular element without destroying your environment. For example, if you want to move a stackful of numbers into an array, you could write a recursive function that uses z (stack depth) or z 1- as the index, stores the element, and checks whether z == 0 to terminate itself.

[z 1- :a z 0 !=F]dsFx    # or I could just write such a function for you :)

Be aware of the following:

Arrays are associated with instances on named stacks. If you push a new value on a stack that has an array associated with it, that array will also be "pushed back", and a "new" array will take its place. The old array won't be usable until the corresponding value on the named stack is also usable (i.e., on top of its stack). This is a complicated concept that would be better explained with a good animation, which is beyond me.

You can store stuff in a named array without actually pushing a value into the corresponding named register. However, if you do this, you cannot access the stack/register with that name for the rest of the session. dc will crash.

If you pop a value off a named stack, any values in the corresponding array will be lost—no warnings, no safeguards, nothing. Just gone (which can also be useful).


问:
Traverse all numbers with only one bit flip per step
You can count 0, 1, 2, 3, 4.
But to get from 3 to 4 you have to change 3 bits at once.
Given a number of bits, how can you go through all numbers once,
but change at each step only 1! bit.

Here is an example for 3 bits:

```<code>000 100 110 010 011 111 101 001
</code>```

so the output is:

```<code>0 1 3 2 6 7 5 4
</code>```

Rules:

given a number of bits n, return a list of 2^n unique numbers

between to consecutive numbers only one bit is different

the shorter the code the better

答:
C++, 188 bytes

```<code>#include <cstdlib>
#include <iostream>
#define y if(b)f(b-1)
int x=0;
void f(int b){y;std::cout<<(x^=1<<b)<<' ';y;}
int main(int,char**v){int b=std::atoi(v[1]);std::cout<<x<<' ';y;}
</code>```

Specify the number of bits on the command line and it will print a list of space separated integers.

Body:
C++, 188 bytes

#include <cstdlib>
#include <iostream>
#define y if(b)f(b-1)
int x=0;
void f(int b){y;std::cout<<(x^=1<<b)<<' ';y;}
int main(int,char**v){int b=std::atoi(v[1]);std::cout<<x<<' ';y;}

Specify the number of bits on the command line and it will print a list of space separated integers.


问:
Derivative at the Edge
My preferred way to approximate a derivative is the central difference, its more accurate than forward difference or backward difference, and I'm too lazy to go higher-order. But the central difference requires a data point on either side of point you are evaluating. Normally this means you end up not having a derivative at either endpoint. To solve it, I want you to switch to forward and backward difference at the edges:

Specifically, I want you to use a forward difference for the first point, a backward difference for the last point, and a central difference for all the points in the middle. Also, you can assume x values are evenly spaced, and focus only on y. Use these formulas:

Good luck, I'm looking forward to seeing if someone comes up with a simple rule which reproduces all 3 derivatives in the right places!

EX INPUT:

```<code>0.034  9.62    8.885   3.477   2.38
</code>```

I will use FD, CD, and BD to denote which algorithm to use in which spot, so above 5 points are used to approximate derivatives using

```<code>FD     CD      CD      CD     BD
</code>```

And then the calculated values would be:

```<code>9.586  4.4255 -3.0715 -3.2525 -1.097
</code>```

You can assume that there will always be at least 3 input points, and you can calculate using single or double precision.

And as always, shortest answer wins.

答:
MATL, <s>21</s> 15 bytes

```<code>2/d1)6Mh8Mt0)h+
</code>```

TryItOnline

Halves the input vector, and takes successive differences, to give d=[i(2)-i(1) i(3)-i(2) ... i(end)-i(end-1)]/2 and then makes two modified vectors, [d(1) d] and [d d(end)], and adds them.

The older version was better (because convolution), but 21 bytes

```<code>d1j)6M1)6MTT2/H3$Y+bv
</code>```

Title: Derivative at the Edge

Body:
MATL, <s>21</s> 15 bytes

2/d1)6Mh8Mt0)h+

TryItOnline

Halves the input vector, and takes successive differences, to give d=[i(2)-i(1) i(3)-i(2) ... i(end)-i(end-1)]/2 and then makes two modified vectors, [d(1) d] and [d d(end)], and adds them.

The older version was better (because convolution), but 21 bytes

d1j)6M1)6MTT2/H3$Y+bv


问:
Calculate Euler's totient function

Background

Euler's totient
function φ(n) is defined as the number of whole numbers less than or equal to n that are relatively prime to n,
that is, the number of possible values of x in 0 < x <= n for which
gcd(n, x) == 1.
We've had
a
few totient-related challenges
before, but never one which is just calculating it.

The mapping of the totient function onto the whole numbers is OEIS A000010.

Challenge

Given an integer n > 0, calculate φ(n).
You may take input through
command-line arguments,
standard input,
function arguments,
or anything else reasonable.
You may give output through
standard output,
return values,
or anything else reasonable.
Anonymous functions are acceptable.
You may assume that the input will not overflow your natural method of storing integers, e.g. int in C, but you must support inputs up to 255.
If your language has a built-in totient function, you may not use it.

Examples

```<code>φ(1) => 1
φ(2) => 1
φ(3) => 2
φ(8) => 4
φ(9) => 6
φ(26) => 12
φ(44) => 20
φ(105) => 48
</code>```

Shortest answer in bytes wins. If your language uses an encoding other than UTF-8, mention it in your answer.

答:
Pyth, 6 bytes

```<code>smq1iQ
</code>```

Try it online!

```<code>/iLQQ1
</code>```

Try it online!

Explanation

```<code>smq1iQ     input as Q
smq1iQdQ   implicitly fill variables

 m     Q   for d in [0 1 2 3 .. Q-1]:
    iQd        gcd of Q and d
  q1           equals 1? (1 if yes, 0 if no)
s          sum of the results

/iLQQ1     input as Q

 iLQQ      gcd of each in [0 1 2 3 .. Q-1] with Q
/    1     count the number of occurrences of 1
</code>```

Title: Calculate Euler's totient function

Body:
Pyth, 6 bytes

smq1iQ

Try it online!

/iLQQ1

Try it online!

Explanation

smq1iQ     input as Q
smq1iQdQ   implicitly fill variables

 m     Q   for d in [0 1 2 3 .. Q-1]:
    iQd        gcd of Q and d
  q1           equals 1? (1 if yes, 0 if no)
s          sum of the results

/iLQQ1     input as Q

 iLQQ      gcd of each in [0 1 2 3 .. Q-1] with Q
/    1     count the number of occurrences of 1


答:
J, 11 bytes

```<code>+/@(1=+.)i.
</code>```

Usage

```<code>>> f =: +/@(1=+.)i.
>> f 44
<< 20
</code>```

where >> is STDIN and << is STDOUT.

Explanation

```<code>+/ @ ( 1 = +. ) i.
               │
   ┌───────────┴┐
 +/@(1=+.)      i.
   │
 ┌─┼──┐
+/ @ 1=+.
    ┌─┼─┐
    1 = +.

>> (i.) 44            NB. generate range
<< 0 1 2 3 4 ... 43
>> (+.i.) 44          NB. calculate gcd of each with input
<< 44 1 2 1 4 ... 1
>> ((1=+.)i.) 44      NB. then test if each is one (1 if yes, 0 if no)
<< 0 1 0 1 0 ... 1
>> (+/@(1=+.)i.) 44   NB. sum of all the tests
<< 20
</code>```

Title: Calculate Euler's totient function

Body:
Background

Euler's totient
function φ(n) is defined as the number of whole numbers less than or equal to n that are relatively prime to n,
that is, the number of possible values of x in 0 < x <= n for which
gcd(n, x) == 1.
We've had
a
few totient-related challenges
before, but never one which is just calculating it.

The mapping of the totient function onto the whole numbers is OEIS A000010.

Challenge

Given an integer n > 0, calculate φ(n).
You may take input through
command-line arguments,
standard input,
function arguments,
or anything else reasonable.
You may give output through
standard output,
return values,
or anything else reasonable.
Anonymous functions are acceptable.
You may assume that the input will not overflow your natural method of storing integers, e.g. int in C, but you must support inputs up to 255.
If your language has a built-in totient function, you may not use it.

Examples

```<code>φ(1) => 1
φ(2) => 1
φ(3) => 2
φ(8) => 4
φ(9) => 6
φ(26) => 12
φ(44) => 20
φ(105) => 48
</code>```

Shortest answer in bytes wins. If your language uses an encoding other than UTF-8, mention it in your answer.

Body:
J, 11 bytes

+/@(1=+.)i.

Usage

>> f =: +/@(1=+.)i.
>> f 44
<< 20

where >> is STDIN and << is STDOUT.

Explanation

+/ @ ( 1 = +. ) i.
               │
   ┌───────────┴┐
 +/@(1=+.)      i.
   │
 ┌─┼──┐
+/ @ 1=+.
    ┌─┼─┐
    1 = +.

>> (i.) 44            NB. generate range
<< 0 1 2 3 4 ... 43
>> (+.i.) 44          NB. calculate gcd of each with input
<< 44 1 2 1 4 ... 1
>> ((1=+.)i.) 44      NB. then test if each is one (1 if yes, 0 if no)
<< 0 1 0 1 0 ... 1
>> (+/@(1=+.)i.) 44   NB. sum of all the tests
<< 20


答:
Perl 6, <s> 26 24 </s> 22 bytes

<s>{[+] (^$^n Xgcd $n) X== 1}
{+grep 2>*,(^$_ Xgcd$_)}</s>
{[+] 2 X>(^$_ Xgcd$_)}```

<h3>Explanation:</h3>

<pre class="lang-perl6 prettyprint-override"><code>{
  [+] # reduce using &infix:<+>
    2
    X[>] # crossed compared using &infix:«>»
    (
      ^$_    # up to the input ( excludes input )
      X[gcd] # crossed using &infix:<gcd>
      $_     # the input
    )
}
</code>```

Example:

#! /usr/bin/env perl6
use v6.c;

my &φ = {[+] 2 X>(^$_ Xgcd$_)};

say φ(1) # 1
say φ(2) # 1
say φ(3) # 2
say φ(8) # 4
say φ(9) # 6
say φ(26) # 12
say φ(44) # 20
say φ(105) # 48

say φ 12345 # 6576
```

Title: Calculate Euler's totient function

Body:
Perl 6, <s> 26 24 </s> 22 bytes

<s>{[+] (^$^n Xgcd $n) X== 1}
{+grep 2>*,(^$_ Xgcd$_)}</s>
{[+] 2 X>(^$_ Xgcd$_)}

Explanation:

{
  [+] # reduce using &infix:<+>
    2
    X[>] # crossed compared using &infix:«>»
    (
      ^$_    # up to the input ( excludes input )
      X[gcd] # crossed using &infix:<gcd>
      $_     # the input
    )
}

Example:

#! /usr/bin/env perl6
use v6.c;

my &φ = {[+] 2 X>(^$_ Xgcd$_)};

say φ(1) # 1
say φ(2) # 1
say φ(3) # 2
say φ(8) # 4
say φ(9) # 6
say φ(26) # 12
say φ(44) # 20
say φ(105) # 48

say φ 12345 # 6576


答:
Actually, 11 bytes

```<code>;╗R`╜g`M1@c
</code>```

Try it online!

Explanation

```<code>;╗R`╜g`M1@c   register stack             remarks

                       44
;                      44 44
 ╗            44       44
  R           44       [1 2 3 .. 44]
       M      44       10                for example
    ╜         44       10 44
     g        44       2
              44       [1 2 1 .. 44]     gcd of each with register
        1     44       [1 2 1 .. 44] 1
         @    44       1 [1 2 1 .. 44]
          c   44       20                count
</code>```

With built-in

```<code>▒
</code>```

Try it online!

Title: Calculate Euler's totient function

Body:
Actually, 11 bytes

;╗R`╜g`M1@c

Try it online!

Explanation

;╗R`╜g`M1@c   register stack             remarks

                       44
;                      44 44
 ╗            44       44
  R           44       [1 2 3 .. 44]
       M      44       10                for example
    ╜         44       10 44
     g        44       2
              44       [1 2 1 .. 44]     gcd of each with register
        1     44       [1 2 1 .. 44] 1
         @    44       1 [1 2 1 .. 44]
          c   44       20                count

With built-in

▒

Try it online!


答:
Mathematica, <s>27</s> 22 bytes

```<code>Range@#~GCD~#~Count~1&
</code>```

An unnamed function that takes and returns an integer.

Not much to explain here, except that @ is prefix notation for function calls and ~...~ is (left-associative) infix notation, so the above is the same as:

```<code>Count[GCD[Range[#], #], 1] &
</code>```

Title: Calculate Euler's totient function

Body:
Mathematica, <s>27</s> 22 bytes

Range@#~GCD~#~Count~1&

An unnamed function that takes and returns an integer.

Not much to explain here, except that @ is prefix notation for function calls and ~...~ is (left-associative) infix notation, so the above is the same as:

Count[GCD[Range[#], #], 1] &


Title: Derivative at the Edge

Body:
My preferred way to approximate a derivative is the central difference, its more accurate than forward difference or backward difference, and I'm too lazy to go higher-order. But the central difference requires a data point on either side of point you are evaluating. Normally this means you end up not having a derivative at either endpoint. To solve it, I want you to switch to forward and backward difference at the edges:

Specifically, I want you to use a forward difference for the first point, a backward difference for the last point, and a central difference for all the points in the middle. Also, you can assume x values are evenly spaced, and focus only on y. Use these formulas:

Good luck, I'm looking forward to seeing if someone comes up with a simple rule which reproduces all 3 derivatives in the right places!

EX INPUT:

```<code>0.034  9.62    8.885   3.477   2.38
</code>```

I will use FD, CD, and BD to denote which algorithm to use in which spot, so above 5 points are used to approximate derivatives using

```<code>FD     CD      CD      CD     BD
</code>```

And then the calculated values would be:

```<code>9.586  4.4255 -3.0715 -3.2525 -1.097
</code>```

You can assume that there will always be at least 3 input points, and you can calculate using single or double precision.

And as always, shortest answer wins.

Body:
05AB1E, <s>20</s> <s>19</s> <s>17</s> 14 bytes

¥Ð¦øO;s¤s0èŠ)˜

Explained

¥Ð              # triplicate deltas of list
                  [9.585999999999999, -0.7349999999999994, -5.4079999999999995, -1.097]
  ¦øO;          # get central difference (fold addition over deltas and divide by 2)
                  [4.4254999999999995, -3.0714999999999995, -3.2524999999999995]
      s¤        # get backwards difference
                  -1.097
        s0è     # get forwards difference
                  9.585999999999999
           Š)˜  # reorder differences, merge to list and flatten
                  [9.585999999999999, 4.4254999999999995, -3.0714999999999995, -3.2524999999999995, -1.097]

Try it online

Saved 2 bytes thanks to @Adnan


问:
Find the nth Fibonnaci Prime, in the shortest code
The challenge is rather simple:

Take a positive whole number \$n\$ as input.

Output the \$n\$th Fibonacci prime number, i.e. the \$n\$th Fibonacci number that is also prime.

Input can be as an parameter to a function (and the output will be the return value), or can be taken from the command line (and outputted there).

Note: Using built in prime checking functions or Fibonacci series generators is not allowed.

The first 10 Fibonacci primes are

```<code>[2, 3, 5, 13, 89, 233, 1597, 28657, 514229, 433494437]
</code>```

Shortest code wins. Good luck!

答:
Groovy: 105 (134 with whitespaces)

b is the fibonacci function.

the closure inside the if is the prime check function. Update: a small fix on it

r is the prime fibonacci number.

```<code>r={ n->
  c=k=0
  while(1) {
    b={a->a<2?a:b(a-1)+b(a-2)}
    f=b k++
    if({z->z<3?:(2..<z).every{z%it}}(f)&&c++==n)return f
  }
}
</code>```

Test cases:

```<code>assert r(0) == 0
assert r(1) == 1
assert r(2) == 1
assert r(3) == 2
assert r(4) == 3
assert r(5) == 5
assert r(6) == 13
assert r(7) == 89
assert r(8) == 233
assert r(9) == 1597
</code>```

A readable version:

```<code>def fib(n) {
  n < 2 ? n : fib(n-1) + fib(n-2)
}
def prime(n) {
  n < 2 ?: (2..<n).every { n % it }
}
def primeFib(n) {
  primes = inc = 0
  while( 1 ) {
    f = fib inc++
    if (prime( f ) && primes++ == n) return f
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Groovy: 105 (134 with whitespaces)

b is the fibonacci function.

the closure inside the if is the prime check function. Update: a small fix on it

r is the prime fibonacci number.

r={ n->
  c=k=0
  while(1) {
    b={a->a<2?a:b(a-1)+b(a-2)}
    f=b k++
    if({z->z<3?:(2..<z).every{z%it}}(f)&&c++==n)return f
  }
}

Test cases:

assert r(0) == 0
assert r(1) == 1
assert r(2) == 1
assert r(3) == 2
assert r(4) == 3
assert r(5) == 5
assert r(6) == 13
assert r(7) == 89
assert r(8) == 233
assert r(9) == 1597

A readable version:

def fib(n) {
  n < 2 ? n : fib(n-1) + fib(n-2)
}
def prime(n) {
  n < 2 ?: (2..<n).every { n % it }
}
def primeFib(n) {
  primes = inc = 0
  while( 1 ) {
    f = fib inc++
    if (prime( f ) && primes++ == n) return f
  }
}


答:
Brachylog, 25 bytes

```<code>:{:1e.$pdL,?$pd:LcCdC}fl.
</code>```

Explanation

Brachylog has no GCD built-in yet, so we check that the two numbers have no prime factors in common.

Main predicate:

```<code>:{...}fl.             Find all variables which satisfy predicate 1 when given to it as
                      output and with Input as input.
                      Unify the Output with the length of the resulting list
</code>```

Predicate 1:

```<code>:1e.                  Unify Output with a number between Input and 1
    $pdL              L is the list of prime factors of Output with no duplicates
        ,
         ?$pd:LcC     C is the concatenation of the list of prime factors of Input with
                      no duplicates and of L
                 dC   C with duplicates removed is still C
</code>```

Title: Calculate Euler's totient function

Body:
Brachylog, 25 bytes

:{:1e.$pdL,?$pd:LcCdC}fl.

Explanation

Brachylog has no GCD built-in yet, so we check that the two numbers have no prime factors in common.

Main predicate:

:{...}fl.             Find all variables which satisfy predicate 1 when given to it as
                      output and with Input as input.
                      Unify the Output with the length of the resulting list

Predicate 1:

:1e.                  Unify Output with a number between Input and 1
    $pdL              L is the list of prime factors of Output with no duplicates
        ,
         ?$pd:LcC     C is the concatenation of the list of prime factors of Input with
                      no duplicates and of L
                 dC   C with duplicates removed is still C


答:
Python >=3.5, <s>76</s> <s>64</s> 58 bytes

Thanks to LeakyNun for golfing off 12 (!) bytes.

Thanks to Sp3000 for golfing off 6 bytes.

```<code>import math
lambda n:sum(math.gcd(n,x)<2for x in range(n))
</code>```

I love how readable Python is. This makes sense, even through the golfedness.

Title: Calculate Euler's totient function

Body:
Python >=3.5, <s>76</s> <s>64</s> 58 bytes

Thanks to LeakyNun for golfing off 12 (!) bytes.

Thanks to Sp3000 for golfing off 6 bytes.

import math
lambda n:sum(math.gcd(n,x)<2for x in range(n))

I love how readable Python is. This makes sense, even through the golfedness.


答:
MATL, 7 bytes

```<code>t:Zd1=s
</code>```

You can TryItOnline. Simplest idea, make a vector 1 to N, and taken gcd of each element with N (Zd does gcd). Then, find which elements are equal to 1, and sum the vector to get the answer.

Title: Calculate Euler's totient function

Body:
MATL, 7 bytes

t:Zd1=s

You can TryItOnline. Simplest idea, make a vector 1 to N, and taken gcd of each element with N (Zd does gcd). Then, find which elements are equal to 1, and sum the vector to get the answer.


答:
Jelly, 4 bytes

```<code>Rgċ1
</code>```

Try it online!

Explanation

```<code>Rgċ1   Main monadic chain. Argument: z

R      Yield [1 2 3 .. z].
 g     gcd (of each) (with z).
  ċ1   Count the number of occurrences of 1.
</code>```

With built-in

```<code>ÆṪ
</code>```

Try it online!

Explanation

```<code>ÆṪ   Main monadic chain. Argument: z

ÆṪ   Totient of z.
</code>```

Title: Calculate Euler's totient function

Body:
Jelly, 4 bytes

Rgċ1

Try it online!

Explanation

Rgċ1   Main monadic chain. Argument: z

R      Yield [1 2 3 .. z].
 g     gcd (of each) (with z).
  ċ1   Count the number of occurrences of 1.

With built-in

ÆṪ

Try it online!

Explanation

ÆṪ   Main monadic chain. Argument: z

ÆṪ   Totient of z.


问:
ASCII Art Mayan Numerals
This challenge is simple.  Given a number, output a ascii-art representation of the number, using the Mayan Base-20 numeral system.

What is the Mayan system?

The Mayans used base 20 to store numbers, so the first position was the 1s place, the next the 20s place, then the 400s, etc.

So Mayan number 1 is 1 in base 10, but 10 is actually 20 in base 10, 207 is 807 in base 10, etc..

And they represented their numbers as pictographs, with a special symbol for 0.

```<code> -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------
</code>```

That was their zero.  (at least the half picascii half my artisticness ascii art version)

That is a <s>real</s> picture of the mayan zero symbol.1

This was their five:

```<code>--------------------------------
|                              |
--------------------------------
</code>```

And a 4:

```<code> ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----
</code>```

Finally, to put it together:

```<code> ----   ----   ----
|    | |    | |    |
|    | |    | |    |
 ----   ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------
</code>```

So they have x//5 bars, and x%5 dots on top of the bars.  And if x=0, they use the shell/loaf instead of a blank space.

For more images, try the Wikimedia Commons page of Maya number images.

But this is only for numbers up to 19. We aren't allowed to have more than 4 bars and 4 dots in a single 'story'... So we go up!

The output for 20 is:

```<code> ----
|    |
|    |
 ----

 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------
</code>```

Note this would normally be invalid, because is has a 1 and a 0 at the same time.  But the 3 (note that, your answer needs at least 3) newlines before the 0 mean a new place value.

The bottom story has dots, meaning 1, and bars meaning 5.  But it actually has dots meaning 20^0 and bars meaning 20^0 * 5.

Each story goes up a power.  The second story dots mean 20 (20^1) and 100 (20^1 * 5).

So the number 506 can be represented as:

```<code> ----
|    |
|    |
 ----

--------------------------------
|                              |
--------------------------------

 ----
|    |
|    |
 ----
--------------------------------
|                              |
--------------------------------
</code>```

This is (20^0) * 1 + (20^0 * 5) * 1 + (20^1 * 5) * 1 + (20^2) * 1 = 1 + 5 + 100 + 400 = 506.

Your mission, should you choose not or choose to (it doesn't matter), is to output a ascii art representation of the base-10 number.

Other Rules:

Leading/trailing space is okay, as long as the dots, bars, and shells are intact.

The bars, dots, and shells must be exactly what the test cases have.  No resizing.

Leading '0's are okay. (leading shells on the output)

You don't have to have exactly 3 newlines between each place value or story, just at least 3.

Test Cases:

```<code>15

--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

12

 ----   ----
|    | |    |
|    | |    |
 ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

4

 ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----

0

 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------

24

 ----
|    |
|    |
 ----

 ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----

33

 ----
|    |
|    |
 ----

 ----   ----   ----
|    | |    | |    |
|    | |    | |    |
 ----   ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

20

 ----
|    |
|    |
 ----

 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------
</code>```

1: They also used the heads of gods for the symbols, but for this challenge the shell/bread/zelda chest will be used.

答:
Python 3, 213 bytes

Came up with an even shorter version using a different approach:

```<code>s,v,h,x=' |-\n'
t=s+h*19+s
k=4*s+v
w=v+4*k
y=v+s*19+v
a=' ----  '
b=v+k+s
c=h*32
d=v+s*30+v
m=lambda n:m(n//20)+([n%5*a,n%5*b,n%5*b,n%5*a][:n%5*4]+n%20//5*[c,d,d,c]if n%20else[t,w,w,v+h*19+v,y,y,t])+[x,x]if n else[]
</code>```

explanation

The first 9 lines or so, build up strings that are used to make the symbols

```<code>s,v,h,x = ' |-\n'
k = '    |'

    # parts for a unit
a = ' ----  '
b = '|    | '

    # parts for a five
c = '--------------------------------'
d = '|                              |'

    # parts for a zero
t = ' ------------------- '
w = '|    |    |    |    |'
y = '|                   |'
</code>```

The core of the solution is the recursive function m, which builds a list of strings, one string for each line in the output.  Schematically, m looks like:

```<code>m(n//20) + (ones + fives if n%20 else zero) + [x,x] if n else []
</code>```

m can be rewritten like:

```<code>def m(n):
  if n:
    ans = m(n//20)                             # process high digits first

    if n%20:                                   # if there is a base-20 digit
      ans += [n%5*a,n%5*b,n%5*b,n%5*a][:n%5*4] # add strings for the 'ones' if any
      ans += n%20//5 * [c, d, d, c]            # add strings for the 'fives' if any

    else:
      ans += [t,w,w,v+h*19+v,y,y,t]            # otherwise, add strings for a `zero`

    ans += [x,x]                               # blank lines between digit groups

  else:
    ans = []                                   # base case

  return ans
</code>```

The recursive call m(n//20) comes first so that the most significant digits are done first.

[n%5*a,n%5*b,n%5*b,n%5*a] are the string for ones symbols.  a is the top row for a single symbol.  n%5 is the number of one symbols for this digit.  So, n%5*a is a string for the top (and bottom) row of n%5 ones. Similarly, 'n%5*b` is a string for the 2nd (and 3rd) row.

The expression [:n%5*4] acts like an if to avoid extra blank lines in the output if there aren't any 'ones' to output.  It's not needed, but makes the output look better.

n%20//5 is the number of symbols for five that are needed.  [c,d,d,c] are the strings to make one symbol for five.

[t,w,w,v+h*19+v,y,y,t] are the strings to make the zero symbol

[x,x] puts at least three blank lines between groups of Mayan digits

Title: ASCII Art Mayan Numerals

Body:
Python 3, 213 bytes

Came up with an even shorter version using a different approach:

s,v,h,x=' |-\n'
t=s+h*19+s
k=4*s+v
w=v+4*k
y=v+s*19+v
a=' ----  '
b=v+k+s
c=h*32
d=v+s*30+v
m=lambda n:m(n//20)+([n%5*a,n%5*b,n%5*b,n%5*a][:n%5*4]+n%20//5*[c,d,d,c]if n%20else[t,w,w,v+h*19+v,y,y,t])+[x,x]if n else[]

explanation

The first 9 lines or so, build up strings that are used to make the symbols

s,v,h,x = ' |-\n'
k = '    |'

    # parts for a unit
a = ' ----  '
b = '|    | '

    # parts for a five
c = '--------------------------------'
d = '|                              |'

    # parts for a zero
t = ' ------------------- '
w = '|    |    |    |    |'
y = '|                   |'

The core of the solution is the recursive function m, which builds a list of strings, one string for each line in the output.  Schematically, m looks like:

m(n//20) + (ones + fives if n%20 else zero) + [x,x] if n else []

m can be rewritten like:

def m(n):
  if n:
    ans = m(n//20)                             # process high digits first

    if n%20:                                   # if there is a base-20 digit
      ans += [n%5*a,n%5*b,n%5*b,n%5*a][:n%5*4] # add strings for the 'ones' if any
      ans += n%20//5 * [c, d, d, c]            # add strings for the 'fives' if any

    else:
      ans += [t,w,w,v+h*19+v,y,y,t]            # otherwise, add strings for a `zero`

    ans += [x,x]                               # blank lines between digit groups

  else:
    ans = []                                   # base case

  return ans

The recursive call m(n//20) comes first so that the most significant digits are done first.

[n%5*a,n%5*b,n%5*b,n%5*a] are the string for ones symbols.  a is the top row for a single symbol.  n%5 is the number of one symbols for this digit.  So, n%5*a is a string for the top (and bottom) row of n%5 ones. Similarly, 'n%5*b` is a string for the 2nd (and 3rd) row.

The expression [:n%5*4] acts like an if to avoid extra blank lines in the output if there aren't any 'ones' to output.  It's not needed, but makes the output look better.

n%20//5 is the number of symbols for five that are needed.  [c,d,d,c] are the strings to make one symbol for five.

[t,w,w,v+h*19+v,y,y,t] are the strings to make the zero symbol

[x,x] puts at least three blank lines between groups of Mayan digits


答:
Pyke, 5 bytes

```<code>m.H1/
</code>```

Try it here!

```<code>count(map(gcd, range(input)), 1)
</code>```

Title: Calculate Euler's totient function

Body:
Pyke, 5 bytes

m.H1/

Try it here!

count(map(gcd, range(input)), 1)


Title: Calculate Euler's totient function

Body:
JavaScript (ES6), 67 bytes

f=n=>[...Array(n)].reduce(r=>r+=g(n,++i)<2,i=0,g=(a,b)=>b?g(b,a%b):a)


答:
Julia 1.x, 22 bytes

```<code>!n=sum(gcd.(1:n,n).<2)
</code>```

This is the same as the old solution, but using newer features of the language, as the original solution dates back to something like Julia 0.4. This solution uses function broadcasting to achieve the result more efficiently.

Julia, 25 bytes

```<code>!n=sum(i->gcd(i,n)<2,1:n)
</code>```

It's simple - the sum function allows you to give it a function to apply before summing - basically the equivalent of running map and then sum. This directly counts the number of relatively prime numbers less than n.

Title: Calculate Euler's totient function

Body:
Julia 1.x, 22 bytes

!n=sum(gcd.(1:n,n).<2)

This is the same as the old solution, but using newer features of the language, as the original solution dates back to something like Julia 0.4. This solution uses function broadcasting to achieve the result more efficiently.

Julia, 25 bytes

!n=sum(i->gcd(i,n)<2,1:n)

It's simple - the sum function allows you to give it a function to apply before summing - basically the equivalent of running map and then sum. This directly counts the number of relatively prime numbers less than n.


问:
Downward Number Race
Your task is to create a program that adds random numbers to previous sums in the ultimate number racing showdown.

Each racer (column) starts at 0 and adds either 1 or 0 to the previous sum at each step of the race until all of the racers reach the score required to win. The 1 or 0 should be chosen at random (the standard definition of random can be found here). The output will show the result of the race, with each column representing one racer, in this format:

```<code>>> racers:5,score needed:2

0 0 0 0 0 # all racers start at 0
+ + + + + # add
1 0 0 0 1 # random 1 or 0
= = = = = # equals
1 0 0 0 1 # sum
+ + + + +
0 0 0 0 1
= = = = =
1 0 0 0 2 # winner!
+ + + +
1 1 1 1
= = = =
2 1 1 1
  + + +
  1 1 1
  = = =
  2 2 2   # losers
</code>```

Note: only the numbers, +, and = need to be included in the output.

Input

Your program will accept the following two parameters as input:

the number of racers (columns), which must be greater than two

the score required to win, which must be greater than one

This is code-golf--the program with the least bytes wins.

Edit: there's a non-enforceable max score of 9--this is to preserve the integrity of the column. Also, spaces between columns can be omitted in the output.

答:
TSQL, <s>367</s> <s>345</s> 341 bytes

Golfed

```<code>DECLARE @r int=20, -- racers
        @g char=2  -- goal

DECLARE @ varchar(99)=REPLICATE('0',@r)a:PRINT @
DECLARE @A varchar(99)='',@s varchar(99)='',@i int=0WHILE @i<@r
SELECT
@i+=1,@A+=char(43-x*11),@s+=IIF(x=1,' ',LEFT(y,1)),@=RIGHT(@,@r-1)+IIF(x=1,' ',REPLACE(LEFT(@,1)+y,@g+1,' '))FROM(SELECT
IIF(LEFT(@,1)IN('',@g),1,0)x,ROUND(RAND(),0)y)z
PRINT @A+'
'+@s+'
'+REPLACE(@A,'+','=')IF @>''goto a
</code>```

Try it online

Ungolfed:

```<code>DECLARE @r int=10, -- racers
        @g char=2  -- goal

DECLARE @ varchar(99)=REPLICATE('0',@r)
a:
PRINT @
DECLARE @A varchar(99)='',@s varchar(99)='',@i int=0

WHILE @i<@r
  SELECT
    @i+=1,
    @A+=char(43-x*11),
    @s+=IIF(x=1,' ',LEFT(y,1)),
    @=RIGHT(@,@r-1)+IIF(x=1,' ',REPLACE(LEFT(@,1)+y,@g+1,' '))
  FROM(SELECT IIF(LEFT(@,1)IN('',@g),1,0)x,ROUND(RAND(),0)y)z

PRINT @A+'
'+@s+'
'+REPLACE(@A,'+','=')

IF @>''GOTO a
</code>```

Note that the random seed on the test site will always be the same, giving the same result each time, in studio management it will give different results. Can use different values for racers and goal to get a different picture

Title: Downward Number Race

Body:
TSQL, <s>367</s> <s>345</s> 341 bytes

Golfed

DECLARE @r int=20, -- racers
        @g char=2  -- goal

DECLARE @ varchar(99)=REPLICATE('0',@r)a:PRINT @
DECLARE @A varchar(99)='',@s varchar(99)='',@i int=0WHILE @i<@r
SELECT
@i+=1,@A+=char(43-x*11),@s+=IIF(x=1,' ',LEFT(y,1)),@=RIGHT(@,@r-1)+IIF(x=1,' ',REPLACE(LEFT(@,1)+y,@g+1,' '))FROM(SELECT
IIF(LEFT(@,1)IN('',@g),1,0)x,ROUND(RAND(),0)y)z
PRINT @A+'
'+@s+'
'+REPLACE(@A,'+','=')IF @>''goto a

Try it online

Ungolfed:

DECLARE @r int=10, -- racers
        @g char=2  -- goal

DECLARE @ varchar(99)=REPLICATE('0',@r)
a:
PRINT @
DECLARE @A varchar(99)='',@s varchar(99)='',@i int=0

WHILE @i<@r
  SELECT
    @i+=1,
    @A+=char(43-x*11),
    @s+=IIF(x=1,' ',LEFT(y,1)),
    @=RIGHT(@,@r-1)+IIF(x=1,' ',REPLACE(LEFT(@,1)+y,@g+1,' '))
  FROM(SELECT IIF(LEFT(@,1)IN('',@g),1,0)x,ROUND(RAND(),0)y)z

PRINT @A+'
'+@s+'
'+REPLACE(@A,'+','=')

IF @>''GOTO a

Note that the random seed on the test site will always be the same, giving the same result each time, in studio management it will give different results. Can use different values for racers and goal to get a different picture


问:
Write a program to elasticize strings
Nice verb there, in the title.

Write a program that given an input string, will "elasticize" this string and output the result. Elasticizing a string is done as follows:

The first character is shown once.
The second character is shown twice.
The third character is shown thrice,
and so on.

As you can see, the amount of duplications of a certain character is related to the character's index as opposed to its previous occurrences in the string.

You can expect to receive only printable ASCII characters. Based off the following link, these characters have decimal values 32-126.

Examples:

Why: Whhyyy

SKype: SKKyyyppppeeeee

LobbY: LoobbbbbbbYYYYY (Note how there are 7 b's since the first b is shown 3 times and the second b is shown 4 times, making a total of 7 b's).

A and B: A  aaannnnddddd      BBBBBBB

Shortest bytes wins :)

答:
Clojure, 86 bytes

```<code>(fn[s](apply str(mapcat #(repeat(+(nth % 1)1)(nth % 0))(map list s(range(count s))))))
</code>```

Well, nearly beat C. Create a list of pairs (symbol, its position), then repeat each symbol given number of times and flatten the result list and concatenate the list into one string.

See it here: https://ideone.com/uQNar2

Title: Write a program to elasticize strings

Body:
Clojure, 86 bytes

(fn[s](apply str(mapcat #(repeat(+(nth % 1)1)(nth % 0))(map list s(range(count s))))))

Well, nearly beat C. Create a list of pairs (symbol, its position), then repeat each symbol given number of times and flatten the result list and concatenate the list into one string.

See it here: https://ideone.com/uQNar2


答:
GolfScript, 13 chars

```<code>~2\?,{.2/^}%`
</code>```

For example, the input 3 produces the output [0 1 3 2 6 7 5 4].

Here's a de-golfed version with comments:

```<code>~              # evaluate the input, turning it from a string into a number
2 \ ?          # raise 2 to the power given by the input...
,              # ...and turn it into a list containing the numbers from 0 to 2^n-1
{ . 2 / ^ } %  # xor each number in the list with itself divided by 2
`              # un-eval the list into a string for output
</code>```

It's perhaps interesting to note that there are no particular "golfing tricks" involved — this is basically the most obvious and straightforward way to solve this task in GolfScript.

Title: Traverse all numbers with only one bit flip per step

Body:
You can count 0, 1, 2, 3, 4.
But to get from 3 to 4 you have to change 3 bits at once.
Given a number of bits, how can you go through all numbers once,
but change at each step only 1! bit.

Here is an example for 3 bits:

```<code>000 100 110 010 011 111 101 001
</code>```

so the output is:

```<code>0 1 3 2 6 7 5 4
</code>```

Rules:

given a number of bits n, return a list of 2^n unique numbers

between to consecutive numbers only one bit is different

the shorter the code the better

Body:
GolfScript, 13 chars

~2\?,{.2/^}%`

For example, the input 3 produces the output [0 1 3 2 6 7 5 4].

Here's a de-golfed version with comments:

~              # evaluate the input, turning it from a string into a number
2 \ ?          # raise 2 to the power given by the input...
,              # ...and turn it into a list containing the numbers from 0 to 2^n-1
{ . 2 / ^ } %  # xor each number in the list with itself divided by 2
`              # un-eval the list into a string for output

It's perhaps interesting to note that there are no particular "golfing tricks" involved — this is basically the most obvious and straightforward way to solve this task in GolfScript.


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

7 bytes thanks to Martin Ender.

```<code>.+
$*
(?!(11+)\1*$(?<=^\1+)).
</code>```

Try it online!

Explanation

There are two stages (commands).

First stage

```<code>.+
$*
</code>```

It is a simple regex substitution, converting the input to that many ones.

For example, 5 would be converted to 11111.

Second stage

```<code>(?!(11+)\1*$(?<=^\1+)).
</code>```

This regex tries to match the positions which satisfy the condition (co-prime with input), and then return the number of matches.

Title: Calculate Euler's totient function

Body:
Background

Euler's totient
function φ(n) is defined as the number of whole numbers less than or equal to n that are relatively prime to n,
that is, the number of possible values of x in 0 < x <= n for which
gcd(n, x) == 1.
We've had
a
few totient-related challenges
before, but never one which is just calculating it.

The mapping of the totient function onto the whole numbers is OEIS A000010.

Challenge

Given an integer n > 0, calculate φ(n).
You may take input through
command-line arguments,
standard input,
function arguments,
or anything else reasonable.
You may give output through
standard output,
return values,
or anything else reasonable.
Anonymous functions are acceptable.
You may assume that the input will not overflow your natural method of storing integers, e.g. int in C, but you must support inputs up to 255.
If your language has a built-in totient function, you may not use it.

Examples

```<code>φ(1) => 1
φ(2) => 1
φ(3) => 2
φ(8) => 4
φ(9) => 6
φ(26) => 12
φ(44) => 20
φ(105) => 48
</code>```

Shortest answer in bytes wins. If your language uses an encoding other than UTF-8, mention it in your answer.

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

7 bytes thanks to Martin Ender.

.+
$*
(?!(11+)\1*$(?<=^\1+)).

Try it online!

Explanation

There are two stages (commands).

First stage

.+
$*

It is a simple regex substitution, converting the input to that many ones.

For example, 5 would be converted to 11111.

Second stage

(?!(11+)\1*$(?<=^\1+)).

This regex tries to match the positions which satisfy the condition (co-prime with input), and then return the number of matches.


问:
Difference of the square of the sum
Find the difference between the square of the sums and sum of the squares.

This is the mathematical representation:

\$\left(\sum n\right)^2-\sum n^2\$

Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive.
Limits will be whole integers above 0.

Your program/method should return the answer.

You may use whichever base you would like to, but please state in your answer which base you have used.

Test case (Base 10)

```<code>5,9      970
91,123   12087152
1,10     2640
</code>```

This is usual code-golf, so the shorter the answer the better.

答:
Perl 5.10, 41 bytes

```<code>map{$s+=$_,$r+=$_**2}(<>..<>);say$s**2-$r
</code>```

Input is given on 2 lines, for instance:

```<code>61
127
</code>```

Try it here!

Title: Difference of the square of the sum

Body:
Perl 5.10, 41 bytes

map{$s+=$_,$r+=$_**2}(<>..<>);say$s**2-$r

Input is given on 2 lines, for instance:

61
127

Try it here!


答:
Batch, <s>151</s> <s>145</s> 144 bytes

```<code>@echo off
set t=
for /l %%i in (1,1,%1)do call:g %1 %%i
echo %t%
exit/b
:g
set/ag=%1%%%2
if not %g%==0 call:g %2 %g%
if %2%==1 set/at+=1
</code>```

Edit: Saved 4 bytes by removing unnecessary spaces. Saved 1 byte by using +=. Saved 1 byte by clearing t as += will interpret that as 0 anyway. Saved 1 byte thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ.

Title: Calculate Euler's totient function

Body:
Batch, <s>151</s> <s>145</s> 144 bytes

@echo off
set t=
for /l %%i in (1,1,%1)do call:g %1 %%i
echo %t%
exit/b
:g
set/ag=%1%%%2
if not %g%==0 call:g %2 %g%
if %2%==1 set/at+=1

Edit: Saved 4 bytes by removing unnecessary spaces. Saved 1 byte by using +=. Saved 1 byte by clearing t as += will interpret that as 0 anyway. Saved 1 byte thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ.


Title: Derivative at the Edge

Body:
My preferred way to approximate a derivative is the central difference, its more accurate than forward difference or backward difference, and I'm too lazy to go higher-order. But the central difference requires a data point on either side of point you are evaluating. Normally this means you end up not having a derivative at either endpoint. To solve it, I want you to switch to forward and backward difference at the edges:

Specifically, I want you to use a forward difference for the first point, a backward difference for the last point, and a central difference for all the points in the middle. Also, you can assume x values are evenly spaced, and focus only on y. Use these formulas:

Good luck, I'm looking forward to seeing if someone comes up with a simple rule which reproduces all 3 derivatives in the right places!

EX INPUT:

```<code>0.034  9.62    8.885   3.477   2.38
</code>```

I will use FD, CD, and BD to denote which algorithm to use in which spot, so above 5 points are used to approximate derivatives using

```<code>FD     CD      CD      CD     BD
</code>```

And then the calculated values would be:

```<code>9.586  4.4255 -3.0715 -3.2525 -1.097
</code>```

You can assume that there will always be at least 3 input points, and you can calculate using single or double precision.

And as always, shortest answer wins.

Body:
JavaScript (ES6), 62 bytes

a=>a.map((_,i)=>i&&i--<a.length-2?(a[i+2]-a[i])/2:a[i+1]-a[i])


答:
J, 9 bytes

```<code>(-~:)&.q:
</code>```

This is based on the Jsoftware's essay on totient functions.

Given n = p1e1 ∙ p2e2 ∙∙∙ pkek where pk is a prime factor of n, the totient function φ(n) = φ(p1e1) ∙ φ(p2e2) ∙∙∙ φ(pkek) = (p1 - 1) p1e1 - 1 ∙ (p2 - 1) p2e2 - 1 ∙∙∙ (pk - 1) pkek - 1.

Usage

```<code>   f =: (-~:)&.q:
   (,.f"0) 1 2 3 8 9 26 44 105
  1  1
  2  1
  3  2
  8  4
  9  6
 26 12
 44 20
105 48
   f 12345
6576
</code>```

Explanation

```<code>(-~:)&.q:  Input: integer n
       q:  Prime decomposition. Get the prime factors whose product is n
(   )&     Operate on them
  ~:         Nub-sieve. Create a mask where 1 is the first occurrence
             of a unique value and 0 elsewhere
 -           Subtract elementwise between the prime factors and the mask
     &.q:  Perform the inverse of prime decomposition (Product of the values)
</code>```

Title: Calculate Euler's totient function

Body:
J, 9 bytes

(-~:)&.q:

This is based on the Jsoftware's essay on totient functions.

Given n = p1e1 ∙ p2e2 ∙∙∙ pkek where pk is a prime factor of n, the totient function φ(n) = φ(p1e1) ∙ φ(p2e2) ∙∙∙ φ(pkek) = (p1 - 1) p1e1 - 1 ∙ (p2 - 1) p2e2 - 1 ∙∙∙ (pk - 1) pkek - 1.

Usage

   f =: (-~:)&.q:
   (,.f"0) 1 2 3 8 9 26 44 105
  1  1
  2  1
  3  2
  8  4
  9  6
 26 12
 44 20
105 48
   f 12345
6576

Explanation

(-~:)&.q:  Input: integer n
       q:  Prime decomposition. Get the prime factors whose product is n
(   )&     Operate on them
  ~:         Nub-sieve. Create a mask where 1 is the first occurrence
             of a unique value and 0 elsewhere
 -           Subtract elementwise between the prime factors and the mask
     &.q:  Perform the inverse of prime decomposition (Product of the values)


问:
Create output twice the length of the code

The Challenge

Write a complete program that writes twice as many bytes to standard output as the length of the program.

Rules

The program must write ASCII characters to the standard output.

The contents of the output doesn't matter.

The output, measured in bytes, must be exactly twice the length of the program, also measured in bytes, unless you fulfill the bonus.

Any trailing newline is included in the output's byte count.

Bonus

Your program can optionally take a number, n, as input. If so, the output must be exactly n * program length bytes. You can assume that n will always be a positive integer. If no input is provided, n must default to 2.

If you do this,  you can subtract 25 bytes from your score.

Shortest program wins.

Restrictions

No standard loopholes.

The program must be at least 1 byte long.

No adding unnecessary whitespace to the source code to change its length. Similarly, comments don't count.

Unless you fulfill the bonus, the program must accept no input. If you do fulfill the bonus, the integer must be the only input.

Lowest score (program length in bytes - bonus) wins.

The shortest answer for each language wins for that language.

Leaderboards

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
PD, 204 bytes

```<code>#N canvas 1 7 1 1 1;
#X obj 1 6 loadbang;
#X msg 1 1 \; pd quit;
#X obj 2 5 print;
#X obj 2 2 metro 10;
#X obj 1 7 del 340;
#X connect 0 0 3 0;
#X connect 0 0 4 0;
#X connect 3 0 2 0;
#X connect 4 0 1 0;
</code>```

run with pd -nogui patchname.pd 2>&1. The program will print the String print: bang (12 bytes including the newline) every 10ms. Then the program terminates after 340ms which will result in the string being printed 34 times (34 * 12 = 408 Bytes output).

Body:
PD, 204 bytes

#N canvas 1 7 1 1 1;
#X obj 1 6 loadbang;
#X msg 1 1 \; pd quit;
#X obj 2 5 print;
#X obj 2 2 metro 10;
#X obj 1 7 del 340;
#X connect 0 0 3 0;
#X connect 0 0 4 0;
#X connect 3 0 2 0;
#X connect 4 0 1 0;

run with pd -nogui patchname.pd 2>&1. The program will print the String print: bang (12 bytes including the newline) every 10ms. Then the program terminates after 340ms which will result in the string being printed 34 times (34 * 12 = 408 Bytes output).


答:
Python with NumPy, 29 bytes

```<code>import numpy;numpy.gradient
</code>```

This happens to be the default behaviour of NumPy's gradient function. The bytes were counted according to this consensus.

Title: Derivative at the Edge

Body:
Python with NumPy, 29 bytes

import numpy;numpy.gradient

This happens to be the default behaviour of NumPy's gradient function. The bytes were counted according to this consensus.


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

```
<s>.bcF_-VNYK++]hJ,VUQQJ]eJttK</s>
<s>.bcF-VYN+]hJ,VQUQJ+tJ]eJ</s>
<s>++hJ-V+tQeQ+hQQcR2PtJeJ</s>
<s>*V++1*].5ttlQ1-V+tQeQ+h</s>
*V++1m.5ttQ1-V+tQeQ+h
```

Try it online!

Title: Derivative at the Edge

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

<s>.bcF_-VNYK++]hJ,VUQQJ]eJttK</s>
<s>.bcF-VYN+]hJ,VQUQJ+tJ]eJ</s>
<s>++hJ-V+tQeQ+hQQcR2PtJeJ</s>
<s>*V++1*].5ttlQ1-V+tQeQ+h</s>
*V++1m.5ttQ1-V+tQeQ+h

Try it online!


问:
Decode a Microsoft MS-DOS 5.0 FAT directory entry
The Microsoft FAT file system has a directory table to represent which "files" are in which "folders" on the disk. For the time, these entries crammed a lot of information into a small amount of bits. There are a bunch of technical specifications over on Wiki for the curious, but the challenge here is going to focus on a "simple" decoding of an entry.

Each entry consists of a 32-byte binary word, broken up into several sections. For consistency in this challenge, we'll be using the MS-DOS 5.0 version, the bytes are ordered as big endian, and we're calling byte 0x00 as the left-most, and byte 0x1F as the right-most.

Below is a brief schematic of the relevant sections, and what should be the output for each section (in bold).

The first 11 bytes are the file name in ASCII format (this is where the famous 8.3 filename comes from -- 8 bytes for the file name, 3 bytes for the extension). These are straight ASCII encoding, and should be output as ASCII with a period (.) between.

Note: both the 8 and the 3 parts are padded with spaces to make a full-length entry. The output should ignore spaces (i.e., don't output them).

The file extension may be empty (i.e., all spaces), in which case the output should not output the dot.

Since ASCII only uses the lower 7 bits, the bytes will all have a leading 0.

The next byte (0x0b) is a bitmask of the following:

0x01 Read Only - output RO

0x02 Hidden - output H

0x04 System - output S

0x08 Volume Label - output VL. File size (below) should be output as 0, regardless of its actual entry.

0x10 Subdirectory - output SD. File size (below) should be output as 0, regardless of its actual entry.

0x20 Archive - output A

0x40 Device - ignored for this challenge.

0x80 Reserved - ignored for this challenge.

Since this is a bitmask, multiple flags are possible - all applicable outputs should be concatenated together in any order. For example, 0xff could be ROHSVLSDA (or any other combination).

The next two bytes (0x0c and 0x0d) are not used under MS-DOS 5.0.

The next two bytes (0x0e and 0x0f) are the creation time as follows:

Bits 15 to 11 are the hours in 24-hour format - output 00 to 23

Bits 10 to 5 are the minutes - output 00 to 59

Bits 4 to 0 are the seconds/2 - output 00 to 58 (note that seconds are only in two-second resolution)

For clarification: hhhhhmmmmmmsssss when written big-endian.

The next two bytes (0x10 and 0x11) are the creation date as follows:

Bits 15 to 9 are the year - output 1980 for 0 up to 2107 for 127

Bits 8 to 5 are the months - output 1 to 12 (with or without leading zero)

Bits 4 to 0 are the day - output 0 to 31 (with or without leading zero)

For clarification: yyyyyyymmmmddddd when written big-endian.

The next two bytes (0x12 and 0x13) are the last access date. While used in MS-DOS 5.0, we're ignoring this portion for this challenge.

The next two bytes (0x14 and 0x15) are not used by MS-DOS 5.0.

The next two bytes (0x16 and 0x17) are the last modified time, following the same format as the creation time, above.

The next two bytes (0x18 and 0x19) are the last modified date, following the same format as the creation date, above.

The next two bytes (0x1a and 0x1b) are the cluster location of the file on disk. We're ignoring this portion for this challenge.

The final four bytes (0x1c, 0x1d, 0x1e, and 0x1f) are the file size - output as an unsigned integer, unless the VL or SD flags are set (above), in which case output 0.

Visual representation

```<code>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
\______________________________FILENAME________________________________________________/\_ATTR_/\___NOTUSED____/\_CREATIONTIME_/\_CREATIONDATE_/\__LASTACCESS__/\___NOTUSED____/\_MODIFIEDTIME_/\_MODIFIEDDATE_/\___NOTUSED____/\___________FILESIZE___________/
</code>```

Input

A single 32-byte word (i.e., 256 bits), in whatever format is convenient.

This could be as a string of 1 and 0, as several unsigned ints, an array of Boolean values, etc.

Please specify in your answer what format you're using for input.

You cannot take multiple input (i.e., an array pre-broken into the relevant byte sizes) unless that is the only way for your language to take input. Parsing the input is part of the challenge.

You can assume input to be valid (for example, you don't need to perform date checking to verify that the date is valid).

Bytes that are unused can be all 0, all 1, etc., just so long as they are present. In the below examples, I used all 0 for the unused bytes.

Output

Either printed to screen or returned, the following:

The filename as an ASCII string

The file attributes as an ASCII string

The creation time and creation date, with appropriate separators (colons, slashes, something to distinguish the components)

The modified time and modified date, again with appropriate separators

The file size

The output can be a space-separated or newline-separated single string, separate elements in an array, etc. Please specify in your answer how your output is formatted.

Rules

Standard I/O formats are acceptable.

Either a full program or a function are acceptable.

Standard loopholes are forbidden.

This is code-golf, so all usual golfing rules apply, and the shortest code wins.

Built-ins that perform exactly this function are forbidden.

Examples

```<code>0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000

programm.ing HS 20:18:08 2016/06/20 20:18:08 2016/06/20 53248

0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001

ppcg SDS 11:43:24 2010/12/31 20:18:08 2016/06/20 0
</code>```

Body:
Ruby, 344 bytes

m=gets
s=->b,l{b.slice!(0,l).to_i 2}
t=->b{'%02d:%02d:%02d %d/%d/%d'%[s[b,5],s[b,6],2*s[b,5],s[b,7]+1980,s[b,4],s[b,5],]}
i=(0..q=32).map{|i|m[i*8,8].to_i 2}
c=i.map(&:chr).join
n=c[0,8].strip
e=c[8,3].strip
e>?!&&n<<?.+e
f=''
6.times{|j|i[11][j]>0&&f<<%w(RO H S VL SD A)[j]}
$><<[n,f,t[m[112,q]],t[m[176,q]],(f[/VL|SD/]?0:m[-q,q].to_i(2))]*' '

The slightly more readable version is available here.

Online test: http://ideone.com/Fww1Rw


答:
05AB1E, 7 bytes

```<code>Lvy¹¿i¼
</code>```

Explained

```<code>Lv        # for each x in range(1,n)
  y¹¿     # GCD(x,n)
     i¼   # if true (1), increase counter
          # implicitly display counter
</code>```

Try it online

Title: Calculate Euler's totient function

Body:
05AB1E, 7 bytes

Lvy¹¿i¼

Explained

Lv        # for each x in range(1,n)
  y¹¿     # GCD(x,n)
     i¼   # if true (1), increase counter
          # implicitly display counter

Try it online


问:
Tips for golfing in GolfScript
What, this post doesn't exist yet?

Of course, GolfScript is made for golfing, so you might think that no specific tips are really needed.  But to make full use of GolfScript's features, you need to learn some non-obvious tricks.  This post is for collecting such helpful tips and tricks.

To start with, here are the official GolfScript reference pages.  You should really familiarize yourself with these first:

Tutorial

Syntax

Built-ins

Quick reference

In particular, I would very much suggest reading the pages in this order — the quick reference is of little use until you're already reasonably familiar with the built-ins, and the tutorial includes some important details that are not explained on the other pages.

Ps. For the sake of inspiration and personal interest, here are some questions I'd like to see nice answers to:

How to do limited transliteration in GolfScript?  {FROM?TO=}% works if you can be sure all the inputs are found in FROM (or don't mind them all being mapped to the last element of TO), but all the ways I've seen for leaving unmapped values unchanged have been more or less klugey.

How to best convert a string into an array of ASCII codes and back?  Which operations do this as a side effect?  What's the best way to dump the characters in a string onto the stack (like ~ does for arrays)?

答:
Negating a number

One thing GolfScript lacks is a built-in negation operator.
The obvious ways to convert a number on the stack to its negative, like -1* or 0\-, need three chars.  However, there's a way to do it in two:

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

This works because GolfScript uses two's complement arithmetic, so that ~x equals −x−1.

Of course, the variant (~ also works; choosing between them is generally a matter of taste.

Title: Tips for golfing in GolfScript

Body:
Negating a number

One thing GolfScript lacks is a built-in negation operator.
The obvious ways to convert a number on the stack to its negative, like -1* or 0\-, need three chars.  However, there's a way to do it in two:

~)

This works because GolfScript uses two's complement arithmetic, so that ~x equals −x−1.

Of course, the variant (~ also works; choosing between them is generally a matter of taste.


答:
Haskell, <s>31</s> 30 bytes

```<code>\n->sum[1|x<-[1..n],gcd n x<2]
</code>```

1 byte saved, thanks to @Damien.

Selects values with gcd = 1, maps each to 1, then takes the sum.

Title: Calculate Euler's totient function

Body:
Haskell, <s>31</s> 30 bytes

\n->sum[1|x<-[1..n],gcd n x<2]

1 byte saved, thanks to @Damien.

Selects values with gcd = 1, maps each to 1, then takes the sum.


问:
Showcase of Languages

Notes

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

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

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

How this works

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

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

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

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

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

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

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

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

Current answers, sorted alphabetically by language name

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

答:
Golisp

Factoid

Golisp is a very simple programming language, but despite it's name it's not a Lisp dialect.

Length 1 snippet

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

Return 0, but since this value isn't used this is a no-op.

Length 2 snippet

```<code>""
</code>```

Return a empty string, but since this value isn't used this is a no-op.

Length 3 snippet

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

Create a list with 1 element, 0

Length 4 snippet

```<code>+[1]
</code>```

Call the function + with one argument, 1. The returned value is 1.

Length 5 snippet

```<code>chr@5
</code>```

Use the shorthand notation function@argument. Return the ASCII character ENQ (5), but as always, nothing is printed :/

Length 6 snippet

```<code>+[3 5]
</code>```

Simply add 3 and 5.

Title: Showcase of Languages

Body:
Golisp

Factoid

Golisp is a very simple programming language, but despite it's name it's not a Lisp dialect.

Length 1 snippet

0

Return 0, but since this value isn't used this is a no-op.

Length 2 snippet

""

Return a empty string, but since this value isn't used this is a no-op.

Length 3 snippet

(0)

Create a list with 1 element, 0

Length 4 snippet

+[1]

Call the function + with one argument, 1. The returned value is 1.

Length 5 snippet

chr@5

Use the shorthand notation function@argument. Return the ASCII character ENQ (5), but as always, nothing is printed :/

Length 6 snippet

+[3 5]

Simply add 3 and 5.


答:
PowerShell v2+, 72 bytes

```<code>param($n)1..$n|%{$a=$_;$b=$n;while($b){$a,$b=$b,($a%$b)};$o+=!($a-1)};$o
</code>```

PowerShell doesn't have a GCD function available to it, so I had to roll my own.

This takes input $n, then ranges from 1 to $n and pipes those into a loop |%{...}. Each iteration we set two helper variables $a and $b and then execute a GCD while loop. Each iteration we're checking that $b is still non-zero, and then saving $a%$b to $b and the previous value of $b to $a for the next loop. We then accumulate whether $a is equal to 1 in our output variable $o. Once the for loop is done, we place $o on the pipeline and output is implicit.

As an example of how the while loop works, consider $n=20 and we're on $_=8. The first check has $b=20, so we enter the loop. We first calculate $a%$b or 8%20 = 8, which gets set to $b at the same time that 20 gets set to $a. Check 8=0, and we enter the second iteration. We then calculate 20%8 = 4 and set that to $b, then set $a to 8. Check 4=0, and we enter the third iteration. We calculate 8%4 = 0 and set that to $b, then set $a to 4. Check 0=0 and we exit the loop, so the GCD(8,20) is $a = 4. Thus, !($a-1) = !(4-1) = !(3) = 0 so $o += 0 and we don't count that one.

Title: Calculate Euler's totient function

Body:
PowerShell v2+, 72 bytes

param($n)1..$n|%{$a=$_;$b=$n;while($b){$a,$b=$b,($a%$b)};$o+=!($a-1)};$o

PowerShell doesn't have a GCD function available to it, so I had to roll my own.

This takes input $n, then ranges from 1 to $n and pipes those into a loop |%{...}. Each iteration we set two helper variables $a and $b and then execute a GCD while loop. Each iteration we're checking that $b is still non-zero, and then saving $a%$b to $b and the previous value of $b to $a for the next loop. We then accumulate whether $a is equal to 1 in our output variable $o. Once the for loop is done, we place $o on the pipeline and output is implicit.

As an example of how the while loop works, consider $n=20 and we're on $_=8. The first check has $b=20, so we enter the loop. We first calculate $a%$b or 8%20 = 8, which gets set to $b at the same time that 20 gets set to $a. Check 8=0, and we enter the second iteration. We then calculate 20%8 = 4 and set that to $b, then set $a to 8. Check 4=0, and we enter the third iteration. We calculate 8%4 = 0 and set that to $b, then set $a to 4. Check 0=0 and we exit the loop, so the GCD(8,20) is $a = 4. Thus, !($a-1) = !(4-1) = !(3) = 0 so $o += 0 and we don't count that one.


答:
Python 2, 278 bytes

```<code>import random
r=5
w=2
s=(0,)*r
while s.count(w)<len(s):
    print ''.join(map(lambda a:str(a),s))+"\n"+'+'*len(s)
    s = tuple(map(lambda x: x<w and x+random.randrange(2) or x,s))
    print ''.join(map(lambda a:str(a), s))+"\n"+'='*len(s)
    s = tuple([x for x in s if x!= w])
</code>```

where r is the no. of racers and w is the score to win

Try it here!

Title: Downward Number Race

Body:
Your task is to create a program that adds random numbers to previous sums in the ultimate number racing showdown.

Each racer (column) starts at 0 and adds either 1 or 0 to the previous sum at each step of the race until all of the racers reach the score required to win. The 1 or 0 should be chosen at random (the standard definition of random can be found here). The output will show the result of the race, with each column representing one racer, in this format:

```<code>>> racers:5,score needed:2

0 0 0 0 0 # all racers start at 0
+ + + + + # add
1 0 0 0 1 # random 1 or 0
= = = = = # equals
1 0 0 0 1 # sum
+ + + + +
0 0 0 0 1
= = = = =
1 0 0 0 2 # winner!
+ + + +
1 1 1 1
= = = =
2 1 1 1
  + + +
  1 1 1
  = = =
  2 2 2   # losers
</code>```

Note: only the numbers, +, and = need to be included in the output.

Input

Your program will accept the following two parameters as input:

the number of racers (columns), which must be greater than two

the score required to win, which must be greater than one

This is code-golf--the program with the least bytes wins.

Edit: there's a non-enforceable max score of 9--this is to preserve the integrity of the column. Also, spaces between columns can be omitted in the output.

Body:
Python 2, 278 bytes

import random
r=5
w=2
s=(0,)*r
while s.count(w)<len(s):
    print ''.join(map(lambda a:str(a),s))+"\n"+'+'*len(s)
    s = tuple(map(lambda x: x<w and x+random.randrange(2) or x,s))
    print ''.join(map(lambda a:str(a), s))+"\n"+'='*len(s)
    s = tuple([x for x in s if x!= w])

where r is the no. of racers and w is the score to win

Try it here!


问:
Rube Goldberg Hello World
For this golf, you will need to use more than one language.

The task

A Rube Goldberg machine is a contraption that takes an enormous number of complicated steps in order to execute a very simple task. The goal of this golf is to output Rube Goldberg... but not directly.

The machine

Your "machine" is the source code that, once executed, will give another source code in another language that will output Rube Goldberg upon execution. Got it?

I rephrase: your initial code must give another code, that other code must output Rube Goldberg. Both codes must be written in different languages.

The bonus which is more like the only fun way to do it

There is a bonus if your code outputs a code that will output a code that will ... that will output Rube Goldberg.

NOTE: any sort of output can be used (stdout, stderr, dialog box, ...)

The points

The number of points is equal to the number of bytes used in your code, divided by the number of distinct, extra languages that you used.

NOTE: different languages use different encodings. The number of bytes is counted in the initial language with its own encoding.

Examples

Pyth -> J -> Javascript -> output in 30 bytes = 30/2 = 15 points (J and Javascript are the extra languages)

Java -> C# -> C++ -> PHP -> output in 36 bytes = 36/3 = 12 points (More bytes and more languages can win over fewer bytes and fewer languages (I know there is no way that these languages do it in 36 bytes))

C -> output in 10 bytes = 10/0 = Infinity points (No extra languages)

Python -> Perl -> Ruby -> Python -> Ruby in 44 bytes = 44/2 = 22 points (Perl and Ruby are the extra languages, the second Python is not counted as it is not an extra language, the second Ruby is not counted as it has already been used)

NOTE: Languages that output their input can't be used. That would be an extra language with absolutely no additional bytes.

The answer

Please provide an answer that clearly states which languages you used and shows us the code at each step (i.e.: in each language).

The winner

Of course, like usual, the lowest score wins.

NOTE: As usual, standard loopholes and "cheats" are not allowed.

答:
MATL -> CJam -> 05AB1E -> Golfscript <s>21/2</s> <s>18/2</s> 22/3

Thanks for Martin for 3 chars off!

```<code>'"''Rube Goldberg''"`'
</code>```

executed in MATL gives

```<code>"''Rube Goldberg''"`
</code>```

which in CJam gives

```<code>"'Rube Goldberg'"
</code>```

which in 05AB1E gives

```<code>'Rube Goldberg'
</code>```

which in Golfscript gives

```<code>Rube Goldberg
</code>```

Title: Rube Goldberg Hello World

Body:
MATL -> CJam -> 05AB1E -> Golfscript <s>21/2</s> <s>18/2</s> 22/3

Thanks for Martin for 3 chars off!

'"''Rube Goldberg''"`'

executed in MATL gives

"''Rube Goldberg''"`

which in CJam gives

"'Rube Goldberg'"

which in 05AB1E gives

'Rube Goldberg'

which in Golfscript gives

Rube Goldberg


答:
Common Lisp, 58 bytes

```<code>(defun o(x)(loop for i from 1 to x if (=(gcd x i)1)sum 1))
</code>```

This is a simple loop which counts up 1 to the given n and increments the sum if gcd = 1. I use the function name o since t is the true boolean value. Not nearly the shortest but fairly simple.

Title: Calculate Euler's totient function

Body:
Background

Euler's totient
function φ(n) is defined as the number of whole numbers less than or equal to n that are relatively prime to n,
that is, the number of possible values of x in 0 < x <= n for which
gcd(n, x) == 1.
We've had
a
few totient-related challenges
before, but never one which is just calculating it.

The mapping of the totient function onto the whole numbers is OEIS A000010.

Challenge

Given an integer n > 0, calculate φ(n).
You may take input through
command-line arguments,
standard input,
function arguments,
or anything else reasonable.
You may give output through
standard output,
return values,
or anything else reasonable.
Anonymous functions are acceptable.
You may assume that the input will not overflow your natural method of storing integers, e.g. int in C, but you must support inputs up to 255.
If your language has a built-in totient function, you may not use it.

Examples

```<code>φ(1) => 1
φ(2) => 1
φ(3) => 2
φ(8) => 4
φ(9) => 6
φ(26) => 12
φ(44) => 20
φ(105) => 48
</code>```

Shortest answer in bytes wins. If your language uses an encoding other than UTF-8, mention it in your answer.

Body:
Common Lisp, 58 bytes

(defun o(x)(loop for i from 1 to x if (=(gcd x i)1)sum 1))

This is a simple loop which counts up 1 to the given n and increments the sum if gcd = 1. I use the function name o since t is the true boolean value. Not nearly the shortest but fairly simple.


答:
Javascript -> PHP -> Foo 14 points

Javascript:

```<code>alert`echo'"Rube Goldberg"'`
</code>```

PHP:

```<code>echo'"Rube Goldberg"'
</code>```

Foo:

```<code>"Rube Goldberg"
</code>```

Title: Rube Goldberg Hello World

Body:
For this golf, you will need to use more than one language.

The task

A Rube Goldberg machine is a contraption that takes an enormous number of complicated steps in order to execute a very simple task. The goal of this golf is to output Rube Goldberg... but not directly.

The machine

Your "machine" is the source code that, once executed, will give another source code in another language that will output Rube Goldberg upon execution. Got it?

I rephrase: your initial code must give another code, that other code must output Rube Goldberg. Both codes must be written in different languages.

The bonus which is more like the only fun way to do it

There is a bonus if your code outputs a code that will output a code that will ... that will output Rube Goldberg.

NOTE: any sort of output can be used (stdout, stderr, dialog box, ...)

The points

The number of points is equal to the number of bytes used in your code, divided by the number of distinct, extra languages that you used.

NOTE: different languages use different encodings. The number of bytes is counted in the initial language with its own encoding.

Examples

Pyth -> J -> Javascript -> output in 30 bytes = 30/2 = 15 points (J and Javascript are the extra languages)

Java -> C# -> C++ -> PHP -> output in 36 bytes = 36/3 = 12 points (More bytes and more languages can win over fewer bytes and fewer languages (I know there is no way that these languages do it in 36 bytes))

C -> output in 10 bytes = 10/0 = Infinity points (No extra languages)

Python -> Perl -> Ruby -> Python -> Ruby in 44 bytes = 44/2 = 22 points (Perl and Ruby are the extra languages, the second Python is not counted as it is not an extra language, the second Ruby is not counted as it has already been used)

NOTE: Languages that output their input can't be used. That would be an extra language with absolutely no additional bytes.

The answer

Please provide an answer that clearly states which languages you used and shows us the code at each step (i.e.: in each language).

The winner

Of course, like usual, the lowest score wins.

NOTE: As usual, standard loopholes and "cheats" are not allowed.

Body:
Javascript -> PHP -> Foo 14 points

Javascript:

alert`echo'"Rube Goldberg"'`

PHP:

echo'"Rube Goldberg"'

Foo:

"Rube Goldberg"


答:
Jolf -> Actually -> Jelly -> Pyth -> Retina -> /// -> Golfscript: 15 / 6 = 2.5 points

5.4 points thanks to Martin Ender.

0.1 points thanks to Cᴏɴᴏʀ O'Bʀɪᴇɴ.

Note: both Actually and Jelly have their own code-page, so they could be transfered byte-by-byte, just not in the Online versions.

Jolf

```<code>aq"“'ẉ'ɠ@ịQCṁỊ»
</code>```

Actually

```<code>"“'ẉ'ɠ@ịQCṁỊ»
</code>```

Try it online!

Jelly

```<code>“'ẉ'ɠ@ịQCṁỊ»
</code>```

Try it online!

Pyth

```<code>k"'Rube Goldberg'/
</code>```

Try it online!

Retina

```

'Rube Goldberg'/
```

Try it online!

///

```<code>'Rube Goldberg'/
</code>```

Try it online!

Golfscript

```<code>'Rube Goldberg'
</code>```

Try it online!

Title: Rube Goldberg Hello World

Body:
Jolf -> Actually -> Jelly -> Pyth -> Retina -> /// -> Golfscript: 15 / 6 = 2.5 points

5.4 points thanks to Martin Ender.

0.1 points thanks to Cᴏɴᴏʀ O'Bʀɪᴇɴ.

Note: both Actually and Jelly have their own code-page, so they could be transfered byte-by-byte, just not in the Online versions.

Jolf

aq"“'ẉ'ɠ@ịQCṁỊ»

Actually

"“'ẉ'ɠ@ịQCṁỊ»

Try it online!

Jelly

“'ẉ'ɠ@ịQCṁỊ»

Try it online!

Pyth

k"'Rube Goldberg'/

Try it online!

Retina

'Rube Goldberg'/

Try it online!

///

'Rube Goldberg'/

Try it online!

Golfscript

'Rube Goldberg'

Try it online!


答:
Python → Ruby → Bash, score: 35 / 2 = 17.5

```<code>print"puts'echo \"Rube Goldberg\"'"
</code>```

when executed in Python, gives

```<code>puts'echo "Rube Goldberg"'
</code>```

with the \"s escaped. Next, this, executed Ruby gives

```<code>echo "Rube Goldberg"
</code>```

and lastly, executing this in Bash gives

```<code>Rube Goldberg
</code>```

which is the expected string.

Title: Rube Goldberg Hello World

Body:
Python → Ruby → Bash, score: 35 / 2 = 17.5

print"puts'echo \"Rube Goldberg\"'"

when executed in Python, gives

puts'echo "Rube Goldberg"'

with the \"s escaped. Next, this, executed Ruby gives

echo "Rube Goldberg"

and lastly, executing this in Bash gives

Rube Goldberg

which is the expected string.


答:
Perl -> JavaScript (ES6) -> Batch -> sh, 39 / 3 = 13 points

Perl

```<code>print 'alert`@echo echo Rube Goldberg`'
</code>```

JavaScript (ES6)

```<code>alert`@echo echo Rube Goldberg`
</code>```

Batch

```<code>@echo echo Rube Goldberg
</code>```

sh

```<code>echo Rube Goldberg
</code>```

Title: Rube Goldberg Hello World

Body:
Perl -> JavaScript (ES6) -> Batch -> sh, 39 / 3 = 13 points

Perl

print 'alert`@echo echo Rube Goldberg`'

JavaScript (ES6)

alert`@echo echo Rube Goldberg`

Batch

@echo echo Rube Goldberg

sh

echo Rube Goldberg


答:
APL → J → K, 21 bytes/2 → 10.5

'''"Rube Goldberg"'''

on Dyalog APL gives

'"Rube Goldberg"'

which in J gives

"Rube Goldberg"

which in K gives

Rube Goldberg

If we allow even closer related languages we can get many more.

Title: Rube Goldberg Hello World


答:
/// -> PowerShell -> CJam -> Foo -> BASH, 24 bytes/4 = 6

```<code>'"echo Rube Goldberg"p'/
</code>```

When executed in /// gives

```<code>'"echo Rube Goldberg"p'
</code>```

which, when executed in PowerShell gives

```<code>"echo Rube Goldberg"p
</code>```

which, when executed in CJam gives

```<code>"echo Rube Goldberg"
</code>```

which, when executed in Foo gives

```<code>echo Rube Goldberg
</code>```

which, when executed in BASH gives

```<code>Rube Goldberg
</code>```

Title: Rube Goldberg Hello World

Body:
/// -> PowerShell -> CJam -> Foo -> BASH, 24 bytes/4 = 6

'"echo Rube Goldberg"p'/

When executed in /// gives

'"echo Rube Goldberg"p'

which, when executed in PowerShell gives

"echo Rube Goldberg"p

which, when executed in CJam gives

"echo Rube Goldberg"

which, when executed in Foo gives

echo Rube Goldberg

which, when executed in BASH gives

Rube Goldberg


Title: Rube Goldberg Hello World

Body:
Python -> Batch -> Javascript -> Java -> PHP -> C++ -> Foo -> Brainfuck 31.(142857) points

Python

print'@echo alert`void f(){System.out.println("echo\"void f(){cout<<\\"\\\\"-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.\\\\"\\"}\""`'

Batch

@echo alert`void f(){System.out.println("echo\"void f(){cout<<\\"\\\\"-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.\\\\"\\"}\""`

JavaScript

alert`void f(){System.out.println("echo\"void f(){cout<<\\"\\\\"-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.\\\\"\\"}\""`

Java

void f(){System.out.println("echo\"void f(){cout<<\\"\\\\"-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.\\\\"\\"}\""

PHP

echo"void f(){cout<<\"\\"-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.\\"\"}"

C++

void f(){cout<<"\"-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.\""}

Foo

"-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------."

BrainFuck

-[--->+<]>---.----[-->+++<]>.+[->+++<]>.+++.--[--->+<]>-.+++[->++<]>+.[--->+<]>++.---.--------.--.+++.+++++++++++++.-----------.


答:
php 121

Not really very much in the way of tricks behind this one.
Flattening an array in php isn't short so it's necessary to build it flat in the first place

```<code><?php for($a=[$b=$argv[1]];$b--;)$a=array_reduce($a,function($r,$v){return array_merge($r,range(1,$v));},[]);print_r($a);
</code>```

Title: Count Up, Replace, Repeat!

Body:
Definition

Define the nth array of the CURR sequence as follows.

Begin with the singleton array A = [n].

For each integer k in A, replace the entry k with k natural numbers, counting up from 1 to k.

Repeat the previous step n - 1 more times.

For example, if n = 3, we start with the array [3].

We replace 3 with 1, 2, 3, yielding [1, 2, 3].

We now replace 1, 2, and 3 with 1; 1, 2 and 1, 2, 3 (resp.), yielding [1, 1, 2, 1, 2, 3].

Finally, we perform the same replacements as in the previous step for all six integers in the array, yielding [1, 1, 1, 2, 1, 1, 2, 1, 2, 3]. This is the third CURR array.

Task

Write a program of a function that, given a strictly positive integer n as input, computes the nth CURR array.

The output has to be a flat list of some kind (and array returned from a function, a string representation of your language's array syntax, whitespace-separated, etc.).

This is code-golf. May the shortest code in bytes win!

Test cases

```<code> 1 -> [1]
 2 -> [1, 1, 2]
 3 -> [1, 1, 1, 2, 1, 1, 2, 1, 2, 3]
 4 -> [1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4]
 5 -> [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5]
 6 -> [1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 1, 2, 1, 1, 2, 1, 2, 3, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6]
</code>```

Body:
php 121

Not really very much in the way of tricks behind this one.
Flattening an array in php isn't short so it's necessary to build it flat in the first place

<?php for($a=[$b=$argv[1]];$b--;)$a=array_reduce($a,function($r,$v){return array_merge($r,range(1,$v));},[]);print_r($a);