问:
Generate n digits of Gijswijt's sequence

Introduction

Gijswijt's sequence (A090822) is famously really, REALLY slow. To illustrate:

The first 3 appears in the 9th term (alright).

The first 4 appears in the 220th term (a long way away, but feasible).

The first 5 appears at (approximately) the 10^(10^23)th term (just no).

No one really even knows where the first 6 is... it's suspected it's at the...

2^(2^(3^(4^5)))th term.

You can assume that you won't have to deal with a two-digit number.

The sequence is generated like so:

The first term is 1.

Each term after that is the amount of repeating "blocks" previous to it (if there are multiple repeating "blocks", the largest amount of repeating blocks is used).

To clarify, here are the first few terms.

1 -> 1, 1 (one repeating block (1), so the digit recorded is 1)

1, 1 -> 1, 1, 2 (two repeating blocks (1), so the digit recorded is 2)

1, 1, 2 -> 1, 1, 2, 1 (one repeating block (2 or 1, 1, 2), so the digit recorded is 1)

1, 1, 2, 1 -> 1, 1, 2, 1, 1 (you get the idea)

1, 1, 2, 1, 1 -> 1, 1, 2, 1, 1, 2

1, 1, 2, 1, 1, 2 -> 1, 1, 2, 1, 1, 2, 2 (two repeating blocks (1, 1, 2), so the digit recorded is 2)

Task

Your task is, as stated in the question, to generate n digits of the Gijswijt sequence.

Instructions

The input will be an integer n.

Your code can output the digits in any form (a list, multiple outputs, etc.).

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

答:
Retina, <s>66</s> 60 bytes

```<code>+1`((\d+)?(?<1>\2)*(?<!\3(?>(?<-1>\3)*)(?!.*\2)(.+)))!
$1$#1
</code>```

Input is a unary integer using ! as the digit (although that could be changed to any other non-numeric character). Output is simply a string of digits.

Try it online! (Alternatively, for convenience here's a version that takes decimal input.)

For testing purposes, this can be sped up a lot with a small modification, which allows testing of input 220 in under a minute:

```<code>+1`((\d+)?(?<1>\2)*(?=!)(?<!\3(?>(?<-1>\3)*)(?!.*\2)(.+)))!
$1$#1
</code>```

Try it online! (Decimal version.)

If you want to test even larger numbers, it's best to just feed it some massive input and put a : after the initial +. This will make Retina print the current sequence each time it finishes computing a new digit (with all the digits off-by-one).

Explanation

The solution consists of a single regex substitution, which is applied to the input repeatedly until the result stops changing, which in this case happens because the regex no longer matches. The + at the beginning introduces this loop. The 1 is a limit which tells Retina only to replace the first match (this is only relevant for the very first iteration). In each iteration, the stage replaces one ! (from the left) with the next digit of the sequence.

As usual, if you need a primer on balancing groups I refer you to my SO answer.

Here is an annotated version of the regex. Note that the goal is to capture the maximum number of repeated blocks in group 1.

```<code>(                 # Group 1, this will contain some repeated block at the end
                  # of the existing sequence. We mainly need this so we can
                  # write it back in the substitution. We're also abusing it
                  # for the actual counting but I'll explain that below.
  (\d+)?          # If possible (that is except on the first iteration) capture
                  # one of more digits into group 2. This is a candidate block
                  # which we're checking for maximum repetitions. Note that this
                  # will match the *first* occurrence of the block.
  (?<1>\2)*       # Now we capture as many copies of that block as possible
                  # into group 1. The reason we use group 1 is that this captures
                  # one repetition less than there is in total (because the first
                  # repetition is group 2 itself). Together with the outer
                  # (unrelated) capture of the actual group one, we fix this
                  # off-by-one error. More importantly, this additional capture
                  # from the outer group isn't added until later, such that the
                  # lookbehind which comes next doesn't see it yet, which is
                  # actually very useful.
                  # Before we go into the lookbehind note that at the end of the
                  # regex there's a '!' to ensure that we can actually reach the
                  # end of the string with this repetition of blocks. While this
                  # isn't actually checked until later, we can essentially assume
                  # that the lookbehind is only relevant if we've actually counted
                  # repetitions of a block at the end of the current sequence.

  (?<!            # We now use a lookbehind to ensure that this is actually the
                  # largest number of repetitions possible. We do this by ensuring
                  # that there is no shorter block which can be matched more
                  # often from the end than the current one. The first time this
                  # is true (since, due to the regex engine's backtracking rules,
                  # we start from longer blocks and move to shorter blocks later),
                  # we know we've found the maximum number of repetitions.
                  # Remember that lookbehinds are matched right-to-left, so
                  # you should read the explanation of the lookbehind from
                  # bottom to top.
    \3            # Try to match *another* occurrence of block 3. If this works,
                  # then this block can be used more often than the current one
                  # and we haven't found the maximum number of repetitions yet.
    (?>           # An atomic group to ensure that we're actually using up all
                  # repetitions from group 1, and don't backtrack.
      (?<-1>\3)*  # For each repetition in group 1, try to match block 3 again.
    )
    (?!.*\2)      # We ensure that this block isn't longer than the candidate
                  # block, by checking that the candidate block doesn't appear
                  # right of it.
    (.+)          # We capture a block from the end into group 3.
  )               # Lookbehind explanation starts here. Read upwards.
)
!                 # As I said above, this ensures that our block actually reaches
                  # the end of the string.
</code>```

Finally, after this is all done, we write back $1 (thereby deleting the !) as well as the number of captures in the group with $#1 which corresponds to the maximum number of repetitions.

Body:
Retina, <s>66</s> 60 bytes

+1`((\d+)?(?<1>\2)*(?<!\3(?>(?<-1>\3)*)(?!.*\2)(.+)))!
$1$#1

Input is a unary integer using ! as the digit (although that could be changed to any other non-numeric character). Output is simply a string of digits.

Try it online! (Alternatively, for convenience here's a version that takes decimal input.)

For testing purposes, this can be sped up a lot with a small modification, which allows testing of input 220 in under a minute:

+1`((\d+)?(?<1>\2)*(?=!)(?<!\3(?>(?<-1>\3)*)(?!.*\2)(.+)))!
$1$#1

Try it online! (Decimal version.)

If you want to test even larger numbers, it's best to just feed it some massive input and put a : after the initial +. This will make Retina print the current sequence each time it finishes computing a new digit (with all the digits off-by-one).

Explanation

The solution consists of a single regex substitution, which is applied to the input repeatedly until the result stops changing, which in this case happens because the regex no longer matches. The + at the beginning introduces this loop. The 1 is a limit which tells Retina only to replace the first match (this is only relevant for the very first iteration). In each iteration, the stage replaces one ! (from the left) with the next digit of the sequence.

As usual, if you need a primer on balancing groups I refer you to my SO answer.

Here is an annotated version of the regex. Note that the goal is to capture the maximum number of repeated blocks in group 1.

(                 # Group 1, this will contain some repeated block at the end
                  # of the existing sequence. We mainly need this so we can
                  # write it back in the substitution. We're also abusing it
                  # for the actual counting but I'll explain that below.
  (\d+)?          # If possible (that is except on the first iteration) capture
                  # one of more digits into group 2. This is a candidate block
                  # which we're checking for maximum repetitions. Note that this
                  # will match the *first* occurrence of the block.
  (?<1>\2)*       # Now we capture as many copies of that block as possible
                  # into group 1. The reason we use group 1 is that this captures
                  # one repetition less than there is in total (because the first
                  # repetition is group 2 itself). Together with the outer
                  # (unrelated) capture of the actual group one, we fix this
                  # off-by-one error. More importantly, this additional capture
                  # from the outer group isn't added until later, such that the
                  # lookbehind which comes next doesn't see it yet, which is
                  # actually very useful.
                  # Before we go into the lookbehind note that at the end of the
                  # regex there's a '!' to ensure that we can actually reach the
                  # end of the string with this repetition of blocks. While this
                  # isn't actually checked until later, we can essentially assume
                  # that the lookbehind is only relevant if we've actually counted
                  # repetitions of a block at the end of the current sequence.

  (?<!            # We now use a lookbehind to ensure that this is actually the
                  # largest number of repetitions possible. We do this by ensuring
                  # that there is no shorter block which can be matched more
                  # often from the end than the current one. The first time this
                  # is true (since, due to the regex engine's backtracking rules,
                  # we start from longer blocks and move to shorter blocks later),
                  # we know we've found the maximum number of repetitions.
                  # Remember that lookbehinds are matched right-to-left, so
                  # you should read the explanation of the lookbehind from
                  # bottom to top.
    \3            # Try to match *another* occurrence of block 3. If this works,
                  # then this block can be used more often than the current one
                  # and we haven't found the maximum number of repetitions yet.
    (?>           # An atomic group to ensure that we're actually using up all
                  # repetitions from group 1, and don't backtrack.
      (?<-1>\3)*  # For each repetition in group 1, try to match block 3 again.
    )
    (?!.*\2)      # We ensure that this block isn't longer than the candidate
                  # block, by checking that the candidate block doesn't appear
                  # right of it.
    (.+)          # We capture a block from the end into group 3.
  )               # Lookbehind explanation starts here. Read upwards.
)
!                 # As I said above, this ensures that our block actually reaches
                  # the end of the string.

Finally, after this is all done, we write back $1 (thereby deleting the !) as well as the number of captures in the group with $#1 which corresponds to the maximum number of repetitions.


问:
Transform a matrix
Write a program or function where a matrix A (maximum value of dimensions of the matrix is 100) is transformed to a new matrix B. Each element of the new matrix B is the sum of the positive neighbors of the corresponding element of the matrix A.

Only neighbors in the four orthogonal directions are considered, and the edges do not wrap around.

Example input:

```<code> 1  2  3
 4 -1 -2
-3 -4 10
 1  2 10
</code>```

Output:

```<code> 6  4  2
 1  6 13
 5 12 10
 2 11 12
</code>```

Rules:

As input use integers.

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

答:
Pyth, 36 bytes

```<code>Lm+Vt+d0+0dbJmm/+.akk2dQ.b+VNYyJCyCJ
</code>```

Try it online!

Direct translation of my answer in Jelly.

ContentLicense: CC BY-SA 3.0

Title: Transform a matrix

Body:
Pyth, 36 bytes

Lm+Vt+d0+0dbJmm/+.akk2dQ.b+VNYyJCyCJ

Try it online!

Direct translation of my answer in Jelly.


问:
Draw a simple cube
We don't have a single challenge about drawing a real 3 dimensional cube, so here it goes:

Challenge

Your task is to draw a rotated, cube with perspective. It can be in a separate window or as an image.

Input

Your input is 3 separate numbers between 0 and 359.99... These represent the rotation around the x, y and z axis in degrees.

```<code>0 0 0
30 0 40
95 320 12
</code>```

Output

You can either display it in a separate window or save an image. You can use any type of display (vector based, rasterized, etc.).

Edit: ASCII is allowed too, to allow golfing languages with only textual output.

The output for rasterized or ASCII graphics must be at least 50*50 (pixels for rasterization, characters for ASCII)

Additional information

The positive z axis points out from the window, the x axis is horizontal, and the y axis is vertical. Basically the OpenGL standard.

Rotations are counter-clockwise if you look at the cube in the negative direction of a specific axis, e.g looking down for the y axis.

The camera should be on the z axis at a reasonable distance from the cube in the negative z direction, the cube should be at (0;0;0). The. cube also needs to be fully visible, and take up at least 50% of the drawing frame. The camera should look in the positive z direction at the cube.

The rotations of the cube get applied in the x->y->z order.

The cube is rotated around it's center, it doesn't move.

To project a cube in 2d space, you need to divide the x and y coordinates of the cube with the distance parallel to the z-axis between the point and the camera.

Rules

Rendering libraries are allowed, but the vertices need to be defined in the code. No 3d cube model class.

Test cases

答:
Maple, <s>130+14</s> (in progress)

```<code>with(plots):f:=(X,Y,Z)->plot3d(0,x=0..1,y=0..1,style=contour,tickmarks=[0,0,0],labels=["","",""],axes=boxed,orientation=[Z,-X,Y]);
</code>```

This plots a constant function inside a box, then uses plot options to hide ticks, labels and the function itself. Adding projection=.5 to the options brings the camera closer, enabling perspective view.

I wrote this before the specs were finalized and the rotation order is x, y', z'' instead of x, y, z. Until I fix the angles, here is another solution

POV-Ray, 182

```<code>#include"a.txt"
#include"shapes.inc"
camera{location 9*z look_at 0}
light_source{9*z color 1}
object{Wire_Box(<-2,-2,-2>,<2,2,2>,.01,0)texture{pigment{color rgb 1}}rotate<R.x,-R.y,-R.z>}
</code>```

reads input through the a.txt file which should contain

#declare R=<xx,yy,zz>;

with xx,yy,zz being the rotation angles

Title: Draw a simple cube

Body:
Maple, <s>130+14</s> (in progress)

with(plots):f:=(X,Y,Z)->plot3d(0,x=0..1,y=0..1,style=contour,tickmarks=[0,0,0],labels=["","",""],axes=boxed,orientation=[Z,-X,Y]);

This plots a constant function inside a box, then uses plot options to hide ticks, labels and the function itself. Adding projection=.5 to the options brings the camera closer, enabling perspective view.

I wrote this before the specs were finalized and the rotation order is x, y', z'' instead of x, y, z. Until I fix the angles, here is another solution

POV-Ray, 182

#include"a.txt"
#include"shapes.inc"
camera{location 9*z look_at 0}
light_source{9*z color 1}
object{Wire_Box(<-2,-2,-2>,<2,2,2>,.01,0)texture{pigment{color rgb 1}}rotate<R.x,-R.y,-R.z>}

reads input through the a.txt file which should contain

#declare R=<xx,yy,zz>;

with xx,yy,zz being the rotation angles


答:
Haskell, 97 bytes

```<code>f 1=[1]
f n|x<-f$n-1=last[k|k<-[1..n],p<-[1..n],k*p<n,take(k*p)x==([1..k]>>take p x)]:x
reverse.f
</code>```

The third line defines an anonymous function that takes an integer and returns a list of integers.
See it in action.

Explanation

The helper function f constructs the sequence in reverse, by recursively checking whether the previous sequence begins with a repeated block.
k is the number of repetitions, and p is the length of the block.

```<code>f 1=[1]                                   -- Base case: return [1]
f n|x<-f$n-1=                             -- Recursive case; bind f(n-1) to x.
  last[k|k<-[1..n],                       -- Find the greatest element k of [1..n] such that
  p<-[1..n],                              -- there exists a block length p such that
  k*p<n,                                  -- k*p is at most the length of x, and
  take(k*p)x                              -- the prefix of x of length p*k
    ==                                    -- is equal to
  ([1..k]>>take p x)                      -- the prefix of length p repeated k times.
  ]:x                                     -- Insert that k to x, and return the result.
reverse.f                                 -- Composition of reverse and f.
</code>```

Title: Generate n digits of Gijswijt's sequence

Body:
Introduction

Gijswijt's sequence (A090822) is famously really, REALLY slow. To illustrate:

The first 3 appears in the 9th term (alright).

The first 4 appears in the 220th term (a long way away, but feasible).

The first 5 appears at (approximately) the 10^(10^23)th term (just no).

No one really even knows where the first 6 is... it's suspected it's at the...

2^(2^(3^(4^5)))th term.

You can assume that you won't have to deal with a two-digit number.

The sequence is generated like so:

The first term is 1.

Each term after that is the amount of repeating "blocks" previous to it (if there are multiple repeating "blocks", the largest amount of repeating blocks is used).

To clarify, here are the first few terms.

1 -> 1, 1 (one repeating block (1), so the digit recorded is 1)

1, 1 -> 1, 1, 2 (two repeating blocks (1), so the digit recorded is 2)

1, 1, 2 -> 1, 1, 2, 1 (one repeating block (2 or 1, 1, 2), so the digit recorded is 1)

1, 1, 2, 1 -> 1, 1, 2, 1, 1 (you get the idea)

1, 1, 2, 1, 1 -> 1, 1, 2, 1, 1, 2

1, 1, 2, 1, 1, 2 -> 1, 1, 2, 1, 1, 2, 2 (two repeating blocks (1, 1, 2), so the digit recorded is 2)

Task

Your task is, as stated in the question, to generate n digits of the Gijswijt sequence.

Instructions

The input will be an integer n.

Your code can output the digits in any form (a list, multiple outputs, etc.).

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

Body:
Haskell, 97 bytes

f 1=[1]
f n|x<-f$n-1=last[k|k<-[1..n],p<-[1..n],k*p<n,take(k*p)x==([1..k]>>take p x)]:x
reverse.f

The third line defines an anonymous function that takes an integer and returns a list of integers.
See it in action.

Explanation

The helper function f constructs the sequence in reverse, by recursively checking whether the previous sequence begins with a repeated block.
k is the number of repetitions, and p is the length of the block.

f 1=[1]                                   -- Base case: return [1]
f n|x<-f$n-1=                             -- Recursive case; bind f(n-1) to x.
  last[k|k<-[1..n],                       -- Find the greatest element k of [1..n] such that
  p<-[1..n],                              -- there exists a block length p such that
  k*p<n,                                  -- k*p is at most the length of x, and
  take(k*p)x                              -- the prefix of x of length p*k
    ==                                    -- is equal to
  ([1..k]>>take p x)                      -- the prefix of length p repeated k times.
  ]:x                                     -- Insert that k to x, and return the result.
reverse.f                                 -- Composition of reverse and f.


问:
Shortest Unique Substring
Given (on STDIN, as command line arguments, or as function arguments) two distinct non-empty strings, find and return the shortest substring of the first string which is not a substring of the second. If no such substring exists, you may return the empty string, return any string which isn't a substring of the original string, or throw an exception. If you are returning from a function, you may also return null (or undefined, None, etc.) in this case. If multiple such substrings are tied for the shortest, you may return any one of them.

Strings can consist of any printable ascii characters.

Input given on STDIN will be given with one string on each line. At your request, a single empty line may be added at the end of the input.

This is code golf, so the shortest valid program wins.

SOME TEST CASES

INPUT:

```<code>STRING ONE
STRING TWO
</code>```

OUTPUT:

```<code>E
</code>```

INPUT:

```<code>A&&C
A&$C
</code>```

VALID OUTPUTS:

```<code>&&
&C
</code>```

INPUT:

(Two randomly-generated 80-letter strings)

```<code>QIJYXPYWIWESWBRFWUHEERVQFJROYIXNKPKVDDFFZBUNBRZVUEYKLURBJCZJYMINCZNQEYKRADRYSWMH
HAXUDFLYFSLABUCXUWNHPSGQUXMQUIQYRWVIXGNKJGYUTWMLLPRIZDRLFXWKXOBOOEFESKNCUIFHNLFE
</code>```

ALL VALID OUTPUTS:

```<code>AD
BJ
BR
CZ
DD
EE
ER
EY
EY
FF
FJ
FW
FZ
HE
IJ
IN
IW
JC
JR
JY
KL
KP
KR
KV
LU
MH
MI
NB
NQ
OY
PK
PY
QE
QF
QI
RA
RB
RF
RO
RV
RY
RZ
SW
UE
UH
UN
UR
VD
VQ
VU
WB
WE
WI
WU
XN
XP
YI
YK
YK
YM
YS
YW
YX
ZB
ZJ
ZN
ZV
</code>```

答:
Brachylog, 23 bytes

```<code>:1foh.,{,.[A:B]hs?'~sB}
</code>```

Works on the old Java transpiler. Expects the two strings in a list as input, unifies the output with the substring. If no substring is found, returns false.

Unfortunately I have not yet coded the subset built-in in the new Prolog transpiler.

Explanation

```<code>:1f               Find all bindings which satisfy predicate 1 with that binding as input and
                  with the Input of the main predicate as output.
   oh.,           Order that list of bindings, and unify the output with the first one.

{
 ,.[A:B]          Unify the output with the list [A,B]
        hs?       Unify the input with a subset of A
           '~sB   Check that no subset of B can be unified with the input
               }
</code>```

Title: Shortest Unique Substring

Body:
Brachylog, 23 bytes

:1foh.,{,.[A:B]hs?'~sB}

Works on the old Java transpiler. Expects the two strings in a list as input, unifies the output with the substring. If no substring is found, returns false.

Unfortunately I have not yet coded the subset built-in in the new Prolog transpiler.

Explanation

:1f               Find all bindings which satisfy predicate 1 with that binding as input and
                  with the Input of the main predicate as output.
   oh.,           Order that list of bindings, and unify the output with the first one.

{
 ,.[A:B]          Unify the output with the list [A,B]
        hs?       Unify the input with a subset of A
           '~sB   Check that no subset of B can be unified with the input
               }


答:
Pyth, 11 bytes

```<code>Jwhf!}TJ.:z
</code>```

Try it online!

Title: Shortest Unique Substring

Body:
Given (on STDIN, as command line arguments, or as function arguments) two distinct non-empty strings, find and return the shortest substring of the first string which is not a substring of the second. If no such substring exists, you may return the empty string, return any string which isn't a substring of the original string, or throw an exception. If you are returning from a function, you may also return null (or undefined, None, etc.) in this case. If multiple such substrings are tied for the shortest, you may return any one of them.

Strings can consist of any printable ascii characters.

Input given on STDIN will be given with one string on each line. At your request, a single empty line may be added at the end of the input.

This is code golf, so the shortest valid program wins.

SOME TEST CASES

INPUT:

```<code>STRING ONE
STRING TWO
</code>```

OUTPUT:

```<code>E
</code>```

INPUT:

```<code>A&&C
A&$C
</code>```

VALID OUTPUTS:

```<code>&&
&C
</code>```

INPUT:

(Two randomly-generated 80-letter strings)

```<code>QIJYXPYWIWESWBRFWUHEERVQFJROYIXNKPKVDDFFZBUNBRZVUEYKLURBJCZJYMINCZNQEYKRADRYSWMH
HAXUDFLYFSLABUCXUWNHPSGQUXMQUIQYRWVIXGNKJGYUTWMLLPRIZDRLFXWKXOBOOEFESKNCUIFHNLFE
</code>```

ALL VALID OUTPUTS:

```<code>AD
BJ
BR
CZ
DD
EE
ER
EY
EY
FF
FJ
FW
FZ
HE
IJ
IN
IW
JC
JR
JY
KL
KP
KR
KV
LU
MH
MI
NB
NQ
OY
PK
PY
QE
QF
QI
RA
RB
RF
RO
RV
RY
RZ
SW
UE
UH
UN
UR
VD
VQ
VU
WB
WE
WI
WU
XN
XP
YI
YK
YK
YM
YS
YW
YX
ZB
ZJ
ZN
ZV
</code>```

Body:
Pyth, 11 bytes

Jwhf!}TJ.:z

Try it online!


答:
Python, <s>119</s> <s>115</s> 91

lambda a,b:[a[m:m+n]for n in range(1,len(a)+1)for m in range(len(a))if a[m:m+n]not in b][0]
```
<p>Test cases:</p>
<pre class="lang-python prettyprint-override"><code>| Input 1  | Input 2     | Output        |
|----------+-------------+---------------|
| 'abcd'   | 'abc'       |  'd'          |
| 'abcd'   | 'dabc'      |  'cd'         |
| 'abcd'   | 'dcbabbccd' |  'abc'        |
| 'abcdf'  | 'abcdebcdf' |  'abcdf'      |
| 'abc'    | 'abc'       |  (IndexError) |
</code>```

Working on making it shorter, but this is my brain instinct. Not really much of a golfer yet.

Thanks to @user81655 and @NonlinearFruit for the extra bytes.

Edit:

Dang. Tried this code:

def z(a,b):
 for s in [a[m:m+n]for n in range(1,len(a)+1)for m in range(len(a)-n+1)]:
  if s not in b:return s
 return''
```

Thought it was a few bytes shorter. Turns out it was 1 byte longer than what I had before the edit.

Title: Shortest Unique Substring

Body:
Python, <s>119</s> <s>115</s> 91

lambda a,b:[a[m:m+n]for n in range(1,len(a)+1)for m in range(len(a))if a[m:m+n]not in b][0]

Test cases:

| Input 1  | Input 2     | Output        |
|----------+-------------+---------------|
| 'abcd'   | 'abc'       |  'd'          |
| 'abcd'   | 'dabc'      |  'cd'         |
| 'abcd'   | 'dcbabbccd' |  'abc'        |
| 'abcdf'  | 'abcdebcdf' |  'abcdf'      |
| 'abc'    | 'abc'       |  (IndexError) |

Working on making it shorter, but this is my brain instinct. Not really much of a golfer yet.

Thanks to @user81655 and @NonlinearFruit for the extra bytes.

Edit:

Dang. Tried this code:

def z(a,b):
 for s in [a[m:m+n]for n in range(1,len(a)+1)for m in range(len(a)-n+1)]:
  if s not in b:return s
 return''

Thought it was a few bytes shorter. Turns out it was 1 byte longer than what I had before the edit.

ContentLicense: CC BY-SA 4.0


答:
JavaScript (Firefox), 80 bytes

solution=

a=>b=>[for(_ of(i=0,a))for(_ of(j=!++i,a))if(b.includes(s=a.substr(j++,i)))s][0]

document.write("```"+
[ [ "test", "best" ], [ "wes", "west" ], [ "red", "dress" ] ]
.map(c=>c+": "+solution(c[0])(c[1])).join`\n`)</code>```

Test works only in Firefox. Returns undefined if there is no substring.

Title: Shortest Unique Substring

Body:
JavaScript (Firefox), 80 bytes

solution=

a=>b=>[for(_ of(i=0,a))for(_ of(j=!++i,a))if(b.includes(s=a.substr(j++,i)))s][0]

document.write("<pre>"+
[ [ "test", "best" ], [ "wes", "west" ], [ "red", "dress" ] ]
.map(c=>c+": "+solution(c[0])(c[1])).join`\n`)

Test works only in Firefox. Returns undefined if there is no substring.


问:
Run through an array
We all often hear the idiom "walk through the array" to mean "map the function over the following array". However, I need it done (now!), so I want you to run through the array.

How do I run?

Imagine there's a wild pack of wolves behind you

Running through an array is like walking through one, except you  can skip over elements. Yes, it's sometimes messy, but it (generally) works. "Which elements are skipped?", you may ask. Well, this is done at random. Let's walk through running through the array!

Let e be the current element.

Let random generate a random float in [0,1). If random() < 0.5, then you go the next element and then to step 1. (You may generate a number by other means, so long as their is an (ideally) equal chance of skipping and remaining. E.g., you can use choose an element from a two-member set and perform the action based on the result.)

Otherwise, you perform function f on e.

Objective

Given an array/list/string like either A and a number K, run through the array, adding K to each member accessed. Output/return this array. A will only contain non-negative integers, and K will only ever be a non-negative integers. This is a code-golf, so the shortest program in bytes wins.

Test cases (examples)

```<code>K, A => possible K'
[1, 2, 3, 4], 0 => [1, 2, 3, 4]
[1, 2, 3, 4], 1 => [1, 3, 3, 5]
[0, 0, 0, 0], 2 => [2, 0, 0, 2]
</code>```

Title: Run through an array

Body:
JavaScript (ES6), 38 bytes

solution=

a=>k=>a.map(n=>Math.random()<.5?n:n+k)

document.write("<pre>"+
[ [[1,2,3,4], 0], [[1,2,3,4], 1], [[0,0,0,0], 2], [[4,22,65,32,91,46,18], 42] ]
.map(c=>"["+c[0]+"],"+c[1]+": "+solution(c[0])(c[1])).join`\n`)


答:
Pyth, 7

```<code>m+*O2vz
</code>```

Try it here

Uses a random choice instead of floating point comparison, but should be indistinguishable.

Expansion:

```<code>m+*O2vz     ## implicitly, a d and Q are added to the end of the program
m+*O2vzdQ   ## Q = eval(input()), z= input()
m           ## map over each element d of Q
 +     d    ## add to d
  *O2vz     ## the product of eval(z) and a random number chosen from [0, 1]
</code>```

Using floating point:

```<code>m+*<.5O0vz
</code>```

Try it here

Title: Run through an array

Body:
We all often hear the idiom "walk through the array" to mean "map the function over the following array". However, I need it done (now!), so I want you to run through the array.

How do I run?

Imagine there's a wild pack of wolves behind you

Running through an array is like walking through one, except you  can skip over elements. Yes, it's sometimes messy, but it (generally) works. "Which elements are skipped?", you may ask. Well, this is done at random. Let's walk through running through the array!

Let e be the current element.

Let random generate a random float in [0,1). If random() < 0.5, then you go the next element and then to step 1. (You may generate a number by other means, so long as their is an (ideally) equal chance of skipping and remaining. E.g., you can use choose an element from a two-member set and perform the action based on the result.)

Otherwise, you perform function f on e.

Objective

Given an array/list/string like either A and a number K, run through the array, adding K to each member accessed. Output/return this array. A will only contain non-negative integers, and K will only ever be a non-negative integers. This is a code-golf, so the shortest program in bytes wins.

Test cases (examples)

```<code>K, A => possible K'
[1, 2, 3, 4], 0 => [1, 2, 3, 4]
[1, 2, 3, 4], 1 => [1, 3, 3, 5]
[0, 0, 0, 0], 2 => [2, 0, 0, 2]
</code>```

Body:
Pyth, 7

m+*O2vz

Try it here

Uses a random choice instead of floating point comparison, but should be indistinguishable.

Expansion:

m+*O2vz     ## implicitly, a d and Q are added to the end of the program
m+*O2vzdQ   ## Q = eval(input()), z= input()
m           ## map over each element d of Q
 +     d    ## add to d
  *O2vz     ## the product of eval(z) and a random number chosen from [0, 1]

Using floating point:

m+*<.5O0vz

Try it here


答:
Python 2, <s>60</s> 58 bytes

from random import*
lambda a,k:[e+choice([0,k])for e in a]
```

<p>This program turned out really simple. There aren't many golfing tricks in there, apart from the the obvious "<code>from module import*</code>", using a lambda instead of a regular function and the general lack of whitespace. Other than that it's actually quite idiomatic. If I was writing this for real I'd probably do it in a very similar way:</p>

<pre class="lang-py prettyprint-override"><code>import random
def running_addition(seq, k):
    return [e + random.choice([0, k]) for e in seq]
</code>```

Or perhaps something more fancy:

import random
import operator
import functools

def run_through(seq, func):
    def random_func(arg):
        if random.randint(0, 1):
            return func(arg)
        return arg

    return [random_func(e) for e in seq]

def running_addition(seq, k):
    return run_through(seq, functools.partial(operator.add, k))
```

<p>But that's enough showing off :)</p>

<p>This is the old, 60 byte version from when using a float for randomness was required:</p>

<pre class="lang-py prettyprint-override"><code>from random import*
lambda a,k:[e+k*(random()<.5)for e in a]
</code>```

For each element of the list, add k*(random()<.5). Python booleans evaluate to 0 and 1, so this adds 0 to any elements for which the condition isn't true.

Python's random.random() returns floats in [0, 1), so I didn't have to worry about that.

Title: Run through an array

Body:
Python 2, <s>60</s> 58 bytes

from random import*
lambda a,k:[e+choice([0,k])for e in a]

This program turned out really simple. There aren't many golfing tricks in there, apart from the the obvious "from module import*", using a lambda instead of a regular function and the general lack of whitespace. Other than that it's actually quite idiomatic. If I was writing this for real I'd probably do it in a very similar way:

import random
def running_addition(seq, k):
    return [e + random.choice([0, k]) for e in seq]

Or perhaps something more fancy:

import random
import operator
import functools

def run_through(seq, func):
    def random_func(arg):
        if random.randint(0, 1):
            return func(arg)
        return arg

    return [random_func(e) for e in seq]

def running_addition(seq, k):
    return run_through(seq, functools.partial(operator.add, k))

But that's enough showing off :)

This is the old, 60 byte version from when using a float for randomness was required:

from random import*
lambda a,k:[e+k*(random()<.5)for e in a]

For each element of the list, add k*(random()<.5). Python booleans evaluate to 0 and 1, so this adds 0 to any elements for which the condition isn't true.

Python's random.random() returns floats in [0, 1), so I didn't have to worry about that.


问:
Find the repetend of the decimal representation!
In this challenge 2 years ago, we found the period of a unit fraction (1/n where n is a natural number).

Now, your task is to write a program/function to find the repetend of a unit fraction.

The repetend is the part of the decimal expansion which repeats infinitely, like:

The decimal representation of 1/6 is 0.16666..., then the repetend is 6.

The decimal representation of 1/11 is 0.090909..., then the repetend is 09.

The decimal representation of 1/28 is 0.0357142857142857142857..., then the repetend is 571428.

Specs

Input in any reasonable format.

Output the repetend in decimal, string or list.

For 1/7 (0.142857142857...), you must output 142857 instead of 428571.

For 1/13 (0.076923076923076923...), you must output 076923 instead of 76923.

No brute force, please.

Testcases

```<code>Input    Output
1        0
2        0
3        3
7        142857
13       076923
17       0588235294117647
28       571428
70       142857
98       102040816326530612244897959183673469387755
9899     000101020305081321345590463683200323264976260228305889483786241034447924032730578846348115971310233356904737852308313971108192746742095161127386604707546216789574704515607637135064147893726639054449944438832205273259925244974239822204263056874431760783917567431053641781998181634508536215779371653702394181230427315890493989291847661379937367410849580765733912516415799575714718658450348520052530558642287099707041115264168097787655318719062531568845337912920497019901
</code>```

Scoring

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

No answer would be accepted, because the goal is not to find the language capable of producing the shortest solution, but the shortest solution in each language.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Java, 150 bytes:

String p(int n){int a=1,p;String r="";for(;n%10<1;n/=10);for(;n%2<1;n/=2)a*=5;for(;n%5<1;n/=5)a*=2;for(p=a%=n;;){p*=10;r+=p/n;if(a==(p%=n))return r;}}
```

<h3>Added whitespace:</h3>

<pre class="lang-java prettyprint-override"><code>String p(int n){
    int a=1,p;
    String r="";
    for(;n%10<1;n/=10);
    for(;n%2<1;n/=2)
        a*=5;
    for(;n%5<1;n/=5)
        a*=2;
    for(p=a%=n;;){
        p*=10;
        r+=p/n;
        if(a==(p%=n))
            return r;
    }
}
</code>```

Ungolfed, full program:

import java.util.Scanner;

public class A036275 {
    public static String period(int a,int n){
        if(n%10==0) return period(a,n/10);
        if(n%2==0) return period(a*5,n/2);
        if(n%5==0) return period(a*2,n/5);
        a %= n;
        int pow = a;
        String period = "";
        while(true){
            pow *= 10;
            period += pow/n;
            pow %= n;
            if(pow == a){
                return period;
            }
        }
    }
    public static String period(int n){
        return period(1,n);
    }
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.close();
        System.out.println(period(n));
    }
}
```

Body:
Java, 150 bytes:

String p(int n){int a=1,p;String r="";for(;n%10<1;n/=10);for(;n%2<1;n/=2)a*=5;for(;n%5<1;n/=5)a*=2;for(p=a%=n;;){p*=10;r+=p/n;if(a==(p%=n))return r;}}

Added whitespace:

String p(int n){
    int a=1,p;
    String r="";
    for(;n%10<1;n/=10);
    for(;n%2<1;n/=2)
        a*=5;
    for(;n%5<1;n/=5)
        a*=2;
    for(p=a%=n;;){
        p*=10;
        r+=p/n;
        if(a==(p%=n))
            return r;
    }
}

Ungolfed, full program:

import java.util.Scanner;

public class A036275 {
    public static String period(int a,int n){
        if(n%10==0) return period(a,n/10);
        if(n%2==0) return period(a*5,n/2);
        if(n%5==0) return period(a*2,n/5);
        a %= n;
        int pow = a;
        String period = "";
        while(true){
            pow *= 10;
            period += pow/n;
            pow %= n;
            if(pow == a){
                return period;
            }
        }
    }
    public static String period(int n){
        return period(1,n);
    }
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.close();
        System.out.println(period(n));
    }
}


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

From 8 to 7 thanks to @FryAmTheEggman.

```<code>+2X’¤¡€
</code>```

Try it online!

Explanation

```<code>+2X’¤¡€
      €   Map over each argument...
 2X           Choose a random number from {1,2}
   ’          Minus 1
    ¤                (grammar stuff)
     ¡        Repeat that number of times...
+                 Add the second input (to the argument being mapped over).
</code>```

Title: Run through an array

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

From 8 to 7 thanks to @FryAmTheEggman.

+2X’¤¡€

Try it online!

Explanation

+2X’¤¡€
      €   Map over each argument...
 2X           Choose a random number from {1,2}
   ’          Minus 1
    ¤                (grammar stuff)
     ¡        Repeat that number of times...
+                 Add the second input (to the argument being mapped over).


答:
Java <s>108</s> <s>107</s> <s>85</s> 82 bytes

```<code>void f(int[]s,int k){for(int i:s)System.out.print((i+=Math.random()<.5?k:0)+";");}
</code>```

14 bytes saved thanks to @TimmyD

Title: Run through an array

Body:
Java <s>108</s> <s>107</s> <s>85</s> 82 bytes

void f(int[]s,int k){for(int i:s)System.out.print((i+=Math.random()<.5?k:0)+";");}

14 bytes saved thanks to @TimmyD


答:
MATL, 11 bytes

```<code>tZy1$rEki*+
</code>```

Uses floating point random numbers.

Try it online!

Explanation

```<code>t      % implicit input (array). Duplicate
Zy     % size (array specifying number of rows and columns)
1$r    % random vector between 0 and 1 with that size
Ek     % duplicate, round down: gives 0 or 1 with the same probability
i      % input (number K to be added)
*      % multiply: gives either 0 or K for each element
+      % add element-wise
</code>```

Title: Run through an array

Body:
MATL, 11 bytes

tZy1$rEki*+

Uses floating point random numbers.

Try it online!

Explanation

t      % implicit input (array). Duplicate
Zy     % size (array specifying number of rows and columns)
1$r    % random vector between 0 and 1 with that size
Ek     % duplicate, round down: gives 0 or 1 with the same probability
i      % input (number K to be added)
*      % multiply: gives either 0 or K for each element
+      % add element-wise


答:
Python, <s>87</s> 86 bytes

```<code>lambda s,t,e=enumerate:[s[i:i-~j]for j,_ in e(s)for i,_ in e(s)if(s[i:i-~j]in t)<1][0]
</code>```

If it exists, this will return the leftmost of all shortest unique substrings.

If there is no unique substring, an IndexError is raised.

Test it on Ideone.

Title: Shortest Unique Substring

Body:
Python, <s>87</s> 86 bytes

lambda s,t,e=enumerate:[s[i:i-~j]for j,_ in e(s)for i,_ in e(s)if(s[i:i-~j]in t)<1][0]

If it exists, this will return the leftmost of all shortest unique substrings.

If there is no unique substring, an IndexError is raised.

Test it on Ideone.


答:
HTML/CSS/JS, 739 bytes, probably non-competing

But I just wanted to show off CSS 3D transforms.

w=_=>o.style.transform=`rotateZ(${z.value}deg) rotateY(${y.value}deg) rotateX(${-x.value}deg)````
<pre class="snippet-code-css lang-css prettyprint-override"><code>input {
  width: 5em;
}

#c{width:90px;height:90px;margin:90px;position:relative;perspective:180px}#o{position:absolute;width:90px;height:90px;transform-style:preserve-3d;transform-origin:45px 45px 0px;}#o *{position:absolute;width:90px;height:90px;border:2px solid black}#f{transform:translateZ(45px)}#b{transform:rotateX(180deg)translateZ(45px)}#r{transform:rotateY(90deg)translateZ(45px)}#l{transform:rotateY(-90deg)translateZ(45px)}#u{transform:rotateX(90deg)translateZ(45px)}#d{transform:rotateX(-90deg)translateZ(45px)}</code>```

  X:<input id="x" type="number" value="0" min="0" max="360">
  Y:<input id="y" type="number" value="0" min="0" max="360">
  Z:<input id="z" type="number" value="0" min="0" max="360">

```

Title: Draw a simple cube

Body:
We don't have a single challenge about drawing a real 3 dimensional cube, so here it goes:

Challenge

Your task is to draw a rotated, cube with perspective. It can be in a separate window or as an image.

Input

Your input is 3 separate numbers between 0 and 359.99... These represent the rotation around the x, y and z axis in degrees.

```<code>0 0 0
30 0 40
95 320 12
</code>```

Output

You can either display it in a separate window or save an image. You can use any type of display (vector based, rasterized, etc.).

Edit: ASCII is allowed too, to allow golfing languages with only textual output.

The output for rasterized or ASCII graphics must be at least 50*50 (pixels for rasterization, characters for ASCII)

Additional information

The positive z axis points out from the window, the x axis is horizontal, and the y axis is vertical. Basically the OpenGL standard.

Rotations are counter-clockwise if you look at the cube in the negative direction of a specific axis, e.g looking down for the y axis.

The camera should be on the z axis at a reasonable distance from the cube in the negative z direction, the cube should be at (0;0;0). The. cube also needs to be fully visible, and take up at least 50% of the drawing frame. The camera should look in the positive z direction at the cube.

The rotations of the cube get applied in the x->y->z order.

The cube is rotated around it's center, it doesn't move.

To project a cube in 2d space, you need to divide the x and y coordinates of the cube with the distance parallel to the z-axis between the point and the camera.

Rules

Rendering libraries are allowed, but the vertices need to be defined in the code. No 3d cube model class.

Test cases

Body:
HTML/CSS/JS, 739 bytes, probably non-competing

But I just wanted to show off CSS 3D transforms.

w=_=>o.style.transform=`rotateZ(${z.value}deg) rotateY(${y.value}deg) rotateX(${-x.value}deg)`

input {
  width: 5em;
}

#c{width:90px;height:90px;margin:90px;position:relative;perspective:180px}#o{position:absolute;width:90px;height:90px;transform-style:preserve-3d;transform-origin:45px 45px 0px;}#o *{position:absolute;width:90px;height:90px;border:2px solid black}#f{transform:translateZ(45px)}#b{transform:rotateX(180deg)translateZ(45px)}#r{transform:rotateY(90deg)translateZ(45px)}#l{transform:rotateY(-90deg)translateZ(45px)}#u{transform:rotateX(90deg)translateZ(45px)}#d{transform:rotateX(-90deg)translateZ(45px)}

<div oninput=w()>
  X:<input id="x" type="number" value="0" min="0" max="360">
  Y:<input id="y" type="number" value="0" min="0" max="360">
  Z:<input id="z" type="number" value="0" min="0" max="360">
</div>
<!-- Above code for ease of use of snippet. Golfed version: <div oninput=w()><input id=x><input id=y><input id=z></div> -->

<div id=c><div id=o><div id=f></div><div id=b></div><div id=r></div><div id=l></div><div id=u></div><div id=d>


答:
Pyth, 63 bytes

```<code>W!%QT=/QT;J*F+1-PQ,2 5K%*F+1-L7@,2 5PQJ=NKW1=+k/=*NTJIqK=%NJB;k
</code>```

Try it online!

Direct translation of the answer in Java.

Title: Find the repetend of the decimal representation!

Body:
In this challenge 2 years ago, we found the period of a unit fraction (1/n where n is a natural number).

Now, your task is to write a program/function to find the repetend of a unit fraction.

The repetend is the part of the decimal expansion which repeats infinitely, like:

The decimal representation of 1/6 is 0.16666..., then the repetend is 6.

The decimal representation of 1/11 is 0.090909..., then the repetend is 09.

The decimal representation of 1/28 is 0.0357142857142857142857..., then the repetend is 571428.

Specs

Input in any reasonable format.

Output the repetend in decimal, string or list.

For 1/7 (0.142857142857...), you must output 142857 instead of 428571.

For 1/13 (0.076923076923076923...), you must output 076923 instead of 76923.

No brute force, please.

Testcases

```<code>Input    Output
1        0
2        0
3        3
7        142857
13       076923
17       0588235294117647
28       571428
70       142857
98       102040816326530612244897959183673469387755
9899     000101020305081321345590463683200323264976260228305889483786241034447924032730578846348115971310233356904737852308313971108192746742095161127386604707546216789574704515607637135064147893726639054449944438832205273259925244974239822204263056874431760783917567431053641781998181634508536215779371653702394181230427315890493989291847661379937367410849580765733912516415799575714718658450348520052530558642287099707041115264168097787655318719062531568845337912920497019901
</code>```

Scoring

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

No answer would be accepted, because the goal is not to find the language capable of producing the shortest solution, but the shortest solution in each language.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Pyth, 63 bytes

W!%QT=/QT;J*F+1-PQ,2 5K%*F+1-L7@,2 5PQJ=NKW1=+k/=*NTJIqK=%NJB;k

Try it online!

Direct translation of the answer in Java.


答:
PowerShell v2+, 34 bytes

```<code>param($a,$k)$a|%{$_+$k*(random 2)}
</code>```

Takes input $a and $k, the array and the int respectively. We then loop through the array and each loop iteration output the current element plus $k times (random 2) which will execute Get-Random -Maximum 2 (i.e., either a 0 or a 1). These are all left on the pipeline and output as an array is implicit.

Title: Run through an array

Body:
PowerShell v2+, 34 bytes

param($a,$k)$a|%{$_+$k*(random 2)}

Takes input $a and $k, the array and the int respectively. We then loop through the array and each loop iteration output the current element plus $k times (random 2) which will execute Get-Random -Maximum 2 (i.e., either a 0 or a 1). These are all left on the pipeline and output as an array is implicit.


答:
CJam, 10 bytes

```<code>{f{2mr*+}}
</code>```

Expects the array and the number on top of the stack in that order and replaces them with the new array.

Test it here.

Title: Run through an array

Body:
CJam, 10 bytes

{f{2mr*+}}

Expects the array and the number on top of the stack in that order and replaces them with the new array.

Test it here.


答:
Julia, <s>33</s> <s>29</s> 27 bytes

x->k->x+rand(0:1,endof(x))k
```

This is an anonymous function that accepts an array with an inner anonymous function that accepts an integer and returns an array. To call it, assign it to a variable and call like f(x)(k).

We generate an array with the same length as the input array consisting of zeros and ones chosen at random with equal probability. We multiply this by the input integer and add that to the input array.

Try it online!

Saved 2 bytes thanks to Dennis!

Title: Run through an array

Body:
Julia, <s>33</s> <s>29</s> 27 bytes

x->k->x+rand(0:1,endof(x))k

This is an anonymous function that accepts an array with an inner anonymous function that accepts an integer and returns an array. To call it, assign it to a variable and call like f(x)(k).

We generate an array with the same length as the input array consisting of zeros and ones chosen at random with equal probability. We multiply this by the input integer and add that to the input array.

Try it online!

Saved 2 bytes thanks to Dennis!


答:
JavaScript (ES6), 79 bytes

f=
(a,b)=>[...a].some((_,i,c)=>c.some((_,j)=>b.indexOf(s=a.substr(j,i+1))<0))?s:''```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div oninput=o.textContent=f(a.value,b.value)><input id="a"/><input id="b"/><pre id=o></code>```

If returning false is acceptable, save 2 bytes by using &&s instead of ?s:''.

Title: Shortest Unique Substring

Body:
Given (on STDIN, as command line arguments, or as function arguments) two distinct non-empty strings, find and return the shortest substring of the first string which is not a substring of the second. If no such substring exists, you may return the empty string, return any string which isn't a substring of the original string, or throw an exception. If you are returning from a function, you may also return null (or undefined, None, etc.) in this case. If multiple such substrings are tied for the shortest, you may return any one of them.

Strings can consist of any printable ascii characters.

Input given on STDIN will be given with one string on each line. At your request, a single empty line may be added at the end of the input.

This is code golf, so the shortest valid program wins.

SOME TEST CASES

INPUT:

```<code>STRING ONE
STRING TWO
</code>```

OUTPUT:

```<code>E
</code>```

INPUT:

```<code>A&&C
A&$C
</code>```

VALID OUTPUTS:

```<code>&&
&C
</code>```

INPUT:

(Two randomly-generated 80-letter strings)

```<code>QIJYXPYWIWESWBRFWUHEERVQFJROYIXNKPKVDDFFZBUNBRZVUEYKLURBJCZJYMINCZNQEYKRADRYSWMH
HAXUDFLYFSLABUCXUWNHPSGQUXMQUIQYRWVIXGNKJGYUTWMLLPRIZDRLFXWKXOBOOEFESKNCUIFHNLFE
</code>```

ALL VALID OUTPUTS:

```<code>AD
BJ
BR
CZ
DD
EE
ER
EY
EY
FF
FJ
FW
FZ
HE
IJ
IN
IW
JC
JR
JY
KL
KP
KR
KV
LU
MH
MI
NB
NQ
OY
PK
PY
QE
QF
QI
RA
RB
RF
RO
RV
RY
RZ
SW
UE
UH
UN
UR
VD
VQ
VU
WB
WE
WI
WU
XN
XP
YI
YK
YK
YM
YS
YW
YX
ZB
ZJ
ZN
ZV
</code>```

Body:
JavaScript (ES6), 79 bytes

f=
(a,b)=>[...a].some((_,i,c)=>c.some((_,j)=>b.indexOf(s=a.substr(j,i+1))<0))?s:''

<div oninput=o.textContent=f(a.value,b.value)><input id="a"/><input id="b"/><pre id=o>

If returning false is acceptable, save 2 bytes by using &&s instead of ?s:''.


答:
CJam, 26

```<code>riL{_XW$%A*:X|X@-}g_X#>\f/
</code>```

Try it online

Explanation:

The program builds a series of dividends involved in the calculation of the decimal expansion, until it finds a dividend it has seen before. Then it takes all the dividends starting with that one, and divides them by n to get the digits of the repetend.

```<code>ri       read the input and convert to integer (n)
L        push an empty array (will add the dividends to it)
{…}g     do … while
  _      copy the current array of dividends
  X      push the latest dividend (initially 1 by default)
  W$     copy n from the bottom of the stack
  %A*    calculate X mod n and multiply by 10
  :X     store in X (this is the next dividend)
  |      perform set union with the array of dividends
  X@     push X and bring the old array to the top
  -      set difference; it is empty iff the old array already contained X
          this becomes the do-while loop condition
_X#      duplicate the array of dividends and find the position of X
>        take all dividends from that position
\f/      swap the array with n and divide all dividends by n
</code>```

Body:
CJam, 26

riL{_XW$%A*:X|X@-}g_X#>\f/

Try it online

Explanation:

The program builds a series of dividends involved in the calculation of the decimal expansion, until it finds a dividend it has seen before. Then it takes all the dividends starting with that one, and divides them by n to get the digits of the repetend.

ri       read the input and convert to integer (n)
L        push an empty array (will add the dividends to it)
{…}g     do … while
  _      copy the current array of dividends
  X      push the latest dividend (initially 1 by default)
  W$     copy n from the bottom of the stack
  %A*    calculate X mod n and multiply by 10
  :X     store in X (this is the next dividend)
  |      perform set union with the array of dividends
  X@     push X and bring the old array to the top
  -      set difference; it is empty iff the old array already contained X
          this becomes the do-while loop condition
_X#      duplicate the array of dividends and find the position of X
>        take all dividends from that position
\f/      swap the array with n and divide all dividends by n


答:
Pyth - <s>9</s> 6 bytes

```<code>h-Fm.:
</code>```

Try it online here.

Title: Shortest Unique Substring

Body:
Pyth - <s>9</s> 6 bytes

h-Fm.:

Try it online here.


答:
Retina, 37 bytes

```<code>M!&`\G(.+?)(?!.*¶.*\1)
O$#`.+
$.&
G1`
</code>```

Output is empty if no valid substring is found in A.

Try it online! (Slightly modified to run several test cases at once. The input format is actually linefeed separated, but test suites are easiest to write with one test case per line. The test framework turns the space into a linefeed before the actual code starts.)

Explanation

```<code>M!&`\G(.+?)(?!.*¶.*\1)
</code>```

For each possible starting position in A, match the shortest substring which does not appear in B. The & is for overlapping matches, such that we actually try every starting position, even if a match is longer than one character. The \G ensures that we don't skip any positions - in particular, this way we have to stop at the linefeed, such that we don't get additional matches from B itself. The reason this doesn't mess things up is actually quite subtle: because if there's a starting position in A where we can't find any valid substring, then that's also a failure which will cause \G to stop checking any further positions. However, if (from the current starting position) all substrings appear in B, so will all substrings that start further right of the current position, so discarding those is not an issue (and actually improves performance).

Due to the M! configuration, all of these matches will be returned from the stage, joined with linefeeds.

```<code>O$#`.+
$.&
</code>```

This sorts the lines of the previous result by length. This is done by matching the line with .+. Then $ activates a form of "sort-by", such that the match is substituted with $.& for determining sort order. The $.& itself replaces the match with its length. Finally, the # option tells Retina to sort numerically (otherwise, it would treat the resulting numbers as strings and sort them lexicographically).

```<code>G1`
</code>```

Finally, we simply keep only first line, by using a grep stage with an empty regex (which always matches) and a limit of 1.

Title: Shortest Unique Substring

Body:
Retina, 37 bytes

M!&`\G(.+?)(?!.*¶.*\1)
O$#`.+
$.&
G1`

Output is empty if no valid substring is found in A.

Try it online! (Slightly modified to run several test cases at once. The input format is actually linefeed separated, but test suites are easiest to write with one test case per line. The test framework turns the space into a linefeed before the actual code starts.)

Explanation

M!&`\G(.+?)(?!.*¶.*\1)

For each possible starting position in A, match the shortest substring which does not appear in B. The & is for overlapping matches, such that we actually try every starting position, even if a match is longer than one character. The \G ensures that we don't skip any positions - in particular, this way we have to stop at the linefeed, such that we don't get additional matches from B itself. The reason this doesn't mess things up is actually quite subtle: because if there's a starting position in A where we can't find any valid substring, then that's also a failure which will cause \G to stop checking any further positions. However, if (from the current starting position) all substrings appear in B, so will all substrings that start further right of the current position, so discarding those is not an issue (and actually improves performance).

Due to the M! configuration, all of these matches will be returned from the stage, joined with linefeeds.

O$#`.+
$.&

This sorts the lines of the previous result by length. This is done by matching the line with .+. Then $ activates a form of "sort-by", such that the match is substituted with $.& for determining sort order. The $.& itself replaces the match with its length. Finally, the # option tells Retina to sort numerically (otherwise, it would treat the resulting numbers as strings and sort them lexicographically).

G1`

Finally, we simply keep only first line, by using a grep stage with an empty regex (which always matches) and a limit of 1.


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

Title: ASCII Art Mayan Numerals

Body:
JavaScript (ES6), 254 bytes

f=(n,r=(s,n=19)=>s.repeat(n))=>(n>19?f(n/5>>2)+`

`:``)+(n%5?`${r(s=` ----  `,n%5)}
${t=r(`|    | `,n%5)}
${t}
${s}
`:``)+r(`${s=r(`-`,32)}
|${r(` `,30)}|
${s}
`,n/5&3)+(n%20?``:` ${s=r(`-`)}
${t=r(`|    `,4)}|
${t}|
|${s}|
|${t=r(` `)}|
|${t}|
 ${s}
`)


答:
C#, 152 bytes

string f(string a,string b){int x=a.Length;for(int i=1;i<=x;i++)for(int j=0;j<=x-i;j++){var y=a.Substring(j,i);if(!b.Contains(y))return y;}return null;}
```

Title: Shortest Unique Substring


答:
Clojure, <s>41</s> 37 bytes

```<code>(fn[a k](map #(+(*(rand-int 2)k)%)a))
</code>```

Knocked off a couple of bytes by multiplying by 0 or 1 and dropping the "if". Credit to most all of the other submitters!

Title: Run through an array

Body:
We all often hear the idiom "walk through the array" to mean "map the function over the following array". However, I need it done (now!), so I want you to run through the array.

How do I run?

Imagine there's a wild pack of wolves behind you

Running through an array is like walking through one, except you  can skip over elements. Yes, it's sometimes messy, but it (generally) works. "Which elements are skipped?", you may ask. Well, this is done at random. Let's walk through running through the array!

Let e be the current element.

Let random generate a random float in [0,1). If random() < 0.5, then you go the next element and then to step 1. (You may generate a number by other means, so long as their is an (ideally) equal chance of skipping and remaining. E.g., you can use choose an element from a two-member set and perform the action based on the result.)

Otherwise, you perform function f on e.

Objective

Given an array/list/string like either A and a number K, run through the array, adding K to each member accessed. Output/return this array. A will only contain non-negative integers, and K will only ever be a non-negative integers. This is a code-golf, so the shortest program in bytes wins.

Test cases (examples)

```<code>K, A => possible K'
[1, 2, 3, 4], 0 => [1, 2, 3, 4]
[1, 2, 3, 4], 1 => [1, 3, 3, 5]
[0, 0, 0, 0], 2 => [2, 0, 0, 2]
</code>```

Body:
Clojure, <s>41</s> 37 bytes

(fn[a k](map #(+(*(rand-int 2)k)%)a))

Knocked off a couple of bytes by multiplying by 0 or 1 and dropping the "if". Credit to most all of the other submitters!


问:
Crash IRB (interactive Ruby)
Ruby comes with a built-in REPL, which is quite handy.

Your challenge is to crash it in the least amount of code!

The definition of "crash" is "make it exit in an unintended way." This means exit, quit, abort, irb_exit, irb_quit, et. al. are not valid answers.

Furthermore, you may not cause any side-effect to any other part of the system. For example, `rm -rf /` is not valid either.

Any version 1.9.3 or above is valid. If your code only works on a specific version of Ruby, you may specify that in the answer.

The final restriction is that you may not rely on any gems.

This is code-golf, so the shortest code that crashes IRB will win!

答:
5 characters

```<code>$>=$<
</code>```

Sets stdout to stdin which throws an error trying to open stdin for writing and crashes irb.

Title: Crash IRB (interactive Ruby)

Body:
5 characters

$>=$<

Sets stdout to stdin which throws an error trying to open stdin for writing and crashes irb.


答:
Jelly, <s>12</s> 10 bytes

```<code>%³×⁵
1ÇÐḶ:
</code>```

Saved 2 bytes by keeping track of dividends, an idea I took from @aditsu's CJam answer.

Try it online!

How it works

```<code>%³×⁵     Helper link. Argument: d (dividend)

%³       Yield the remainder of the division of d by n.
  ×⁵     Multiply by 10.

1ÇÐḶ:    Main link. Argument: n

1        Yield 1 (initial dividend).
 ÇÐḶ     Apply the helper link until its results are no longer unique.
         Yield the loop, i.e., everything from the first repeated result
         up to and including the last unique one.
    :    Divide each dividend by n.
</code>```

Body:
Jelly, <s>12</s> 10 bytes

%³×⁵
1ÇÐḶ:

Saved 2 bytes by keeping track of dividends, an idea I took from @aditsu's CJam answer.

Try it online!

How it works

%³×⁵     Helper link. Argument: d (dividend)

%³       Yield the remainder of the division of d by n.
  ×⁵     Multiply by 10.

1ÇÐḶ:    Main link. Argument: n

1        Yield 1 (initial dividend).
 ÇÐḶ     Apply the helper link until its results are no longer unique.
         Yield the loop, i.e., everything from the first repeated result
         up to and including the last unique one.
    :    Divide each dividend by n.


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

答:
Racket

We have Clojure (the Java among LISPs), and Common Lisp (C), but where are Scheme (x86 asm) and <s>more</s> most importantly Racket (Python)?? :o

Racket is like the Python of LISPs. Common Lisp seems old (it's older than FORTRAN!), and Scheme seems boring, academic, and comes with a too-sparse standard library.

On the other hand, Racket is a batteries-included, industry-ready Scheme, that's fun to learn and use every day.

Factoid

In most other LISPs, () is the empty list. However, Racket's syntax is minorly deviant in that '() is the empty list and () is an illegal empty application (that is, the application of nothing to nothing, which makes no sense).

Length 1

```<code>λ
</code>```

Other people have been counting chars not bytes so I'll use this two byte unicode glyph: U+03BB GREEK SMALL LETTER LAMBDA. This is synonymous with the lambda keyword for creating anonymous functions, which is excellent for golf because otherwise, you'd need to (define (name args...) exprs...) which is longer. (Of course, Racket isn't very golfy otherwise.)

Length 2

```<code>#f
</code>```

False. #t is for true, and so is everything that's not #f, much like other functional languages, and much to the dismay of every imperative programmer ever.

Length 3

```<code>let
</code>```

Another keyword. (Still no executable code.) This one is an integral part of any LISP; it lets us define local variables and procedures.

A let form looks like:

```<code>(let ([a 1]
      [b 2])
    (displayln a)  ;; 1
    (displayln b)) ;; 2
(displayln a)      ;; error, a is not defined
</code>```

Or like:

```<code>(let loop ([a 1])
    (displayln a)
    (loop (+ 1 a)))
</code>```

That counts up forever, and will not cause a stack overflow because Racket is tail-recursive, like any compliant Scheme.

Length 4

```<code>cadr
</code>```

One of my favourite things about Racket is this:

Now, car is the LISPism for Current Address Register, or the first item of a pair. LISP lists are singly linked lists like so:

```<code>'(1 2 3)
;; is actually
(cons 1 (cons 2 (cons 3 null)))
(car cdr = (car cdr = (car cdr = null)))
;; i.e.
struct Node { int data; Node* next; };
</code>```

Each item in the list is actually some data, and (a pointer to)another list, which is (a pointer to)another list, which is a... yeah.

To get the cdr (Current Decrement Register) of a given cons cell you use... the cdr function.

How to get the second item in a list? (car (cdr xs)). Or: cadr.

How to get the third item in a list? (car (cdr (cdr xs))). Or: caddr.

How to get the fourth item in a list? (car (cdr (cdr (cdr xs)))). Or: cadddr.

See where this is going? Not often are these actually used over numeric indexing, but they are  very handy.

Title: Showcase of Languages

Body:
Racket

We have Clojure (the Java among LISPs), and Common Lisp (C), but where are Scheme (x86 asm) and <s>more</s> most importantly Racket (Python)?? :o

Racket is like the Python of LISPs. Common Lisp seems old (it's older than FORTRAN!), and Scheme seems boring, academic, and comes with a too-sparse standard library.

On the other hand, Racket is a batteries-included, industry-ready Scheme, that's fun to learn and use every day.

Factoid

In most other LISPs, () is the empty list. However, Racket's syntax is minorly deviant in that '() is the empty list and () is an illegal empty application (that is, the application of nothing to nothing, which makes no sense).

Length 1

λ

Other people have been counting chars not bytes so I'll use this two byte unicode glyph: U+03BB GREEK SMALL LETTER LAMBDA. This is synonymous with the lambda keyword for creating anonymous functions, which is excellent for golf because otherwise, you'd need to (define (name args...) exprs...) which is longer. (Of course, Racket isn't very golfy otherwise.)

Length 2

#f

False. #t is for true, and so is everything that's not #f, much like other functional languages, and much to the dismay of every imperative programmer ever.

Length 3

let

Another keyword. (Still no executable code.) This one is an integral part of any LISP; it lets us define local variables and procedures.

A let form looks like:

(let ([a 1]
      [b 2])
    (displayln a)  ;; 1
    (displayln b)) ;; 2
(displayln a)      ;; error, a is not defined

Or like:

(let loop ([a 1])
    (displayln a)
    (loop (+ 1 a)))

That counts up forever, and will not cause a stack overflow because Racket is tail-recursive, like any compliant Scheme.

Length 4

cadr

One of my favourite things about Racket is this:

Now, car is the LISPism for Current Address Register, or the first item of a pair. LISP lists are singly linked lists like so:

'(1 2 3)
;; is actually
(cons 1 (cons 2 (cons 3 null)))
(car cdr = (car cdr = (car cdr = null)))
;; i.e.
struct Node { int data; Node* next; };

Each item in the list is actually some data, and (a pointer to)another list, which is (a pointer to)another list, which is a... yeah.

To get the cdr (Current Decrement Register) of a given cons cell you use... the cdr function.

How to get the second item in a list? (car (cdr xs)). Or: cadr.

How to get the third item in a list? (car (cdr (cdr xs))). Or: caddr.

How to get the fourth item in a list? (car (cdr (cdr (cdr xs)))). Or: cadddr.

See where this is going? Not often are these actually used over numeric indexing, but they are  very handy.


答:
Octave, 28 bytes

```<code>@(A,R)R*(rand(size(A))<.5)+A
</code>```

Sample run on ideone.

Title: Run through an array

Body:
Octave, 28 bytes

@(A,R)R*(rand(size(A))<.5)+A

Sample run on ideone.


答:
05AB1E, 10 bytes

Code:

```<code>vždÉ²*y+})
</code>```

Try it online!.

Title: Run through an array

Body:
05AB1E, 10 bytes

Code:

vždÉ²*y+})

Try it online!.


答:
Python 3 152 110 98 bytes

This is my first code golf solution so I don't know any tricks. I tested this using a main function with test cases. The file size is only this function.

```<code>from random import*
def a(x,y):
 p=0
 for z in x:
  if random()>.5:x[p]=z+y
  p+=1
 print(x)
</code>```

Thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ for the advice on removing whitespace. Additional praise to @undergroundmonorail for advice that saved 12 bytes.

Title: Run through an array

Body:
Python 3 152 110 98 bytes

This is my first code golf solution so I don't know any tricks. I tested this using a main function with test cases. The file size is only this function.

from random import*
def a(x,y):
 p=0
 for z in x:
  if random()>.5:x[p]=z+y
  p+=1
 print(x)

Thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ for the advice on removing whitespace. Additional praise to @undergroundmonorail for advice that saved 12 bytes.


答:
GameMaker Language, 152 bytes

Based on Kenny's answer

```<code>n=argument0;a=1r=0while(n mod 2<1){a*=5n/=2}while(n mod 5<1){a*=2n/=5}a=a mod n;p=a;while(1){p*=10r=r*10+p/n;r=r mod $5f5e107;p=p mod n;if(a=p)return r}
</code>```

Body:
In this challenge 2 years ago, we found the period of a unit fraction (1/n where n is a natural number).

Now, your task is to write a program/function to find the repetend of a unit fraction.

The repetend is the part of the decimal expansion which repeats infinitely, like:

The decimal representation of 1/6 is 0.16666..., then the repetend is 6.

The decimal representation of 1/11 is 0.090909..., then the repetend is 09.

The decimal representation of 1/28 is 0.0357142857142857142857..., then the repetend is 571428.

Specs

Input in any reasonable format.

Output the repetend in decimal, string or list.

For 1/7 (0.142857142857...), you must output 142857 instead of 428571.

For 1/13 (0.076923076923076923...), you must output 076923 instead of 76923.

No brute force, please.

Testcases

```<code>Input    Output
1        0
2        0
3        3
7        142857
13       076923
17       0588235294117647
28       571428
70       142857
98       102040816326530612244897959183673469387755
9899     000101020305081321345590463683200323264976260228305889483786241034447924032730578846348115971310233356904737852308313971108192746742095161127386604707546216789574704515607637135064147893726639054449944438832205273259925244974239822204263056874431760783917567431053641781998181634508536215779371653702394181230427315890493989291847661379937367410849580765733912516415799575714718658450348520052530558642287099707041115264168097787655318719062531568845337912920497019901
</code>```

Scoring

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

No answer would be accepted, because the goal is not to find the language capable of producing the shortest solution, but the shortest solution in each language.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
GameMaker Language, 152 bytes

Based on Kenny's answer

n=argument0;a=1r=0while(n mod 2<1){a*=5n/=2}while(n mod 5<1){a*=2n/=5}a=a mod n;p=a;while(1){p*=10r=r*10+p/n;r=r mod $5f5e107;p=p mod n;if(a=p)return r}


答:
Ruby, 28 bytes

```<code>->a,k{a.map{|e|e+k*rand(2)}}
</code>```

Title: Run through an array

Body:
Ruby, 28 bytes

->a,k{a.map{|e|e+k*rand(2)}}


问:
Survival Game - Create Your Wolf

The Board

The Board is a two dimensional array of cells. Cells are populated by Animals. Every day, all Animals on the Board simultaneously make one move. If two or more Animals move to the same cell, they fight until one remains. The possible moves and attacks are as follows:

Moves - { Move.UP, Move.RIGHT, Move.DOWN, Move.LEFT, Move.HOLD }

Attacks - { Attack.ROCK, Attack.PAPER, Attack.SCISSORS, Attack.SUICIDE }

Animals fight by playing Rock-Paper-Scissors. Standard rules apply but with two modifications. First, you may commit suicide at any time. Second, a tie is broken pseudorandomly. If more than two Animals collide, two are pseudorandomly selected to fight until one remains.

The Players

Animal behavior and appearance is as follows.

Lion

Represented by the character L. Moves DOWN, RIGHT, then repeats. Pseudorandomly attacks with PAPER or SCISSORS.

Bear

Represented by the character B. Moves DOWN x 4, RIGHT x 4, UP x 4, LEFT x 4, then repeats. Attacks with PAPER.

Stone

Represented by the character S. Moves HOLD. Attacks with ROCK.

Wolf

Only wolves that are submitted as an answer will be included. Represented by 'W'. Moves with any Move. Attacks with any Attack

You will implement the Wolf by filling in the blanks in the following template. All submissions must be in Java and must be contained in a single file. Alternatively, @ProgrammerDan has written a wrapper class that extends the competition to non-java submissions.

// Optional code here
public class Wolf extends Animal {
    // Optional code here
    public Wolf() { super('W'); /* Optional code here */ }
    public Attack fight(char opponent) { /* Required code here. Must return an Attack. */ }
    public Move move() { /* Required code here. Must return a Move. */ }
    // Optional code here
}
```

The submission with the highest average number of living wolves after five trials with 1,000 iterations wins. I will update the winner each time a new answer is posted (but not within the first 24 hours).

Tools

You are provided with a small map of your immediate surroundings in the following form.

char[][] surroundings A zero indexed, 3 by 3 matrix of characters that represent nearby animals. Empty tiles are represented by a space character (' '). You are at surroundings[1][1]. For example, to your right would be surroundings[1][2], and above you is surroundings[0][1]. Your surroundings are updated just before being asked to move, but may be out of date when asked to fight.

You may persist data between invocations of your Wolf, Move requests, and Attack requests. You may neither read from nor modify files created by another Wolf class.

You are provided with the size of the map in the following form

int MAP_SIZE

Assumptions

All submission will compete on the same board against all other submissions as well as Lions, Bears, and Stones

The board is a square with sides of length sqrt(n+3)*20 where n is the number of submissions. All sides wrap, so you can safely move in any direction infinitely.

Simulation begins at ~25% board capacity with 100 of each Animal pseudorandomly distributed across the board.

If an Animal throws an exception when asked to move, that Animal will HOLD

If an Animal throws an exception when asked to fight, that Animal will SUICIDE

If an Animal has no letter when the controller checks, that Animal will immediately die

Getting Started and Testing Instructions

The tools you need to test your submission can be found here. The following files should be available at that link.

ExampleRun.gif - A 5-10 second gif of the program running.

Scoreboard - The latest results of the competition.

Wild.jar - An executable that you can run to watch the premade Animals run around.

Wild.zip - The NetBeans project that houses the controller program with a few premade Animals added. Use this to develop your submission.

WildPopulated.zip - Same as above, but with and about 40 submissions added for you to test against. The GUI has also been removed because of performance issues. The results will simply appear a few moments after you run. The non-Java submissions are commented out because they require extra downloads and effort. Use this to test your submission against the field.

Wolf.txt -  A naive implementation of the Wolf class in Java. You may use and expand that implementation without crediting me.

To test your class:

Download Wild.zip

Rename your Wolf.java and Wolf class to something unique

Add your UniquelyNamedWolf.java file to Wild\src\animals\

In the Wild class, add your class to classes array, like this.

Class[] classes = { UniquelyNamedWolf.class, Bear.class, Lion.class, Stone.class, Wolf.class };

Rebuild and run

I also included another project containing all of the submissions, for testing purposes. I creatively named it "WildPopulated". The three or four non-Java wolves were commented out, because getting them to run requires a lot of extra work and downloads. The one I posted should run with zero extra work. The GUI was also commented out for the sake of speed.

Scoreboard April 22, 2014

The Scoreboard has been moved to Google Drive. View it here. It will be updated on a casual basis (i.e., when I get to it) as new submissions come in.

Side Challenge - NoHOLD

Removed because no (as in zero) participation. It wasn't part of the original challenge anyway.

答:
PsychoWolf

```<code>import java.lang.reflect.Field;
import java.util.Random;

public class PsychoWolf extends Animal {
    private int tracker = 0;

    public PsychoWolf() {
        super('W');
        try {
            Field field = Math.class.getDeclaredField("randomNumberGenerator");
            field.setAccessible(true);
            field.set(null, new Random() {
                public double nextDouble() {
                    return 0;
                }
            });
        } catch (RuntimeException | NoSuchFieldException
                | IllegalAccessException e) {

        }
    }

    public Attack fight(char c) {
        switch (c) {
        case 'B':
        case 'L':
            return Attack.SCISSORS;
        case 'S':
            return Attack.PAPER;
        default:
            return Attack.ROCK;
        }
    }

    public Move move() {
        if (surroundings[0][1] == 'W') {
            tracker = 0;
            return Move.DOWN;
        } else if (surroundings[1][0] == 'W') {
            tracker = 0;
            return Move.RIGHT;
        } else if (surroundings[2][1] == 'W') {
            tracker = 0;
            return Move.UP;
        } else if (surroundings[1][2] == 'W') {
            tracker = 0;
            return Move.LEFT;
        } else if (tracker > 10) {
            tracker = 0;
            return Move.values()[new Random().nextInt(5)];
        } else if (surroundings[0][1] == 'S' || surroundings[0][1] == 'B') {
            tracker++;
            return Move.UP;
        } else if (surroundings[1][0] == 'S' || surroundings[1][0] == 'B') {
            tracker++;
            return Move.LEFT;
        } else if (surroundings[2][1] == 'S' || surroundings[2][1] == 'B') {
            tracker++;
            return Move.DOWN;
        } else if (surroundings[1][2] == 'S' || surroundings[1][2] == 'B') {
            tracker++;
            return Move.RIGHT;
        } else {
            tracker = 0;
            return Move.values()[new Random().nextInt(5)];
        }
    }
}
</code>```

Attempts to counter GamblerWolf by setting random value back into range [0, 1). This also makes it always defeat Lions. Vulnerable to CamoWolf. Tracks Bears and also goes after Stones (which makes it especially vulnerable to CamoWolf.

Title: Survival Game - Create Your Wolf

Body:
PsychoWolf

import java.lang.reflect.Field;
import java.util.Random;

public class PsychoWolf extends Animal {
    private int tracker = 0;

    public PsychoWolf() {
        super('W');
        try {
            Field field = Math.class.getDeclaredField("randomNumberGenerator");
            field.setAccessible(true);
            field.set(null, new Random() {
                public double nextDouble() {
                    return 0;
                }
            });
        } catch (RuntimeException | NoSuchFieldException
                | IllegalAccessException e) {

        }
    }

    public Attack fight(char c) {
        switch (c) {
        case 'B':
        case 'L':
            return Attack.SCISSORS;
        case 'S':
            return Attack.PAPER;
        default:
            return Attack.ROCK;
        }
    }

    public Move move() {
        if (surroundings[0][1] == 'W') {
            tracker = 0;
            return Move.DOWN;
        } else if (surroundings[1][0] == 'W') {
            tracker = 0;
            return Move.RIGHT;
        } else if (surroundings[2][1] == 'W') {
            tracker = 0;
            return Move.UP;
        } else if (surroundings[1][2] == 'W') {
            tracker = 0;
            return Move.LEFT;
        } else if (tracker > 10) {
            tracker = 0;
            return Move.values()[new Random().nextInt(5)];
        } else if (surroundings[0][1] == 'S' || surroundings[0][1] == 'B') {
            tracker++;
            return Move.UP;
        } else if (surroundings[1][0] == 'S' || surroundings[1][0] == 'B') {
            tracker++;
            return Move.LEFT;
        } else if (surroundings[2][1] == 'S' || surroundings[2][1] == 'B') {
            tracker++;
            return Move.DOWN;
        } else if (surroundings[1][2] == 'S' || surroundings[1][2] == 'B') {
            tracker++;
            return Move.RIGHT;
        } else {
            tracker = 0;
            return Move.values()[new Random().nextInt(5)];
        }
    }
}

Attempts to counter GamblerWolf by setting random value back into range [0, 1). This also makes it always defeat Lions. Vulnerable to CamoWolf. Tracks Bears and also goes after Stones (which makes it especially vulnerable to CamoWolf.