问:
Where can the cannon go?

Introduction

The game of xiangqi, also known as Chinese chess, is a chess-like game
popular in China, Vietnam, Taiwan, and other East Asian countries. The colours
of the two sides in xiangqi are red and black. There are seven pieces in
xiangqi: the general (G), advisor (A), elephant (E), horse (H), chariot
(R), cannon (C), and soldier (S). For the purposes of this challenge,
uppercase pieces are considered red and lowercase pieces black. Most of these
pieces have a rough equivalent in Western chess, but there is one completely unique piece: the cannon.

The cannon moves like a rook in chess or a chariot in xiangqi (moving any
number of spaces on either the X or Y axes), but cannot attack this way.
Instead, it attacks by jumping along the X or Y axes (the same way it moves)
over one piece of any colour (friend or foe) and landing on the
opposite-coloured piece, which it then captures. Note that like all chess and
xiangqi pieces, cannons cannot capture pieces of their own colour.

For example, in the following diagram, the spaces to which the cannon (C)
can move are marked with *, and those to which it can jump and capture
are marked with X, assuming that there is a black/lowercase piece there.

```<code>....X....
.........
.........
....h....
....*....
****C**aX
....E....
....X....
....g....
....R....
</code>```

Challenge

Write a program or function that, given a xiangqi board and the coordinates of
a cannon on that board as input, outputs a list of coordinates to which the
cannon can move or jump.

The format for all I/O is flexible.

Acceptable formats for the xiangqi board include a newline-separated string, a
list of strings, or a string with any other separator not in aceghrsACEGHRS..
You may assume the board will always be 9x10, the size of a xiangqi board.

The contents of the board itself will consist of a number of periods (.),
representing empty points on the board, and characters representing pieces. The
piece-to-character mapping is as follows:

```<code>A -> advisor
C -> cannon
E -> elephant
G -> general
H -> horse
R -> chariot
S -> soldier
</code>```

Uppercase letters represent red pieces, and lowercase letters represent black pieces. Characters not listed here (i.e. not in aceghrsACEGHRS.) will not appear in the board.

The format of the input coordinate is flexible, and is not required to match
the format of the output coordinates. It can be a list of two integer elements,
a 2-tuple, two numbers with any separator, or two characters, for example. It
may also be either 0-indexed or 1-indexed. You may assume that the coordinate
on the board will always resolve to a cannon (C or c).

The coordinates to which the cannon can jump and move must appear in the same
list in output; distinction between the two is not necessary. Acceptable
formats for any individual output coordinates are the same as those for the
input coord. The coordinates may be newline-separated, output as a list, or any
other representation. No particular order is necessary; the order does not even
have to be deterministic.

Note that jumps onto a piece of the same colour (case) of the cannon are not
legal, and thus cannot appear in the output.

Test cases

Note that not all of the test cases are possible xiangqi positions.

```<code>Input board
Input coordinate (0-indexed)
List of output coordinates

.........
.........
.........
.........
.........
....C....
.........
.........
.........
.........
(4, 5)
[(0, 5), (1, 5), (2, 5), (3, 5), (5, 5), (6, 5), (7, 5), (8, 5), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 6), (4, 7), (4, 8), (4, 9)]

.........
.....G...
.........
.........
.....e...
.........
.........
h..R.c..S
.....a...
.........
(5, 7)
[(4, 7), (6, 7), (7, 7), (5, 6), (5, 5), (5, 1)]

..s......
..A...e..
.........
EACCcsh.H
..r......
.....S...
......s..
....C....
..g......
(2, 3)
[(2, 0), (2, 2), (4, 3), (2, 8)]

rheagaehr
.........
.c.....c.
s.s.s.s.s
.........
.........
S.S.S.S.S
.C.....C.
.........
RHEAGAEHR
(7, 7)
[(2, 7), (3, 7), (4, 7), (5, 7), (6, 7), (8, 7), (7, 0), (7, 3), (7, 4), (7, 5), (7, 6), (7, 8)]
</code>```

Scoring

This is code-golf, so the shortest answer (in bytes) wins. Happy golfing!

答:
Pip, 112 + 1 = 113 bytes

Takes input as command-line arguments: the two coordinates, followed by the 10 lines of the board. Coordinates are 0-based. Outputs coordinates like 67 77, with a newline between the same-row list and the same-column list. One byte added for the -s flag.

```<code>g@>:2P(f:{Ya@bQ'C?X^z;X^AZa@b:'@aR`\.*@\.*`{aR'.s}Ry.`\.*\w *@`s._@>1R`@ *\w\.*`.y_@<v.s@*s}g@ba).ba.(f;J(Zga)b)
</code>```

Try it online!

Explanation of somewhat ungolfed version

```<code>g@>:2
f:{
 Y a@bQ'C ? `[a-z]` `[A-Z]`
 a@b:'@
 aR:`\.*@\.*` {aR'.s}
 aR:y.`\.*\w *@` s._@>1
 aR:`@ *\w\.*`.y _@<v.s
 a@*s
}
P (f g@b a).b
a.(f; J(Zg)@a b)
</code>```

By default, Pip reads command-line args into the list g. It also stores the first five arguments in the variables a through e. Our first two arguments, a and b, are the coordinates of the cannon; g contains the coordinates followed by the rows of the board. To get just the board in g, we slice it from index 2 onward and assign back to g (g@>:2).

Now we define a function f. This function takes two arguments: a string representing a row or column of the board, and the index of the cannon in that string. These arguments are available inside the function as a and b. The function will return a list of all indices that represent spots the cannon can move to or capture.

First, we test whether a@b is C or c. If it's C, we're going to want the regex [a-z] to match the pieces it can capture. If it's c, the regex is [A-Z]. (The golfed code generates these regexes from the builtin variables for lower- and uppercase alphabet.) We Yank the appropriate regex into the y variable.

We change the cannon's character in the string to @ (to distinguish it from other cannons in the same row/column).

Next comes a series of regex replacements, which will change every place the cannon can go to a space character. The first regex \.*@\.* matches @ surrounded by any number of periods, all of which represent empty spots to which the cannon can move. The replacement uses a callback function {aR'.s} to change all the periods to spaces.

The next regex matches a piece the cannon can capture: either [a-z] or [A-Z] (depending on which one was yanked into y earlier) followed by \.*\w *@ (any number of periods, one letter, any number of spaces, and @). This will match a string like h..R @ (provided the cannon was C). The callback function s._@>1 slices the first character off and prepends a space.

The third regex is similar, but matches a capturable piece after the cannon rather than before it.

Finally, the function returns a@*s, using the find-all operator to get a list of the indices of all spaces.

We now call f on the cannon's row and again on the cannon's column. The row's string is g@b, with the cannon's index inside the string being a. The function returns a list of column numbers, to each of which we append the row number b. When the list is printed, the -s flag puts a space between the coordinate pairs.

To get the column, we use the Zip operator to transpose g, select index a, and Join the resulting list of characters into a string. The cannon's index within this string is b. The function returns a list of row numbers, to each of which we prepend the column number a. This list, being the last expression in the program, is autoprinted.

(In case anyone was wondering, the expression separator ; is there to force J to parse as a unary operator rather than binary.)

Title: Where can the cannon go?

Body:
Pip, 112 + 1 = 113 bytes

Takes input as command-line arguments: the two coordinates, followed by the 10 lines of the board. Coordinates are 0-based. Outputs coordinates like 67 77, with a newline between the same-row list and the same-column list. One byte added for the -s flag.

g@>:2P(f:{Ya@bQ'C?X^z;X^AZa@b:'@aR`\.*@\.*`{aR'.s}Ry.`\.*\w *@`s._@>1R`@ *\w\.*`.y_@<v.s@*s}g@ba).ba.(f;J(Zga)b)

Try it online!

Explanation of somewhat ungolfed version

g@>:2
f:{
 Y a@bQ'C ? `[a-z]` `[A-Z]`
 a@b:'@
 aR:`\.*@\.*` {aR'.s}
 aR:y.`\.*\w *@` s._@>1
 aR:`@ *\w\.*`.y _@<v.s
 a@*s
}
P (f g@b a).b
a.(f; J(Zg)@a b)

By default, Pip reads command-line args into the list g. It also stores the first five arguments in the variables a through e. Our first two arguments, a and b, are the coordinates of the cannon; g contains the coordinates followed by the rows of the board. To get just the board in g, we slice it from index 2 onward and assign back to g (g@>:2).

Now we define a function f. This function takes two arguments: a string representing a row or column of the board, and the index of the cannon in that string. These arguments are available inside the function as a and b. The function will return a list of all indices that represent spots the cannon can move to or capture.

First, we test whether a@b is C or c. If it's C, we're going to want the regex [a-z] to match the pieces it can capture. If it's c, the regex is [A-Z]. (The golfed code generates these regexes from the builtin variables for lower- and uppercase alphabet.) We Yank the appropriate regex into the y variable.

We change the cannon's character in the string to @ (to distinguish it from other cannons in the same row/column).

Next comes a series of regex replacements, which will change every place the cannon can go to a space character. The first regex \.*@\.* matches @ surrounded by any number of periods, all of which represent empty spots to which the cannon can move. The replacement uses a callback function {aR'.s} to change all the periods to spaces.

The next regex matches a piece the cannon can capture: either [a-z] or [A-Z] (depending on which one was yanked into y earlier) followed by \.*\w *@ (any number of periods, one letter, any number of spaces, and @). This will match a string like h..R @ (provided the cannon was C). The callback function s._@>1 slices the first character off and prepends a space.

The third regex is similar, but matches a capturable piece after the cannon rather than before it.

Finally, the function returns a@*s, using the find-all operator to get a list of the indices of all spaces.

We now call f on the cannon's row and again on the cannon's column. The row's string is g@b, with the cannon's index inside the string being a. The function returns a list of column numbers, to each of which we append the row number b. When the list is printed, the -s flag puts a space between the coordinate pairs.

To get the column, we use the Zip operator to transpose g, select index a, and Join the resulting list of characters into a string. The cannon's index within this string is b. The function returns a list of row numbers, to each of which we prepend the column number a. This list, being the last expression in the program, is autoprinted.

(In case anyone was wondering, the expression separator ; is there to force J to parse as a unary operator rather than binary.)


问:
Output an upside-down tent
Given an integer, output an upside-down tent.

The input determines both the size of the tent (absolute value) and whether the entrance is on the left side (negative numbers) or the right side (positive numbers).

```<code>If input = -1:
____
\/_/

If input = -2:
________
\  /   /
 \/___/

If input = -3:
____________
\    /     /
 \  /     /
  \/_____/

If input = 1:
____
\_\/

If input = 2:
________
\   \  /
 \___\/

If input = 3:
____________
\     \    /
 \     \  /
  \_____\/

et cetera
</code>```

Note that the top of the tent (i.e. the last line) has 2 * abs(input) - 1 underscores.

There can be no leading spaces, such that the first line directly starts with an underscore.

Assume that the input will never be 0.

Your code should be as short as possible.

This challenge is based on a chat mini challenge by Helka Homba, which is allowed to be used in real challenges under the conditions of Calvin's Hobbies Public License.

答:
C# 241 231 Bytes

Saved 10 bytes thanks to @Kevin Cruijssen

```<code>using s=System.String;s f(int N){var f=N<0;N=N>0?N:-N;var o=new s('_',N*4);for(int j=0,z;j<N;){z=-2*j+2*N-2;var O=j>N-2?'_':' ';o+='\n'+new s(' ',j)+'\\'+new s(' ',z)+(f?'/':O)+new s(O,j++*2)+(f?O:'\\')+new s(' ',z)+'/';}return o;}
</code>```

Old version:

```<code>string f(int N){var f=N<0;N=N>0?N:-N;var o=new string('_',N*4);for(int j=0;j<N;){int z=-2*j+2*N-2;var O=j>N-2?'_':' ';o+='\n'+new string(' ',j)+'\\'+new string(' ',z)+(f?'/':O)+new string(O,j++*2)+(f?O:'\\')+new string(' ',z)+'/';}return o;}
</code>```

Originally had the new string(...) as a Func<char,int,string> but saved one byte using the constructor. I wish int->char was implicit

Pretty sure my math can be fixed somehow too, but I can't see it

ContentLicense: CC BY-SA 3.0

Title: Output an upside-down tent

Body:
C# 241 231 Bytes

Saved 10 bytes thanks to @Kevin Cruijssen

using s=System.String;s f(int N){var f=N<0;N=N>0?N:-N;var o=new s('_',N*4);for(int j=0,z;j<N;){z=-2*j+2*N-2;var O=j>N-2?'_':' ';o+='\n'+new s(' ',j)+'\\'+new s(' ',z)+(f?'/':O)+new s(O,j++*2)+(f?O:'\\')+new s(' ',z)+'/';}return o;}

Old version:

string f(int N){var f=N<0;N=N>0?N:-N;var o=new string('_',N*4);for(int j=0;j<N;){int z=-2*j+2*N-2;var O=j>N-2?'_':' ';o+='\n'+new string(' ',j)+'\\'+new string(' ',z)+(f?'/':O)+new string(O,j++*2)+(f?O:'\\')+new string(' ',z)+'/';}return o;}

Originally had the new string(...) as a Func<char,int,string> but saved one byte using the constructor. I wish int->char was implicit

Pretty sure my math can be fixed somehow too, but I can't see it


问:
Generate keyboard shortcuts for a menu

Menu Shortcuts

Traditionally, user menus are accessible by keyboard shortcuts, such as Alt + (a letter), or even simply hitting the letter when all textboxes are unfocused (gmail style).

Your task

Given the menu entries as an input, your task is to grant each menu entry a proper shortcut letter.

Write a function or a program that accepts a set of words - the menu entries (as an array of strings, or your language equivalent), and returns a dictionary, or a hashmap, from a single letter to a menu entry.

You can either use a parameter and return a value, or use the STDIN and output your results to STDOUT. You are not allowed to assume a global/scope variable is already populated with the input.

Algorithm to determine the proper letter

Basically it's the first available letter of the word. See assumptions and examples below.

In case all entry's letters are not available, the shortcut will be (a letter) + (a number). Which letter you pick from the entry is arbitrary. The number should start from 0 and be incremented by 1 - such that all shortcuts are unique. See third example below.

Assumptions

The input will be a Set, i.e. no repetitions, every entry is unique.

Length of the input can be any non-negative integer (up to MAX_INT of your language).

Case sensitivity: Input is case-sensitive, (but will stay unique when ignoring case). The results should contain the original entries with their original casing. However, the output shortcut letters are not case-sensitive.

All input words will not end with numbers.

No "evil input" will be tested. "Evil input" is such that you have to increment the counter of a certain letter more than 10 times.

Examples

Examples below are in JSON, but you can use your language equivalent for an array and a Dictionary, or - in case you're using STD I/O - any readable format for your input and output (such as csv, or even space-separated values).

1.

```<code>Input:  ['File', 'Edit', 'View', 'Help']
Output: {f:'File', e:'Edit', v:'View', h:'Help'}
</code>```

2.

```<code>Input:  ['Foo', 'Bar', 'FooBar', 'FooBars']
Output: {f:'Foo', b:'Bar', o:'FooBar', a:'FooBars'}
</code>```

3.

```<code>Input:  ['a', 'b', 'aa', 'bb', 'bbq', 'bbb', 'ba']
Output: {a:'a', b:'b', a0:'aa', b0:'bb', q:'bbq', b1:'bbb', b2:'ba'}
</code>```

Winning conditions

Shortest code wins. Only ASCII is allowed.

答:
PHP, 153 bytes

```<code>for($c=[];$w=trim(fgets(STDIN));$c[reset(array_diff(str_split($s),array_keys($c)))?:$y]=$w){$s=strtoupper($w);for($n=0;$c[$y=$s[0].$n++];);}print_r($c);
</code>```

run with php-r '' <<EOF + Enter + <word1>+Enter + <word2>+Enter + ... + EOF+Enter

working on argv for 155 bytes:

```<code>$c=[];foreach($argv as$i=>$w)if($i){$s=strtoupper($w);for($n=0;$c[$y=$s[0].$n++];);$c[reset(array_diff(str_split($s),array_keys($c)))?:$y]=$w;}print_r($c);
</code>```

run with php -r '' <word1> <word2> ...

(-13 bytes with a defined global: foreach($i as$w) instead of foreach($argv as$i=>$w)if($i))

Title: Generate keyboard shortcuts for a menu

Body:
PHP, 153 bytes

for($c=[];$w=trim(fgets(STDIN));$c[reset(array_diff(str_split($s),array_keys($c)))?:$y]=$w){$s=strtoupper($w);for($n=0;$c[$y=$s[0].$n++];);}print_r($c);

run with php-r '<code>' <<EOF + Enter + <word1>+Enter + <word2>+Enter + ... + EOF+Enter

working on argv for 155 bytes:

$c=[];foreach($argv as$i=>$w)if($i){$s=strtoupper($w);for($n=0;$c[$y=$s[0].$n++];);$c[reset(array_diff(str_split($s),array_keys($c)))?:$y]=$w;}print_r($c);

run with php -r '<code>' <word1> <word2> ...

(-13 bytes with a defined global: foreach($i as$w) instead of foreach($argv as$i=>$w)if($i))


问:
Do the auto-super-logarithm
Given a positive integer n and a number a, the n-th tetration of a is defined as a^(a^(a^(...^a))), where ^ denotes exponentiation (or power) and the expression contains the number a exactly n times.

In other words, tetration is right-associative iterated exponentiation. For n=4 and a=1.6 the tetration is 1.6^(1.6^(1.6^1.6)) ≈ 3.5743.

The inverse function of tetration with respect to n is the super-logarithm. In the previous example, 4 is the super-logarithm of 3.5743 with "super-base" 1.6.

The challenge

Given a positive integer n, find x such that n is the super-logarithm of itself in super-base x. That is, find x such that x^(x^(x^(...^x))) (with x appearing n times) equals n.

Rules

Program or function allowed.

Input and output formats are flexible as usual.

The algorithm should theoretically work for all positive integers. In practice, input may be limited to a maximum value owing to memory, time or data-type restrictions. However, the code must work for inputs up to 100 at least in less than a minute.

The algorithm should theoretically give the result with 0.001 precision. In practice, the output precision may be worse because of accumulated errors in numerical computations. However, the output must be accurate up to 0.001 for the indicated test cases.

Shortest code wins.

Test cases

```<code>1    ->  1
3    ->  1.635078
6    ->  1.568644
10   ->  1.508498
25   ->  1.458582
50   ->  1.448504
100  ->  1.445673
</code>```

Reference implementation

Here's a reference implementation in Matlab / Octave (try it at Ideone).

```<code>N = 10; % input
t = .0001:.0001:2; % range of possible values: [.0001 .0002 ... 2]
r = t;
for k = 2:N
    r = t.^r; % repeated exponentiation, element-wise
end
[~, ind] = min(abs(r-N)); % index of entry of r that is closest to N
result = t(ind);
disp(result)
</code>```

For N = 10 this gives result =  1.5085.

The following code is a check of the output precision, using variable-precision arithmetic:

```<code>N = 10;
x = 1.5085; % result to be tested for that N. Add or subtract 1e-3 to see that
            % the obtained y is farther from N
s = num2str(x); % string representation
se = s;
for n = 2:N;
    se = [s '^(' se ')']; % build string that evaluates to iterated exponentiation
end
y = vpa(se, 1000) % evaluate with variable-precision arithmetic
</code>```

This gives:

For x = 1.5085: y = 10.00173...

For x = 1.5085 + .001: y = 10.9075

For x = 1.5085 - .001 it gives y = 9.23248.

so 1.5085 is a valid solution with .001 precision.

Title: Do the auto-super-logarithm

Body:
PHP , 103 Bytes

$z=2;while($z-$a>9**-9){for($r=$s=($a+$z)/2,$i=0;++$i<$n=$argv[1];)$r=$s**$r;$r<$n?$a=$s:$z=$s;}echo$s;


问:
Emulate a 7-segment display

Task

The task is to display any of the 128 possible states of a
7-segment display.

Your program should accept a string of 7 characters ("bits") that are either 0 or 1.
First bit of input corresponds to segment A of the following illustration, the
second to B, etc (ignore dp):

How you represent the display is up to you -- a single Unicode or ASCII symbol,
ASCII art, grafically, or whatever you can come up with. However, each
input must have it's own distinct output. If you come up with something fancy I'm sure you can harvest upvotes by showing off some examples.

All 128 possible states of the display are:

Rules

Codegolf

As I said, any kind of output is allowed, but it would be nice if you specified it.

Input can be stdin or command line argument.

Examples

Input

```<code>1101101
</code>```

Output

As ASCII/Unicode:

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

Different kinds of ASCII art (I'm not too good at this)

```<code> _   ╺┓  ╒╗   ---
 _|  ┏┛  ╔╝     |
|_   ┗╸  ╚╛   ---
              |
              ---
</code>```

Title: Emulate a 7-segment display

Body:
Brainfuck - 224

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

Prints using Exlamation points:

 !
! !
 !
! !
 !

Not the most readable, but not too horrible either.

Surprised at how close this is to not being last place.


问:
Let's get Animated!

The Challenge

GIFs are the most common image format for animation, and are used pretty heavily in today's social media. For the purpose of this challenge, I'm going to redefine what a GIF can be. This challenge will require you to take in a 3D array containing some sort of representation of a 2D 'image' and iterate through them, displaying an animation. This animation can be done anywhere, in a GIF, in your console, in a GUI, etc; the delivery doesn't matter, so long as it is animated.

The Input

A 3D array where the data inside somehow represents a 2D image.

The array may contain RGB data, true/false data or anything else you see fit.

I'm also fine with you dumbing it down to a 2D array of strings or something similar, but the animation must be a 2D animation.

The time between each frame in a format of your choosing (Seconds, Milliseconds, etc...).

People have been asking me whether or not they HAVE to include the duration length. My answer is "meh", as long as you are able to show animation. I'm more concerned that you adhere to the "Array" parameter than this one, meaning no random animations.

The Output

A seamlessly iterated sequence of output that looks like a 2D animation with the correct delay on each transition based on the value input.

The Rules

Output can be, but is not limited to:

GIF image.

GUI animation (my example).

In-console animation.

Honestly, any "animation" that you see fit, as long as it follows the below rules.

When outputting your image you must clear the console before showing the next frame, you cannot just print them sequentially.

Emulating a console "clear" is also acceptable, as long as it looks like a seamless animation (see the hint under my example for more information on what I mean).

Regardless of implementation, your animation should loop forever, or until stopped.

The "looping" can be as simple as while(true){} or infinite recursion, you may assume the user wants to view this masterpiece until they hit "ctrl+c".

You must be able to handle any size 2D 'images', if your language is limited by buffer sizes, this is acceptable and you may state this in your explanation.

Standard loopholes are disallowed.

Example I/O

Input (3D Array, Delay)

```<code>f([
  [[1,0,0],
   [0,0,0],
   [0,0,0]],
  [[0,0,0],
   [0,1,0],
   [0,0,0]],
  [[0,0,0],
   [0,0,0],
   [0,0,1]],
], 1)
</code>```

Output (Example, 2020 Bytes - Java)

```<code>import javax.swing.JFrame;
import javax.swing.JTextArea;

/**
 * Simple GIF class to animate a 3D integer array in a swing text area.
 * (Clearing the console in java isn't something you really do, so I chose
 * java on purpose to make it an extremely ungolf-able answer that someone
 * wouldn't bother to steal).
 */
public class Gif implements Runnable {
    /**
     * The output area.
     */
    private final JTextArea area;

    /**
     * The list of images.
     */
    private final int[][][] images;

    /**
     * The delay between image transitions.
     */
    private final long transitionDelay;

    /**
     * Main method, instantiates a GIF object and runs it.
     * @param args Does absolutely nothing.
     */
    public static void main(String[] args) {
        final int[][][] images = {{{1,0,0},{0,0,0},{0,0,0}},{{0,0,0},{0,1,0},{0,0,0}},{{0,0,0},{0,0,0},{0,0,1}}};
        final long transitionDelay = 1000L;
        new Thread(new Gif(images, transitionDelay)).start();
    }

    /**
     * Constructor for a GIF, takes in a 3D array of images and a transition
     * delay to wait between transitioning the images.
     * @param images The list of images.
     * @param delay The delay between each image.
     */
    public Gif(int[][][] images, long transitionDelay) {
        this.images = images;
        this.transitionDelay = transitionDelay;
        this.area = new JTextArea();
        final JFrame frame = new JFrame("It's a GIF!");
        frame.setSize(10,100);
        frame.add(area);
        frame.setVisible(true);
    }

    /**
     * When run, it will alter the area to imitate an animated GIF.
     */
    @Override
    public void run() {
        while (true) {
            for (int i = 0; i < images.length; i++) {
                final StringBuffer frame = new StringBuffer();
                for (int j = 0; j < images[i].length; j++) {
                    for (int k = 0; k < images[i][j].length; k++) {
                        frame.append("" + images[i][j][k]);
                    }
                    frame.append("\n");
                }
                this.area.setText(frame.toString());
                try{Thread.sleep(transitionDelay);}catch(Exception e){}
                this.area.setText("");
            }
        }
    }
}
</code>```

This results in a swing GUI popping up, animating the array:

HINT HINT: Use a language where console clearing is possible, or specify why what you are doing will end up with a result that looks like an animation in the language you chose. I think some languages have default buffer sizes on their consoles, you may use this to your advantage, but I expect an explanation or example. Just because I output my animation as a string, you don't have to; I could've just as easily used 0 for black and 1 for white and made a real GIF.

Judging

This is code-golf, lowest byte count wins (inputs excluded).

I'll +1 anyone who uses a language in a cool or unexpected way as well.

Title: Let's get Animated!

Body:
Lua(LÖVE), <s>296</s> 287 bytes

c=0;f=1;t=10;l=love
function l.load()loadstring('i='..arg[2])()s=tonumber(arg[3])end
function l.update(d)if c>s then
c=0;f=f==#i and 1 or f+1
end;c=c+d;end
function l.draw()for K,V in pairs(i[f])do
for k,v in pairs(V)do if v>0 then l.graphics.rectangle('fill',k*t,K*t,t,t)end
end
end
end

Usage Example

love main.love '{{{1,0,0},{0,0,0},{0,0,0}},{{0,1,0},{0,0,0},{0,0,0}},{{0,0,1},{0,0,0},{0,0,0}},{{0,0,0},{0,0,1},{0,0,0}},{{0,0,0},{0,0,0},{0,0,1}},{{0,0,0},{0,0,0},{0,1,0}},{{0,0,0},{0,0,0},{1,0,0}},{{0,0,0},{1,0,0},{0,0,0}},{{1,0,0},{1,0,0},{0,0,0}},{{1,1,0},{1,0,0},{0,0,0}},{{1,1,1},{1,0,0},{0,0,0}},{{1,1,1},{1,0,1},{0,0,0}},{{1,1,1},{1,0,1},{0,0,1}},{{1,1,1},{1,0,1},{0,1,1}},{{1,1,1},{1,0,1},{1,1,1}},{{1,1,1},{1,1,1},{1,1,1}},{{0,0,0},{0,0,0},{0,0,0}}}' 1

Output : https://youtu.be/0kDhPbbyG9E


问:
Simplify a continued fraction
Continued fractions are expressions that describe fractions iteratively. They can be represented graphically:

$$
a_0 +\cfrac 1
 {a_1 + \cfrac 1
  {a_2 + \cfrac 1
   {\ddots + \cfrac 1
    {a_n}
   }
  }
 }
$$

Or they can be represented as a list of values: \$[a_0 ; a_1, a_2, \dots, a_n]\$

The challenge:

take a base number: \$a_0\$ and a list of denominator values: \$[a_1, a_2, \dots, a_n]\$ and simplify the continued fraction to a simplified rational fraction: return or print numerator and denominator separately.

Examples:

\$\sqrt 19\$: [4;2,1,3,1,2]: 170/39

\$e\$: [1;0,1,1,2,1,1]: 19/7

\$\pi\$: [3;7,15,1,292,1]: 104348/33215

\$ϕ\$: [1;1,1,1,1,1]: 13/8

Example implementation: (python)

def foo(base, sequence):
    numerator = 1
    denominator = sequence[-1]
    for d in sequence[-2::-1]:
        temp = denominator
        denominator = d * denominator + numerator
        numerator = temp
    return numerator + base * denominator, denominator```

Winning:
 shortest code in bytes: --no builtins that do the entire problem allowed--

答:
LabVIEW, 36 equivalent bytes

Fairly straight forward naive implementation using OP's algorithm. Is there a nicer way to do this?

ContentLicense: CC BY-SA 4.0

Title: Simplify a continued fraction


问:
Produce n n-squares of integers with rotating *'s in consecuitive corners
The objective is to produce output of n squares (nxn) of random integers (0-9) with a moving * that rotates clockwise around the corners, starting from the top left. The squares should be side by side and separated by a single space.

If n = 0, the output should be empty.

Output for n=1:

*

Output for n=2:

```<code>*3 4*
14 07
</code>```

Output for n=3:

```<code>*34 82* 291
453 224 924
145 158 57*
</code>```

Output for n=4:

```<code>*153 135* 0154 0235
2352 5604 3602 2065
2245 6895 3561 7105
7225 5785 479* *662
</code>```

Notice how, for each square, the * rotates around the corners of the square, from left to right, beginning in the top left corner of the first, then moving to the top right of the second, and so on.

The shortest answer (measured in bytes) wins.

答:
APL (Dyalog Unicode), 47 bytes

{⍉⎕FMT'*'@((⍳⍵),¨⍵⍴2⍴¨1(⍵1)⍵(1⍵))⊢⎕D[?10⍴⍨3⍴⍵]}
```

Try it online!

Anonymous prefix lambda.

{…} "dfn"; n is called ⍵

 ⎕D[…] index the list of digits with the indices:

  3⍴⍵ cyclically reshape n into a list of length 3

  10⍴⍨ cyclically reshape the number 10 into an array of those dimensions (3×n×n)

  ? random index (1…10) for each

 ⊢ yield that as argument to the upcoming function (separates indices from data)

 '*'@(…) place asterisks at the following locations:

  1(⍵1)⍵(1⍵) the list [1,[n,1],n,[1,n]]

  2⍴¨ cyclically reshape each into a list of length 2: [[1,1],[n,1],[n,n],[1,n]]

  ⍵⍴ cyclically reshape that list into length n

  (…),¨ prepend an element to each, taking elements from this list:

   ⍳⍵ indices 1…n

 ⎕FMT ForMaT as character matrix (joins layers with a line of spaces)

 ⍉ transpose

Body:
APL (Dyalog Unicode), 47 bytes

{⍉⎕FMT'*'@((⍳⍵),¨⍵⍴2⍴¨1(⍵1)⍵(1⍵))⊢⎕D[?10⍴⍨3⍴⍵]}

Try it online!

Anonymous prefix lambda.

{…} "dfn"; n is called ⍵

 ⎕D[…] index the list of digits with the indices:

  3⍴⍵ cyclically reshape n into a list of length 3

  10⍴⍨ cyclically reshape the number 10 into an array of those dimensions (3×n×n)

  ? random index (1…10) for each

 ⊢ yield that as argument to the upcoming function (separates indices from data)

 '*'@(…) place asterisks at the following locations:

  1(⍵1)⍵(1⍵) the list [1,[n,1],n,[1,n]]

  2⍴¨ cyclically reshape each into a list of length 2: [[1,1],[n,1],[n,n],[1,n]]

  ⍵⍴ cyclically reshape that list into length n

  (…),¨ prepend an element to each, taking elements from this list:

   ⍳⍵ indices 1…n

 ⎕FMT ForMaT as character matrix (joins layers with a line of spaces)

 ⍉ transpose


答:
Python 2, 62 bytes

a=d=0
b=c=1
for n in input():a,b=b,n*b+a;c,d=d,n*d+c
print b,d
```

<p>It's unfortunately not as golfy (see @xnor's answer for shorter), but it calculates the fraction without needing to reverse the input. This uses the "magic table" approach for convergents – given the last two fractions <code>a/c</code> and <code>b/d</code>, the next fraction is <code>(n*b+a)/(n*c+d)</code>.</p>

<p>For instance, for pi:</p>

```          3    7    15     1      292        1

  0   1   3   22   333   355   103993   104348
  1   0   1    7   106   113    33102    33215
```

We can see that 15*22 + 3 = 333, 15*7 + 1 = 106, 1*333 + 22 = 355, 1*106 + 7 = 113, etc.

Title: Simplify a continued fraction

Body:
Continued fractions are expressions that describe fractions iteratively. They can be represented graphically:

$$
a_0 +\cfrac 1
 {a_1 + \cfrac 1
  {a_2 + \cfrac 1
   {\ddots + \cfrac 1
    {a_n}
   }
  }
 }
$$

Or they can be represented as a list of values: \$[a_0 ; a_1, a_2, \dots, a_n]\$

The challenge:

take a base number: \$a_0\$ and a list of denominator values: \$[a_1, a_2, \dots, a_n]\$ and simplify the continued fraction to a simplified rational fraction: return or print numerator and denominator separately.

Examples:

\$\sqrt 19\$: [4;2,1,3,1,2]: 170/39

\$e\$: [1;0,1,1,2,1,1]: 19/7

\$\pi\$: [3;7,15,1,292,1]: 104348/33215

\$ϕ\$: [1;1,1,1,1,1]: 13/8

Example implementation: (python)

def foo(base, sequence):
    numerator = 1
    denominator = sequence[-1]
    for d in sequence[-2::-1]:
        temp = denominator
        denominator = d * denominator + numerator
        numerator = temp
    return numerator + base * denominator, denominator```

Winning:
 shortest code in bytes: --no builtins that do the entire problem allowed--

Body:
Python 2, 62 bytes

a=d=0
b=c=1
for n in input():a,b=b,n*b+a;c,d=d,n*d+c
print b,d

It's unfortunately not as golfy (see @xnor's answer for shorter), but it calculates the fraction without needing to reverse the input. This uses the "magic table" approach for convergents – given the last two fractions a/c and b/d, the next fraction is (n*b+a)/(n*c+d).

For instance, for pi:

          3    7    15     1      292        1

  0   1   3   22   333   355   103993   104348
  1   0   1    7   106   113    33102    33215

We can see that 15*22 + 3 = 333, 15*7 + 1 = 106, 1*333 + 22 = 355, 1*106 + 7 = 113, etc.


答:
MATL, <s>16</s> <s>12</s> 11 bytes

```<code>`G@)D1Y.XxT
</code>```

Input is a cell array of 2D. For example:

```<code>{[1 0 0; 0 0 0; 0 0 0] [0 0 0; 0 1 0; 0 0 0] [0 0 0; 0 0 0; 0 0 1]}
</code>```

The pause time is the 1 in the code. It can be changed to any real number, such as .5 or `.2 .

Try it at MATL Online! (If it doesn't work, refresh the page and press "Run" again.)

The input can also be a cell array of 2D char arrays. For example:

```<code>{['x...';'+...';'....';'....'] ['+x..';'....';'....';'....'] ['.+x.';'....';'....';'....'] ['..+x';'....';'....';'....'] ['...+';'...x';'....';'....'] ['....';'...+';'...x';'....'] ['....';'....';'...+';'...x'] ['....';'....';'....';'..x+'] ['....';'....';'....';'.x+.'] ['....';'....';'....';'x+..'] ['....';'....';'x...';'+...'] ['....';'x...';'+...';'....']}
</code>```

Try this one too!

Explanation

```<code>`       % Do...while
  G     %   Push input: cell array
  @     %   Push iteration index
  )     %   Index to obtain that cell. This uses modular indexing,
        %   so each cell is addressed cyclically
  D     %   Display
  1     %   Push 1: number of seconds to pause
  Y.    %   Pause for that many seconds
  Xx    %   Clear screen
  T     %   True. This is used as loop condition: infinite loop
        % End. Implicitly end do...while loop
</code>```

Title: Let's get Animated!

Body:
The Challenge

GIFs are the most common image format for animation, and are used pretty heavily in today's social media. For the purpose of this challenge, I'm going to redefine what a GIF can be. This challenge will require you to take in a 3D array containing some sort of representation of a 2D 'image' and iterate through them, displaying an animation. This animation can be done anywhere, in a GIF, in your console, in a GUI, etc; the delivery doesn't matter, so long as it is animated.

The Input

A 3D array where the data inside somehow represents a 2D image.

The array may contain RGB data, true/false data or anything else you see fit.

I'm also fine with you dumbing it down to a 2D array of strings or something similar, but the animation must be a 2D animation.

The time between each frame in a format of your choosing (Seconds, Milliseconds, etc...).

People have been asking me whether or not they HAVE to include the duration length. My answer is "meh", as long as you are able to show animation. I'm more concerned that you adhere to the "Array" parameter than this one, meaning no random animations.

The Output

A seamlessly iterated sequence of output that looks like a 2D animation with the correct delay on each transition based on the value input.

The Rules

Output can be, but is not limited to:

GIF image.

GUI animation (my example).

In-console animation.

Honestly, any "animation" that you see fit, as long as it follows the below rules.

When outputting your image you must clear the console before showing the next frame, you cannot just print them sequentially.

Emulating a console "clear" is also acceptable, as long as it looks like a seamless animation (see the hint under my example for more information on what I mean).

Regardless of implementation, your animation should loop forever, or until stopped.

The "looping" can be as simple as while(true){} or infinite recursion, you may assume the user wants to view this masterpiece until they hit "ctrl+c".

You must be able to handle any size 2D 'images', if your language is limited by buffer sizes, this is acceptable and you may state this in your explanation.

Standard loopholes are disallowed.

Example I/O

Input (3D Array, Delay)

```<code>f([
  [[1,0,0],
   [0,0,0],
   [0,0,0]],
  [[0,0,0],
   [0,1,0],
   [0,0,0]],
  [[0,0,0],
   [0,0,0],
   [0,0,1]],
], 1)
</code>```

Output (Example, 2020 Bytes - Java)

```<code>import javax.swing.JFrame;
import javax.swing.JTextArea;

/**
 * Simple GIF class to animate a 3D integer array in a swing text area.
 * (Clearing the console in java isn't something you really do, so I chose
 * java on purpose to make it an extremely ungolf-able answer that someone
 * wouldn't bother to steal).
 */
public class Gif implements Runnable {
    /**
     * The output area.
     */
    private final JTextArea area;

    /**
     * The list of images.
     */
    private final int[][][] images;

    /**
     * The delay between image transitions.
     */
    private final long transitionDelay;

    /**
     * Main method, instantiates a GIF object and runs it.
     * @param args Does absolutely nothing.
     */
    public static void main(String[] args) {
        final int[][][] images = {{{1,0,0},{0,0,0},{0,0,0}},{{0,0,0},{0,1,0},{0,0,0}},{{0,0,0},{0,0,0},{0,0,1}}};
        final long transitionDelay = 1000L;
        new Thread(new Gif(images, transitionDelay)).start();
    }

    /**
     * Constructor for a GIF, takes in a 3D array of images and a transition
     * delay to wait between transitioning the images.
     * @param images The list of images.
     * @param delay The delay between each image.
     */
    public Gif(int[][][] images, long transitionDelay) {
        this.images = images;
        this.transitionDelay = transitionDelay;
        this.area = new JTextArea();
        final JFrame frame = new JFrame("It's a GIF!");
        frame.setSize(10,100);
        frame.add(area);
        frame.setVisible(true);
    }

    /**
     * When run, it will alter the area to imitate an animated GIF.
     */
    @Override
    public void run() {
        while (true) {
            for (int i = 0; i < images.length; i++) {
                final StringBuffer frame = new StringBuffer();
                for (int j = 0; j < images[i].length; j++) {
                    for (int k = 0; k < images[i][j].length; k++) {
                        frame.append("" + images[i][j][k]);
                    }
                    frame.append("\n");
                }
                this.area.setText(frame.toString());
                try{Thread.sleep(transitionDelay);}catch(Exception e){}
                this.area.setText("");
            }
        }
    }
}
</code>```

This results in a swing GUI popping up, animating the array:

HINT HINT: Use a language where console clearing is possible, or specify why what you are doing will end up with a result that looks like an animation in the language you chose. I think some languages have default buffer sizes on their consoles, you may use this to your advantage, but I expect an explanation or example. Just because I output my animation as a string, you don't have to; I could've just as easily used 0 for black and 1 for white and made a real GIF.

Judging

This is code-golf, lowest byte count wins (inputs excluded).

I'll +1 anyone who uses a language in a cool or unexpected way as well.

Body:
MATL, <s>16</s> <s>12</s> 11 bytes

`G@)D1Y.XxT

Input is a cell array of 2D. For example:

{[1 0 0; 0 0 0; 0 0 0] [0 0 0; 0 1 0; 0 0 0] [0 0 0; 0 0 0; 0 0 1]}

The pause time is the 1 in the code. It can be changed to any real number, such as .5 or `.2 .

Try it at MATL Online! (If it doesn't work, refresh the page and press "Run" again.)

The input can also be a cell array of 2D char arrays. For example:

{['x...';'+...';'....';'....'] ['+x..';'....';'....';'....'] ['.+x.';'....';'....';'....'] ['..+x';'....';'....';'....'] ['...+';'...x';'....';'....'] ['....';'...+';'...x';'....'] ['....';'....';'...+';'...x'] ['....';'....';'....';'..x+'] ['....';'....';'....';'.x+.'] ['....';'....';'....';'x+..'] ['....';'....';'x...';'+...'] ['....';'x...';'+...';'....']}

<a href="https://matl.io/?code=%60G%40%29D.2Y.XxT&inputs=%7B%5B%27x...%27%3B%27%2B...%27%3B%27....%27%3B%27....%27%5D+%5B%27%2Bx..%27%3B%27....%27%3B%27....%27%3B%27....%27%5D+%5B%27.%2Bx.%27%3B%27....%27%3B%27....%27%3B%27....%27%5D+%5B%27..%2Bx%27%3B%27....%27%3B%27....%27%3B%27....%27%5D+%5B%27...%2B%27%3B%27...x%27%3B%27....%27%3B%27....%27%5D+%5B%27....%27%3B%27...%2B%27%3B%27...x%27%3B%27....%27%5D+%5B%27....%27%3B%27....%27%3B%27...%2B%27%3B%27...x%27%5D+%5B%27....%27%3B%27....%27%3B%27....%27%3B%27..x%2B%27%5D+%5B%27....%27%3B%27....%27%3B%27....%27%3B%27.x%2B.%27%5D+%5B%27....%27%3B%27....%27%3B%27....%27%3B%27x%2B..%27%5D+%5B%27....%27%3B%27....%27%3B%27x...%27%3B%27%2B...%27%5D+%5B%27....%27%3B%27x...%27%3B%27%2B...%27%3B%27....%27%5D%7D&version=19.1.0" rel="nofollow noreferrer">Try this one too!

Explanation

`       % Do...while
  G     %   Push input: cell array
  @     %   Push iteration index
  )     %   Index to obtain that cell. This uses modular indexing,
        %   so each cell is addressed cyclically
  D     %   Display
  1     %   Push 1: number of seconds to pause
  Y.    %   Pause for that many seconds
  Xx    %   Clear screen
  T     %   True. This is used as loop condition: infinite loop
        % End. Implicitly end do...while loop


答:
J, <s>8</s> 5 bytes

Same as this, but uses a build-in for rationals.

Argument is {a0,a1,a2,a3,...} as a list of J extended precision rational numbers. Result is the fraction as a J extended precision rational number.

```<code>(+%)/
</code>```

(+%) the plus-the-reciprocal-of

/ reduction over

Try it online!

-3 thanks to miles.

Title: Simplify a continued fraction

Body:
J, <s>8</s> 5 bytes

Same as this, but uses a build-in for rationals.

Argument is {a0,a1,a2,a3,...} as a list of J extended precision rational numbers. Result is the fraction as a J extended precision rational number.

(+%)/

(+%) the plus-the-reciprocal-of

/ reduction over

Try it online!

-3 thanks to miles.


Title: Simplify a continued fraction

Body:
Javascript (ES6), 55 bytes

s=>eval('for(F=[1,0];s+"";)F=[s.pop()*F[0]+F[1],F[0]]')

Test cases

var f =
s=>eval('for(F=[1,0];s+"";)F=[s.pop()*F[0]+F[1],F[0]]')

console.log(f([4, 2, 1, 3, 1, 2]));
console.log(f([1, 0, 1, 1, 2, 1, 1]));
console.log(f([3, 7, 15, 1, 292, 1]));
console.log(f([1, 1, 1, 1, 1, 1]));


答:
CJam, <s>18</s> 16 bytes

```<code>XUq~W%{2$*+\}/]p
</code>```

Online interpreter.

```<code>XU                  Push 1 and 0 to the stack
  q~W%              Push input, eval and reverse it
      {     }/      For each n in the reversed input...
       2$             Copy numerator
         *+           Calculate n*denominator + numerator
           \          Swap numerator and denominator
              ]p   Wrap in array and output
</code>```

Title: Simplify a continued fraction

Body:
CJam, <s>18</s> 16 bytes

XUq~W%{2$*+\}/]p

Online interpreter.

XU                  Push 1 and 0 to the stack
  q~W%              Push input, eval and reverse it
      {     }/      For each n in the reversed input...
       2$             Copy numerator
         *+           Calculate n*denominator + numerator
           \          Swap numerator and denominator
              ]p   Wrap in array and output


答:
Javascript (ES6), 50 bytes

f=(s,n=1,d=s.pop())=>s+""?f(s,d,s.pop()*d+n):[d,n]
```
<p>It's thanks to Arnauld's answer, before seeing it I was stuck to 66 bytes:</p>
<pre class="lang-js prettyprint-override"><code>f=(b,s,i=s.length-1,n=1,d=s[i])=>i?f(b,s,--i,d,s[i]*d+n):[n+b*d,d]
</code>```

Example:

Call: f([1, 0, 1, 1, 2, 1, 1])

Output: Array [ 19, 7 ]

Title: Simplify a continued fraction

Body:
Javascript (ES6), 50 bytes

f=(s,n=1,d=s.pop())=>s+""?f(s,d,s.pop()*d+n):[d,n]

It's thanks to Arnauld's answer, before seeing it I was stuck to 66 bytes:

f=(b,s,i=s.length-1,n=1,d=s[i])=>i?f(b,s,--i,d,s[i]*d+n):[n+b*d,d]

Example:

Call: f([1, 0, 1, 1, 2, 1, 1])

Output: Array [ 19, 7 ]


问:
Test if given number is a Keith number
Since Fibonacci numbers and sequences seems like a popular subject for code golf I thought that it might be a fun challenge to code golf with Keith numbers.

So I propose a challenge that is to create a function that takes an integer and gives back a true or false depending on the number is a Keith number or not.

More about Keith numbers

In recreational mathematics, a Keith number or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence:
  14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, …

Numberphile has a video explaining how to calculate a Keith number. But basically you take the digits of a number. Add them together and then take the last digits of the original number and add them to the sum of the calculation, rinse and repeat. And example to make it clear.

14
1 + 4 = 5

  4 + 5 = 9

  5 + 9 = 14

Input

An integer.

Output

True if the number is a Keith number. False if it's not..

答:
Ruby, 82

```<code>def keith?(x)
  l="#{x}".chars.map &:to_i
  0while(l<<(s=l.inject :+)).shift&&s<x
  (s==x)&l[1]
end
</code>```

Suspect Python's a better tool for this one.

Title: Test if given number is a Keith number

Body:
Ruby, 82

def keith?(x)
  l="#{x}".chars.map &:to_i
  0while(l<<(s=l.inject :+)).shift&&s<x
  (s==x)&l[1]
end

Suspect Python's a better tool for this one.


答:
M, 5 bytes

```<code>Ṛİ+¥/
</code>```

The input is a list of the values [a0, a1, ..., aN] and it outputs a rational number.

Try it online! or Verify all test cases.

Explanation

```<code>Ṛİ+¥/  Input: list A
Ṛ      Reverse A
    /  Reduce A from left to right using
   ¥     A dyadic chain
 İ         Take the reciprocal of the left value
  +        Add the reciprocal to the right value
       Return and print implicitly
</code>```

Title: Simplify a continued fraction

Body:
M, 5 bytes

Ṛİ+¥/

The input is a list of the values [a0, a1, ..., aN] and it outputs a rational number.

Try it online! or Verify all test cases.

Explanation

Ṛİ+¥/  Input: list A
Ṛ      Reverse A
    /  Reduce A from left to right using
   ¥     A dyadic chain
 İ         Take the reciprocal of the left value
  +        Add the reciprocal to the right value
       Return and print implicitly


Title: Produce n n-squares of integers with rotating *'s in consecuitive corners

Body:
The objective is to produce output of n squares (nxn) of random integers (0-9) with a moving * that rotates clockwise around the corners, starting from the top left. The squares should be side by side and separated by a single space.

If n = 0, the output should be empty.

Output for n=1:

*

Output for n=2:

```<code>*3 4*
14 07
</code>```

Output for n=3:

```<code>*34 82* 291
453 224 924
145 158 57*
</code>```

Output for n=4:

```<code>*153 135* 0154 0235
2352 5604 3602 2065
2245 6895 3561 7105
7225 5785 479* *662
</code>```

Notice how, for each square, the * rotates around the corners of the square, from left to right, beginning in the top left corner of the first, then moving to the top right of the second, and so on.

The shortest answer (measured in bytes) wins.

Body:
PHP ,181 Bytes

for($i=-1;++$i<$c=($n=$argv[1])**3;){echo!($i%$q=$n*$n)?"\n":((!$m=$i%$n)?" ":"");echo(!$m&!($b=$i%$q/$n&3)|$m==$n-1&$b==1)&$i<$q|($m==$n-1&$b==2|!$m&$b==3)&$i>$c-$q?"*":rand(0,9);}


答:
Haskell, 30 bytes

foldr(\h(n,d)->(h*n+d,n))(1,0)
```

Recursively adds each layer going outward, updating n/d to h+(1/(n/d)), which equals h+d/n or (h*n+d)/n. The fraction is stored as a tuple of (num,denom). The initial fraction of (1,0) flips to 0/1 which is 0.

Title: Simplify a continued fraction

Body:
Haskell, 30 bytes

foldr(\h(n,d)->(h*n+d,n))(1,0)

Recursively adds each layer going outward, updating n/d to h+(1/(n/d)), which equals h+d/n or (h*n+d)/n. The fraction is stored as a tuple of (num,denom). The initial fraction of (1,0) flips to 0/1 which is 0.


答:
Python, 50 bytes

f=lambda l,n=1,d=0:l and f(l,l.pop()*n+d,n)or(n,d)
```

Builds the continued fraction from the end of the list going backwards, repeatedly updating the fraction n/d on the last element x as n/d -> 1+1/(n/d) == (x*n+d)/n.

Title: Simplify a continued fraction

Body:
Python, 50 bytes

f=lambda l,n=1,d=0:l and f(l,l.pop()*n+d,n)or(n,d)

Builds the continued fraction from the end of the list going backwards, repeatedly updating the fraction n/d on the last element x as n/d -> 1+1/(n/d) == (x*n+d)/n.


问:
Decode the chmod

Challenge

Given a three digit octal permissions number, output the permissions that it grants.

chmod

On UNIX OSes file permissions are changed using the chmod command. There are few different ways of using chmod, but the one we will focus on today is using octal permissions.

The three digits in the permissions number represent a different person:

The first digit represents the permissions for the user

The second digit represents the permissions for the group

The last digit represents the permissions for others

Next, each digit represents a permission as shown below in:

```<code>Key: number | permission

7 | Read Write and Execute
6 | Read and Write
5 | Read and Execute
4 | Read only
3 | Write and Execute
2 | Write only
1 | Execute only
0 | None
</code>```

Input

The input will be the three digit number as a string, e.g.:

```<code>133
</code>```

or

```<code>007
</code>```

This will be passed either via STDIN or via function arguments.

Output

Your output should be the different permissions for each of the user, the group and the others. You must display this information like so:

```<code>User:   ddd
Group:  ddd
Others: ddd
</code>```

Where there are three spaces after User, two spaces after Group and one space after Others. You replace ddd with the permissions information.

Your output may be to STDOUT or as a returned string.

Examples

Input: 666

Output:

```<code>User:   Read and Write
Group:  Read and Write
Others: Read and Write
</code>```

Input: 042

Output:

```<code>User:   None
Group:  Read only
Others: Write only
</code>```

Input: 644

Output:

```<code>User:   Read and Write
Group:  Read only
Others: Read only
</code>```

Winning

The shortest code in bytes wins.

答:
Python 3, 191 bytes

def d(n):a,b,c,d,e=' and ',' only',"Execute","Write","Read";l=["None",c+b,d+b,d+a+c,e+b,e+a+c,e+a+d,e+" "+d+a+c];y,u,i=map(int,n);return"User:   %s\nGroup:  %s\nOthers: %s\n"%(l[y],l[u],l[i])
```
<p>ungolfed</p>
```def d(n):
    a,b,c,d,e=' and ',' only',"Execute","Write","Read"
    l=["None",c+b,d+b,d+a+c,e+b,e+a+c,e+a+d,e+" "+d+a+c]
    y,u,i=map(int,n)
    return"User:   %s\nGroup:  %s\nOthers: %s\n"%(l[y],l[u],l[i])
```

Title: Decode the chmod

Body:
Python 3, 191 bytes

def d(n):a,b,c,d,e=' and ',' only',"Execute","Write","Read";l=["None",c+b,d+b,d+a+c,e+b,e+a+c,e+a+d,e+" "+d+a+c];y,u,i=map(int,n);return"User:   %s\nGroup:  %s\nOthers: %s\n"%(l[y],l[u],l[i])

ungolfed

def d(n):
    a,b,c,d,e=' and ',' only',"Execute","Write","Read"
    l=["None",c+b,d+b,d+a+c,e+b,e+a+c,e+a+d,e+" "+d+a+c]
    y,u,i=map(int,n)
    return"User:   %s\nGroup:  %s\nOthers: %s\n"%(l[y],l[u],l[i])


问:
Create a T9 keyboard
This question asks for a T9 dictionary matching functionality which is a very interesting problem. But T9 has another way of typing and that is typing character-by-character. You would NOT need a dictionary to implement this keyboard.

Here is key-map of a T9 keyboard if you forgot:

```<code>+-------+-------+-------+
|   1   |   2   |   3   |
|  .?!  |  ABC  |  DEF  |
+-------+-------+-------+
|   4   |   5   |   6   |
|  GHI  |  JKL  |  MNO  |
+-------+-------+-------+
|   7   |   8   |   9   |
| PQRS  |  TUV  |  WXYZ |
+-------+-------+-------+
|   *   |   0   |   #   |
|   ←   | SPACE |   →   |
+-------+-------+-------+
</code>```

How T9 works

To type a character with T9, you need to press number key representing that character n times. n is order of that character written on that key. Numbers are the last character you can type for each key. For example, to type B I press 2 two times, or to type 5 I press 5 four times. To finish typing this character I press #. * is simply backspace. In our version of keyboard there is no capitalization.

Input and output examples:

```<code>8#99999#055#33#999#22#666#2#777#3# → T9 KEYBOARD
</code>```

Explanation:

8 selects T and # moves to next character

99999 select last character of 9 key which is 9 and # moves to next charachter

0 inserts a space

33 selects second character of  3 key which is K and # moves to next character

And so on...

Rules

Your function or program should accept a string representing T9 keypresses. Output is the resulting text from those keypresses, as outlined above.

This is basic code golf, so the winner is shortest in bytes, and standard rules/loopholes apply.

答:
PHP, 183-10=173 bytes

All versions take input from command line argument; call with php -r '' <string>.

Note: All versions throw a warning if input starts with *.

Prepend $o=[]; to the code to remove that flaw.

```<code>preg_match_all("%(\d)\1*|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]="- 0   .?!1 ABC2 DEF3 GHI4 JKL5 MNO6 PQRS7TUV8 WXYZ9"[$w[0]*5+strlen($w)];echo join($o);
</code>```

does not need hash tags

fails if a key is pressed too often

210-10-??=??? bytes

```<code>$a=[" 0",".?!1",ABC2,DEF3,GHI4,JKL5,MNO6,PQRS7,TUV8,WXYZ9];preg_match_all("%(\d)\1*|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]=$a[$w[0]][strlen($w)%strlen($a[$w[0]])-1];echo join($o);
</code>```

does not need hash tags

rotates if a key is pressed too often

181 bytes, no bonus

```<code>preg_match_all("%\d+#|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]=" 0   .?!1 ABC2 DEF3 GHI4 JKL5 MNO6 PQRS7TUV8 WXYZ9"[$w[0]*5+strlen($w)-2];echo join($o);
</code>```

breakdown

The "no hash tags" versions split the string to (streak of equal numbers) and (asterisk) and forget everything else. The no-bonus version takes (streak of numbers followed by #) and (asterisk).

Then loop through the matches: If a '*' is found, remove the last element of the result array.

The difference between the versions is in the else part:

no bonus version: offset map string to (key*5), then add (keystrokes=word length-1)-1, add character from that position to result.

simple no-tag version: almost the same, but: (keystrokes=word length); added a character to the map string to get rid of the other -1.

rotating version: take item (key) from map array, add character (keystrokes%item length-1) from that item to result.

Title: Create a T9 keyboard

Body:
PHP, 183-10=173 bytes

All versions take input from command line argument; call with php -r '<code>' <string>.

Note: All versions throw a warning if input starts with *.

Prepend $o=[]; to the code to remove that flaw.

preg_match_all("%(\d)\1*|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]="- 0   .?!1 ABC2 DEF3 GHI4 JKL5 MNO6 PQRS7TUV8 WXYZ9"[$w[0]*5+strlen($w)];echo join($o);

does not need hash tags

fails if a key is pressed too often

210-10-??=??? bytes

$a=[" 0",".?!1",ABC2,DEF3,GHI4,JKL5,MNO6,PQRS7,TUV8,WXYZ9];preg_match_all("%(\d)\1*|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]=$a[$w[0]][strlen($w)%strlen($a[$w[0]])-1];echo join($o);

does not need hash tags

rotates if a key is pressed too often

181 bytes, no bonus

preg_match_all("%\d+#|\*%",$argv[1],$m);foreach($m[0]as$w)if("*"==$w)array_pop($o);else$o[]=" 0   .?!1 ABC2 DEF3 GHI4 JKL5 MNO6 PQRS7TUV8 WXYZ9"[$w[0]*5+strlen($w)-2];echo join($o);

breakdown

The "no hash tags" versions split the string to (streak of equal numbers) and (asterisk) and forget everything else. The no-bonus version takes (streak of numbers followed by #) and (asterisk).

Then loop through the matches: If a '*' is found, remove the last element of the result array.

The difference between the versions is in the else part:

no bonus version: offset map string to (key*5), then add (keystrokes=word length-1)-1, add character from that position to result.

simple no-tag version: almost the same, but: (keystrokes=word length); added a character to the map string to get rid of the other -1.

rotating version: take item (key) from map array, add character (keystrokes%item length-1) from that item to result.


问:
Flexagonal flexagation
Being programmers, watching us flex aren't very interesting. Today we change that! In this challenge you will lex and flex hexaflexagons.

About

For a video introduction, watch viharts video(s) on flexagons

A flexagon is a shape that you can flex to reveal faces other than the top and bottom one; we are making a hexahexaflexagon, which has 6 faces. See the image below on how to fold a hexahexaflexagon out of a strip of paper.

A shows both sides of the strip. The two white triangles are glued together.
This is how you would flex it:

Below is a diagram of possible states and their relationships:

The colored circles represent the 6 triangles with the same number from the first image. Each of the circes have two colors- the bottom most represent the back face (what you would see if you where to flip your flexagon around), which you don't have to consider in this challenge.

The gray circles in the background represent how you can flex your flexagon in any given state: there are 4 different ways to flex it, we call these Left, Right, Up and Down. You don't actually flex in these directions, the important bit is that some are opposite to each other.

If you are in the center you can use Left and Right to go to the other center ones. To get out of the center you use Up and Down. If you aren't in the center you cannot use Left or Right.

```<code>Left/Down = clockwise
Right/Up  = anti-clockwise
</code>```

Challenge

Create a function or program that take as input what should be on the 18 front faces and the 18 back faces of a flexagon, a sequence of left, right, up and down flexes, and return the 8 visible faces after the flexes.

Elaborate example computation:

```<code>flex "hexaflexaperplexia"
     "flexagationdevices"
     [Right, Right, Left]

Divide a strip of paper into 18 triangles:
1/2\3/1\2/3\1/2\3/1\2/3\1/2\3/1\2/3   Front
4/4\5/5\6/6\4/4\5/5\6/6\4/4\5/5\6/6   Back

Write "hexaflexaperplexia" on the front of the paper strip:
1/2\3/1\2/3\1/2\3/1\2/3\1/2\3/1\2/3

hexaflexaperplexia
123123123123123123
h  a  e  p  p  x     Face 1, Initially the front face
 e  f  x  e  l  i    Face 2, Initially the back face
  x  l  a  r  e  a   Face 3, Initially hidden

Write "flexagationdevices" on the back of the paperstrip:
4/4\5/5\6/6\4/4\5/5\6/6\4/4\5/5\6/6

flexagationdevices
445566445566445566
fl    at    ev       Face 4, up from 3
  ex    io    ic     Face 5, up from 2
    ag    nd    es   Face 6, up from 1

Flex it [Right, Right, Left]
  The initial visible face is 1: "haeppx"
  flexing Right ..
  The current visible face is 2: "efxeli"
  flexing Right ..
  The current visible face is 3: "xlarea"
  flexing Left ..
  The current visible face is 2: "efxeli"
  flexed [Right, Right, Left]!

outputting "efxeli"
</code>```

Example implementation: http://jdoodle.com/a/18A

Input and expected output:

```<code>> hexaflexaperplexia flexagationdevices RRL
= efxeli

> loremipsumdolorsit hexaflexamexicania RUU
= riuort

> abcdefghijklmnopqr stuvwxyz1234567890 UL
= I can't flex that way :(

> abcdefghijklmnopqr stuvwxyz1234567890 RRRRLLUDDUUUULDD
= uv1278
</code>```

Rules

You may take input and return output in any reasonable way

If the input is impossible, you should indicate so in some way that is distinct from regular output

Standard loopholes apply

This is Codegolf. Shortest code in bytes win.

Title: Flexagonal flexagation

Body:
Haskell (Lambdabot), <s>270</s> 234 bytes

(!)=((map(snd<$>).groupBy((.fst).(==).fst).sortOn fst).).zip.cycle
o n(a,b)|n>1||b<1=(mod(a+[-1,1,0,0]!!n)3,mod(b+[0,0,-1,1]!!n)3)
(x&y)d|(g,h)<-foldl(flip(.))id(o<$>d)(0,0)=([0,1,2]!x++[3,3,4,4,5,5]!y)!!([0,5,1,1,4,2,2,3,0]!!(3*g+h))

Usage:

> (&) "hexaflexaperplexia" "flexagationdevices" [1,3]
"exioic"

[0,1,2,3] = [left,right,up,down]

Thanks to @Damien for a lot of bytes!


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

答:
SX

Length 1 Code

```<code>水
</code>```

Compiles to: pass

Length 3 Code

```<code>10才
</code>```

returns 11. 才 is equivelant to C's ++.

Length 4 Code

```<code>品*30
</code>```

returns the circumference of a circle with a diameter. Assuming math was importing.

Length 5 Code

```<code>送我(@)
</code>```

compiles to def __init__(self):print(self) and will work if put inside a class.

Factoid: sorry pass isn't really that interesting. Sorta interesting, SX is one of the first golfing langauges (I made it when I was in 7th or 8th grade. It also compiles to python.

Title: Showcase of Languages

Body:
SX

Length 1 Code

水

Compiles to: pass

Length 3 Code

10才

returns 11. 才 is equivelant to C's ++.

Length 4 Code

品*30

returns the circumference of a circle with a diameter. Assuming math was importing.

Length 5 Code

送我(@)

compiles to def __init__(self):print(self) and will work if put inside a class.

Factoid: sorry pass isn't really that interesting. Sorta interesting, SX is one of the first golfing langauges (I made it when I was in 7th or 8th grade. It also compiles to python.


答:
APL, <s>36</s> <s>34</s> <s>39</s> <s>36</s> <s>33</s> <s>29</s> 27

```<code>*+/x={(∇⍣(⊃x>¯1↑⍵))⍵,+/⍵↑⍨-⍴⍕x}⍎¨⍕x←⎕
</code>```

Output 1 if Keith, 0 otherwise

GolfScript strikes again!!

Edit

```<code>+/x={(∇⍣(x>⊢/⍵))⍵,+/⍵↑⍨-⍴⍕x}⍎¨⍕x←⎕
</code>```

Using Right-reduction (⊢/) instead of Take minus 1 (¯1↑), directly saving 1 char and indirectly saves 1 from Disclose (⊃)

Explanation

⍎¨⍕x←⎕ takes evaluated input (treated as a number) and assign it to x. Converts it to a character array (aka "string" in other languages), and loop through each character (digit), converting it to a number. So this results in a numerical array of the digits.

{(∇⍣(x>⊢/⍵))⍵,+/⍵↑⍨-⍴⍕x} is the main "loop" function:

+/⍵↑⍨-⍴⍕x takes the last ⍴⍕x (no. of digits in x) numbers from the array and sums them.

⍵, concatenates it to the end of the array.

(x>⊢/⍵) check if the last number on the array (which doesn't have +/⍵↑⍨-⍴⍕x concatenated yet) is smaller than x and returns 1 or 0

∇⍣ executes this function on the new array that many times. So if the last number is smaller than x, this function recurs. Otherwise just return the new array

After the executing the function, the array contains the sums up to the point where 2 of the numbers are greater than or equal to x (e.g. 14 will generate 1 4 5 9 14 23, 13 will generate 1 3 4 7 11 18 29)

Finally check if each number is equal to x and output the sum of the resulting binary array.

Edit

```<code>1=+/x={(∇⍣(x>⊢/⍵))⍵,+/⍵↑⍨-⍴⍕x}⍎¨⍕x←⎕
</code>```

Added 2 chars :-( to make output 0 if the input is one-digit

Yet another edit

```<code>+/x=¯1↓{(∇⍣(x>⊢/⍵))1↓⍵,+/⍵}⍎¨⍕x←⎕
</code>```

Explanation

The function now drops the first number (1↓) from the array instead of taking the last ⍴⍕x (↑⍨-⍴⍕x).

However, this approach makes 1= not adequate to handle single digit numbers. So it now drops the last number from the array before checking equality to x, adding 1 char

You guessed it: EDIT

```<code>+/x=1↓{1↓⍵,+/⍵}⍣{x≤+/⍵}⍎¨⍕x←⎕
</code>```

Compares x to the newly-added item instead of the old last item, so dropping the first (instead of last) item before checking equality to x is suffice, saving a minus sign.
Saves another 3 by using another form of the Power operator(⍣)

And a 25-char gs answer appears (Orz)

Last edit

```<code>x∊1↓{1↓⍵,+/⍵}⍣{x≤+/⍵}⍎¨⍕x←⎕
</code>```

Can't believe I missed that.

Can't golf it anymore.

Title: Test if given number is a Keith number

Body:
Since Fibonacci numbers and sequences seems like a popular subject for code golf I thought that it might be a fun challenge to code golf with Keith numbers.

So I propose a challenge that is to create a function that takes an integer and gives back a true or false depending on the number is a Keith number or not.

More about Keith numbers

In recreational mathematics, a Keith number or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence:
  14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, …

Numberphile has a video explaining how to calculate a Keith number. But basically you take the digits of a number. Add them together and then take the last digits of the original number and add them to the sum of the calculation, rinse and repeat. And example to make it clear.

14
1 + 4 = 5

  4 + 5 = 9

  5 + 9 = 14

Input

An integer.

Output

True if the number is a Keith number. False if it's not..

Body:
APL, <s>36</s> <s>34</s> <s>39</s> <s>36</s> <s>33</s> <s>29</s> 27

*+/x={(∇⍣(⊃x>¯1↑⍵))⍵,+/⍵↑⍨-⍴⍕x}⍎¨⍕x←⎕

Output 1 if Keith, 0 otherwise

GolfScript strikes again!!

Edit

+/x={(∇⍣(x>⊢/⍵))⍵,+/⍵↑⍨-⍴⍕x}⍎¨⍕x←⎕

Using Right-reduction (⊢/) instead of Take minus 1 (¯1↑), directly saving 1 char and indirectly saves 1 from Disclose (⊃)

Explanation

⍎¨⍕x←⎕ takes evaluated input (treated as a number) and assign it to x. Converts it to a character array (aka "string" in other languages), and loop through each character (digit), converting it to a number. So this results in a numerical array of the digits.

{(∇⍣(x>⊢/⍵))⍵,+/⍵↑⍨-⍴⍕x} is the main "loop" function:

+/⍵↑⍨-⍴⍕x takes the last ⍴⍕x (no. of digits in x) numbers from the array and sums them.

⍵, concatenates it to the end of the array.

(x>⊢/⍵) check if the last number on the array (which doesn't have +/⍵↑⍨-⍴⍕x concatenated yet) is smaller than x and returns 1 or 0

∇⍣ executes this function on the new array that many times. So if the last number is smaller than x, this function recurs. Otherwise just return the new array

After the executing the function, the array contains the sums up to the point where 2 of the numbers are greater than or equal to x (e.g. 14 will generate 1 4 5 9 14 23, 13 will generate 1 3 4 7 11 18 29)

Finally check if each number is equal to x and output the sum of the resulting binary array.

Edit

1=+/x={(∇⍣(x>⊢/⍵))⍵,+/⍵↑⍨-⍴⍕x}⍎¨⍕x←⎕

Added 2 chars :-( to make output 0 if the input is one-digit

Yet another edit

+/x=¯1↓{(∇⍣(x>⊢/⍵))1↓⍵,+/⍵}⍎¨⍕x←⎕

Explanation

The function now drops the first number (1↓) from the array instead of taking the last ⍴⍕x (↑⍨-⍴⍕x).

However, this approach makes 1= not adequate to handle single digit numbers. So it now drops the last number from the array before checking equality to x, adding 1 char

You guessed it: EDIT

+/x=1↓{1↓⍵,+/⍵}⍣{x≤+/⍵}⍎¨⍕x←⎕

Compares x to the newly-added item instead of the old last item, so dropping the first (instead of last) item before checking equality to x is suffice, saving a minus sign.
Saves another 3 by using another form of the Power operator(⍣)

And a 25-char gs answer appears (Orz)

Last edit

x∊1↓{1↓⍵,+/⍵}⍣{x≤+/⍵}⍎¨⍕x←⎕

Can't believe I missed that.

Can't golf it anymore.


问:
StringgnirtSStringgnirtSStringgnirtS
Here is a relatively simple challenge for you.

Given a string of length N, output the string forwards, then backwards, then forwards, then backwards... etc. N times. For example, if your input was

```<code>Hello!
</code>```

You should output:

```<code>Hello!!olleHHello!!olleHHello!!olleH
</code>```

You may also optionally output one trailing newline.

Your submission may be either a full program or a function, and you may take input and output in any reasonable format. For example, you may take IO from STDIN/STDOUT, function arguments and return value, from a file, etc. You can safely assume that the input string will not be empty, and will only contain printable ASCII. You must output the new string on a single line. So, for example, if the output to the last example was

```<code>Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
</code>```

This would not be a valid solution!

Here are some more test cases:

```<code>Input:
a
Output:
a

Input:
abcd
Output:
abcddcbaabcddcba

Input:
OK!
Output:
OK!!KOOK!

Input:
4815162342
Output:
4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184

Input:
PPCG
Output:
PPCGGCPPPPCGGCPP

Input:
42
Output:
4224
</code>```

Leaderboards

Since this is a code-golf challenge, standard loopholes are banned, and the shortest answer in bytes wins! However, this is also a competition to have the shortest answer in any particular langauge. While it's unlikely that a Java answer will beat an answer in perl, or some golfing language, it's still very impressive to have the shortest Java answer. So, you can use this leaderboard to see both

The shortest answer out of all languages, and

The shortest answer in each individual language.

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Pip, <s>11</s> 10 bytes

```<code>L#aORVRV:a
</code>```

Try it online!

Explanation:

```<code>            a is first cmdline argument (implicit)
L#a         Loop len(a) times:
      RV:a   Reverse a and assign back to a
   ORV       Output the reverse of a (since it needs to go forward first then backward)
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Pip, <s>11</s> 10 bytes

L#aORVRV:a

Try it online!

Explanation:

            a is first cmdline argument (implicit)
L#a         Loop len(a) times:
      RV:a   Reverse a and assign back to a
   ORV       Output the reverse of a (since it needs to go forward first then backward)


答:
J, <s>13</s> 8 bytes

Saved 5 bytes thanks to miles!

```<code>#;@$];|.
</code>```

This is a 5-train with the following verbs:

```<code># ;@$ ] ; |.
</code>```

The inner fork is composed of ] (identity), ; (link), and |. (reverse). Observe:

```<code>   (| ; |.) 'Hello!'
+------+------+
|Hello!|!olleH|
+------+------+
</code>```

The outer two verbs make the rest of the train. # is, in this case, the size of the argument, that is, the length. The verb linking these is ;@$, or ravel over reshape. Observe:

```<code>   # 'Hello!'
6
   6 $ (] ; |.) 'Hello!'
+------+------+------+------+------+------+
|Hello!|!olleH|Hello!|!olleH|Hello!|!olleH|
+------+------+------+------+------+------+
   ; 6 $ (] ; |.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
   6 ;@$ (] ; |.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
   (# ;@$ (] ; |.)) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
   (# ;@$ ] ; |.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
   (#;@$];|.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
</code>```

Old solution.

```<code>[:,|.^:(i.@#)
</code>```

Simple enough. |. is reverse, and ^: is power conjunction, which repeats it's left verb (right hand) # of times. When the right argument is a verb, that verb is called on the argument. The right verb in this case is range from zero (i.) to the length (#). When raised to an array, the intermediate results are kept. All that needs to be done is to flatten the array with ,.

Intermediate results

```<code>   (i.@#) 'Hello!'
0 1 2 3 4 5
   |.^:0 1 2 3 4 5 'Hello!'
Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
   |.^:(i.@#) 'Hello!'
Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
   ([:,|.^:(i.@#)) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Here is a relatively simple challenge for you.

Given a string of length N, output the string forwards, then backwards, then forwards, then backwards... etc. N times. For example, if your input was

```<code>Hello!
</code>```

You should output:

```<code>Hello!!olleHHello!!olleHHello!!olleH
</code>```

You may also optionally output one trailing newline.

Your submission may be either a full program or a function, and you may take input and output in any reasonable format. For example, you may take IO from STDIN/STDOUT, function arguments and return value, from a file, etc. You can safely assume that the input string will not be empty, and will only contain printable ASCII. You must output the new string on a single line. So, for example, if the output to the last example was

```<code>Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
</code>```

This would not be a valid solution!

Here are some more test cases:

```<code>Input:
a
Output:
a

Input:
abcd
Output:
abcddcbaabcddcba

Input:
OK!
Output:
OK!!KOOK!

Input:
4815162342
Output:
4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184

Input:
PPCG
Output:
PPCGGCPPPPCGGCPP

Input:
42
Output:
4224
</code>```

Leaderboards

Since this is a code-golf challenge, standard loopholes are banned, and the shortest answer in bytes wins! However, this is also a competition to have the shortest answer in any particular langauge. While it's unlikely that a Java answer will beat an answer in perl, or some golfing language, it's still very impressive to have the shortest Java answer. So, you can use this leaderboard to see both

The shortest answer out of all languages, and

The shortest answer in each individual language.

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
J, <s>13</s> 8 bytes

Saved 5 bytes thanks to miles!

#;@$];|.

This is a 5-train with the following verbs:

# ;@$ ] ; |.

The inner fork is composed of ] (identity), ; (link), and |. (reverse). Observe:

   (| ; |.) 'Hello!'
+------+------+
|Hello!|!olleH|
+------+------+

The outer two verbs make the rest of the train. # is, in this case, the size of the argument, that is, the length. The verb linking these is ;@$, or ravel over reshape. Observe:

   # 'Hello!'
6
   6 $ (] ; |.) 'Hello!'
+------+------+------+------+------+------+
|Hello!|!olleH|Hello!|!olleH|Hello!|!olleH|
+------+------+------+------+------+------+
   ; 6 $ (] ; |.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
   6 ;@$ (] ; |.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
   (# ;@$ (] ; |.)) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
   (# ;@$ ] ; |.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH
   (#;@$];|.) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH

Old solution.

[:,|.^:(i.@#)

Simple enough. |. is reverse, and ^: is power conjunction, which repeats it's left verb (right hand) # of times. When the right argument is a verb, that verb is called on the argument. The right verb in this case is range from zero (i.) to the length (#). When raised to an array, the intermediate results are kept. All that needs to be done is to flatten the array with ,.

Intermediate results

   (i.@#) 'Hello!'
0 1 2 3 4 5
   |.^:0 1 2 3 4 5 'Hello!'
Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
   |.^:(i.@#) 'Hello!'
Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
   ([:,|.^:(i.@#)) 'Hello!'
Hello!!olleHHello!!olleHHello!!olleH


答:
Python, 40 bytes

f=lambda s,i=0:s[i:]and s+f(s[::-1],i+1)
```

A recursive function. Prepends the input string s to the function of the reverse until the counter i exceed the length of s.

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Python, 40 bytes

f=lambda s,i=0:s[i:]and s+f(s[::-1],i+1)

A recursive function. Prepends the input string s to the function of the reverse until the counter i exceed the length of s.


答:
Ruby, 39 bytes

```<code>->(s){s.reverse!.gsub(/./){s.reverse!}}
</code>```

I suck at Ruby. Golfing help is appreciated.

Ruby is a really nice language for this because of .reverse!

Explanation

I was hoping it would be someting simple like:

```<code>s.gsub(/./){s.reverse!}
</code>```

but because of boilerplate/challenge restriction it's longer.

What s.reverse! is very useful. s.reverse! is basically s = s.reverse!, meaning it also mutates s.

What each section of the program does is described below:

```<code>->(s){             # Lambda with argument s
      s.reverse!   # Reverse `s` see above for details
      .gsub(/./)   # Replace every character with...
      {s.reverse!} # the input reversed!
</code>```

The thing about s.reverse! that is great is that everytime it is evaluated the string get's flipped. So as it replaces the string. s is modified!

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Ruby, 39 bytes

->(s){s.reverse!.gsub(/./){s.reverse!}}

I suck at Ruby. Golfing help is appreciated.

Ruby is a really nice language for this because of .reverse!

Explanation

I was hoping it would be someting simple like:

s.gsub(/./){s.reverse!}

but because of boilerplate/challenge restriction it's longer.

What s.reverse! is very useful. s.reverse! is basically s = s.reverse!, meaning it also mutates s.

What each section of the program does is described below:

->(s){             # Lambda with argument s
      s.reverse!   # Reverse `s` see above for details
      .gsub(/./)   # Replace every character with...
      {s.reverse!} # the input reversed!

The thing about s.reverse! that is great is that everytime it is evaluated the string get's flipped. So as it replaces the string. s is modified!


答:
Minkolang, 17 bytes:

```<code>$oId$z$Dz[rz[O]].
</code>```

Try it here!

Explanation

```<code>$o                   Read in whole input as characters
  Id                 Push the length of stack and duplicate
    $z               Pop top of stack and store in register (z)
      $D             Pop top of stack (n) and duplicate whole stack n-1 times
        z[     ]     z times, do the following:
          r          Reverse the stack
           z[O]      z times, pop the top of stack and output as character
                .    Stop.
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Minkolang, 17 bytes:

$oId$z$Dz[rz[O]].

Try it here!

Explanation

$o                   Read in whole input as characters
  Id                 Push the length of stack and duplicate
    $z               Pop top of stack and store in register (z)
      $D             Pop top of stack (n) and duplicate whole stack n-1 times
        z[     ]     z times, do the following:
          r          Reverse the stack
           z[O]      z times, pop the top of stack and output as character
                .    Stop.


答:
Jelly, <s>4</s> 3 bytes

```<code>,Ṛṁ
</code>```

Try it online! or Verify all test cases.

Saved a byte thanks to @Maltysen.

Explanation

```<code>,Ṛṁ  Input: string S
 Ṛ    Reverse S
,     Join S with reverse of S. Makes a list [S, rev(S)]
  ṁ   Mold [S, rev(S)] to len(S) by repeating elements cyclically
      Return and print implicitly as a string
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Jelly, <s>4</s> 3 bytes

,Ṛṁ

Try it online! or Verify all test cases.

Saved a byte thanks to @Maltysen.

Explanation

,Ṛṁ  Input: string S
 Ṛ    Reverse S
,     Join S with reverse of S. Makes a list [S, rev(S)]
  ṁ   Mold [S, rev(S)] to len(S) by repeating elements cyclically
      Return and print implicitly as a string


问:
Simulate the Wireworld cellular automaton
Wireworld is a cellular automaton that was designed to be resemble electrons flowing through wires. Its simple mechanics allow the construction of digital circuits.  It has even permitted the construction of an entire computer.

Your mission is to create the shortest Wireworld implementation in your language of choice.

Each cell in the grid has one out of four states.  The four states are "blank," "copper," "electron head," or "electron tail."

A blank cell will always remain a blank cell

An electron head will always become an electron tail

An electron tail will always become copper

A copper cell will become an electron head iff exactly one or two out of its eight neighbors are electron heads, otherwise it will remain copper

This competition will have a similar style to the Shortest Game of Life competition, but with a few changes.

The grid must be at least 40 by 40 cells

The edges of the grid must NOT wrap around (not a torus). Treat cells outside of the field as being constantly "blank."

It must be possible for the users to enter their own starting configuration.

Staring at blank screens is not fun.  The program must visually display the simulation as it is running.

This is code golf,  fewest bytes wins.

答:
APL, Dyalog (131)

```<code>{h t c←1↓⍵∘=¨F←' htc'⋄⎕SM∘←1 1,⍨⊂N←F[1+⊃+/H h(t∨c≠H←c∧S↑1 1↓1 2∊⍨⊃+/+/K∘.⊖(K←2-⍳3)∘.⌽⊂¯1⌽¯1⊖h↑⍨2+S←25 79)×¨⍳3]⋄∇N⊣⎕DL÷4}↑{79↑⍞}¨⍳25
</code>```

The output is displayed in the ⎕SM window. The simulation runs endlessly. The grid is 79x25 because that's the default size of the ⎕SM window. The electron head is h, tail is t, copper is c. The program reads the starting configuration from the keyboard as 25 lines.

Explanation:

↑{79↑⍞}¨⍳25: read the 79x25 grid

h t c←1↓⍵∘=¨F←' htc': get three matrices, one with the heads, one with the tails and one with the copper. Also set F to the string ' htc'.

⎕SM∘←1 1,⍨⊂N←F[1+⊃+/...×¨⍳3]: The "..." part is a vector of length three, where the elements are matrices showing the new heads, tails, and copper respectively. The heads are multiplied by 1, the tails by 2, and the copper by 3, then we sum these matrices together and add one, giving a matrix of indices into F. N becomes the new state, in the same format as the input, and it is shown on the ⎕SM screen starting from the top-left corner.

¯1⌽¯1⊖h↑⍨2+S←25 79: Add a border of blanks to h by growing it by two rows and columns, then rotating it one right and one down.

⊃+/+/K∘.⊖(K←2-⍳3)∘.⌽⊂: Rotate the matrix in all eight directions and then sum the resulting matrices together, giving the amount of neighbours that are heads on each position.

1 2∊⍨: Set only those positions to 1 which have 1 or 2 neighbours.

S↑1 1↓: Remove the border we added earlier.

H←c∧: The new heads are all those copper cells that have 1 or 2 head neighbours.

t∨c≠H: The new copper cells are all old tails, and all old copper cells that have not become heads.

H h(...): The new heads are H as calculated above, the new tails are the old heads, and the new copper cells are as calculated above.

∇N⊣⎕DL÷4: Wait 1/4th of a second, then run the function again on N.

Body:
APL, Dyalog (131)

{h t c←1↓⍵∘=¨F←' htc'⋄⎕SM∘←1 1,⍨⊂N←F[1+⊃+/H h(t∨c≠H←c∧S↑1 1↓1 2∊⍨⊃+/+/K∘.⊖(K←2-⍳3)∘.⌽⊂¯1⌽¯1⊖h↑⍨2+S←25 79)×¨⍳3]⋄∇N⊣⎕DL÷4}↑{79↑⍞}¨⍳25

The output is displayed in the ⎕SM window. The simulation runs endlessly. The grid is 79x25 because that's the default size of the ⎕SM window. The electron head is h, tail is t, copper is c. The program reads the starting configuration from the keyboard as 25 lines.

Explanation:

↑{79↑⍞}¨⍳25: read the 79x25 grid

h t c←1↓⍵∘=¨F←' htc': get three matrices, one with the heads, one with the tails and one with the copper. Also set F to the string ' htc'.

⎕SM∘←1 1,⍨⊂N←F[1+⊃+/...×¨⍳3]: The "..." part is a vector of length three, where the elements are matrices showing the new heads, tails, and copper respectively. The heads are multiplied by 1, the tails by 2, and the copper by 3, then we sum these matrices together and add one, giving a matrix of indices into F. N becomes the new state, in the same format as the input, and it is shown on the ⎕SM screen starting from the top-left corner.

¯1⌽¯1⊖h↑⍨2+S←25 79: Add a border of blanks to h by growing it by two rows and columns, then rotating it one right and one down.

⊃+/+/K∘.⊖(K←2-⍳3)∘.⌽⊂: Rotate the matrix in all eight directions and then sum the resulting matrices together, giving the amount of neighbours that are heads on each position.

1 2∊⍨: Set only those positions to 1 which have 1 or 2 neighbours.

S↑1 1↓: Remove the border we added earlier.

H←c∧: The new heads are all those copper cells that have 1 or 2 head neighbours.

t∨c≠H: The new copper cells are all old tails, and all old copper cells that have not become heads.

H h(...): The new heads are H as calculated above, the new tails are the old heads, and the new copper cells are as calculated above.

∇N⊣⎕DL÷4: Wait 1/4th of a second, then run the function again on N.


答:
Ruby, 43 bytes

```<code>f=->s,i=s.size{$><<s
i<2||f[s.reverse,i-1]}
</code>```

See it on eval.in: https://eval.in/642616

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Ruby, 43 bytes

f=->s,i=s.size{$><<s
i<2||f[s.reverse,i-1]}

See it on eval.in: https://eval.in/642616


问:
An A , or An An?
In English, there is the fun and simple difference between an and a: you use an when preceding a word starting with a vowel sound, and a when the word starts with a consonant sound.

For the sake of simplicity in this challenge, an precedes a word that starts with a vowel (aeiou), and a precedes a word that starts with a consonant.

Input

A string comprising only printable ASCII characters, with [?] appearing in places where you must choose to insert an or a. [?] will always appear before a word. You can assume that the sentence will be grammatically correct and formatted like normal.

Output

The input string with [?] replaced with the appropriate word (an or a). You do have to worry about capitalization!

When to Capitalize

Capitalize a word if it is preceded by no characters (is the first one in the input) or if it is preceded by one of .?! followed by a space.

Examples

```<code>Input: Hello, this is [?] world!
Output: Hello, this is a world!

Input: How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.
Output: How about we build a big building. It will have an orange banana hanging out of a window.

Input: [?] giant en le sky.
Output: A giant en le sky.

Input: [?] yarn ball? [?] big one!
Output: A yarn ball? A big one!

Input: [?] hour ago I met [?] European.
Output: A hour ago I met an European.

Input: Hey sir [Richard], how 'bout [?] cat?
Output: Hey sir [Richard], how 'bout a cat?
</code>```

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

答:
V, 41 bytes

```<code>ÍãÛ?Ý ¨[aeiou]©/an
ÍÛ?Ý/a
Í^aü[.!?] a/A
</code>```

Try it online!, which conveniently can also be used to verify all test cases with no extra byte count.

This takes advantage of V's "Regex Compression". It uses a lot of unprintable characters, so here is a hexdump:

```<code>0000000: cde3 db3f dd85 20a8 5b61 6569 6f75 5da9  ...?.. .[aeiou].
0000010: 2f61 6e0a cddb 3fdd 2f61 0acd 5e61 fc5b  /an...?./a..^a.[
0000020: 2e21 3f5d 2093 612f 41                   .!?] .a/A
</code>```

Title: An A , or An An?

Body:
V, 41 bytes

ÍãÛ?Ý ¨[aeiou]©/an
ÍÛ?Ý/a
Í^aü[.!?] a/A

Try it online!, which conveniently can also be used to verify all test cases with no extra byte count.

This takes advantage of V's "Regex Compression". It uses a lot of unprintable characters, so here is a hexdump:

0000000: cde3 db3f dd85 20a8 5b61 6569 6f75 5da9  ...?.. .[aeiou].
0000010: 2f61 6e0a cddb 3fdd 2f61 0acd 5e61 fc5b  /an...?./a..^a.[
0000020: 2e21 3f5d 2093 612f 41                   .!?] .a/A