答:
Ruby, 82 bytes

```<code>->s{n=s.size-1
(r=-n..n).map{|i|(" "*k=i.abs)+r.map{|j|s[[k+j,k,-j].max]}*" "}*$/}
</code>```

iterates through 1-n..n-1 in both i=y and j=x directions. Without the leading spaces on each line, the output looks like the below, as a result of picking a character from s  with the index  [[i.abs+j,i.abs,-j].max]. Adding leading spaces forms the required hexagon.

```<code>f f f f
f l l l f
f l o o l f
f l o G o l f
f l o o l f
f l l l f
f f f f
</code>```

Ungolfed in test program

```<code>f=->s{
  n=s.size-1             n=string length - 1
  (r=-n..n).map{|i|      iterate from -n to n, build an array of lines
    (" "*k=i.abs)+       k=i.abs. Start each line with k spaces.
    r.map{|j|            iterate from -n to n, build an array of characters.
      s[[k+j,k,-j].max]  select character from s (store null string in array if index past end of string)
    }*" "                concatenate the array of characters into a line, separated by spaces
  }*$/                   concatenate the array of lines into a single string, separate by newlines
}

puts f[gets.chomp]
</code>```

Typical output

```<code>   f f f f
  f l l l f
 f l o o l f
f l o G o l f
 f l o o l f
  f l l l f
   f f f f
</code>```

Title: HexaGolf: Wordagons

Body:
Ruby, 82 bytes

->s{n=s.size-1
(r=-n..n).map{|i|(" "*k=i.abs)+r.map{|j|s[[k+j,k,-j].max]}*" "}*$/}

iterates through 1-n..n-1 in both i=y and j=x directions. Without the leading spaces on each line, the output looks like the below, as a result of picking a character from s  with the index  [[i.abs+j,i.abs,-j].max]. Adding leading spaces forms the required hexagon.

f f f f
f l l l f
f l o o l f
f l o G o l f
f l o o l f
f l l l f
f f f f

Ungolfed in test program

f=->s{
  n=s.size-1             n=string length - 1
  (r=-n..n).map{|i|      iterate from -n to n, build an array of lines
    (" "*k=i.abs)+       k=i.abs. Start each line with k spaces.
    r.map{|j|            iterate from -n to n, build an array of characters.
      s[[k+j,k,-j].max]  select character from s (store null string in array if index past end of string)
    }*" "                concatenate the array of characters into a line, separated by spaces
  }*$/                   concatenate the array of lines into a single string, separate by newlines
}

puts f[gets.chomp]

Typical output

   f f f f
  f l l l f
 f l o o l f
f l o G o l f
 f l o o l f
  f l l l f
   f f f f


问:
Double rotation

Challenge Description

Cycle all letters from the first part of the alphabet in one direction, and letters from the second half of the alphabet in the other. Other characters stay in place.

Examples

1: Hello world

```<code>Hello_world //Input
Hell     ld //Letters from first half of alphabet
    o wor   //Letters from second half of alphabet
     _      //Other characters
dHel     ll //Cycle first letters
    w oro   //Cycle second letters
     _      //Other characters stay
dHelw_oroll //Solution
</code>```

2: codegolf

```<code>codegolf
c deg lf
 o   o

f cde gl
 o   o

focdeogl
</code>```

3.: empty string

```<code>(empty string) //Input
(empty string) //Output
</code>```

Input

String you need to rotate. May be empty. Does not contain newlines.

Output

Rotated input string, trailing newline allowed

May be written to the screen or returned by a function.

Rules

No loopholes allowed

This is code-golf, so shortest code in bytes solving the problem wins

Program must return the correct solution

答:
MATL, 29 bytes

```<code>FT"ttk2Y213:lM@*+)m)1_@^YS9M(
</code>```

Try it online!

Explanation

```<code>FT        % Push arrray [0 1]
"         % For each
  t       %   Duplicate. Takes input string implicitly in the first iteration
  tk      %   Duplicate and convert to lower case
  2Y2     %   Predefined string: 'ab...yz'
  13:     %   Generate vector [1 2 ... 13]
  lM      %   Push 13 again
  @*      %   Multiply by 0 (first iteration) or 1 (second): gives 0 or 13
  +       %   Add: this leaves [1 2 ... 13] as is in the first iteration and
          %   transforms it into [14 15 ... 26] in the second
  )       %   Index: get those letters from the string 'ab...yz'
  m       %   Ismember: logical index of elements of the input that are in
          %   that half of the alphabet
  )       %   Apply index to obtain those elements from the input
  1_@^    %   -1 raised to 0 (first iteration) or 1 (second), i.e. 1 or -1
  YS      %   Circular shift by 1 or -1 respectively
  9M      %   Push the logical index of affected input elements again
  (       %   Assign: put the shifted chars in their original positions
          % End for each. Implicitly display
</code>```

ContentLicense: CC BY-SA 3.0

Title: Double rotation

Body:
MATL, 29 bytes

FT"ttk2Y213:lM@*+)m)1_@^YS9M(

Try it online!

Explanation

FT        % Push arrray [0 1]
"         % For each
  t       %   Duplicate. Takes input string implicitly in the first iteration
  tk      %   Duplicate and convert to lower case
  2Y2     %   Predefined string: 'ab...yz'
  13:     %   Generate vector [1 2 ... 13]
  lM      %   Push 13 again
  @*      %   Multiply by 0 (first iteration) or 1 (second): gives 0 or 13
  +       %   Add: this leaves [1 2 ... 13] as is in the first iteration and
          %   transforms it into [14 15 ... 26] in the second
  )       %   Index: get those letters from the string 'ab...yz'
  m       %   Ismember: logical index of elements of the input that are in
          %   that half of the alphabet
  )       %   Apply index to obtain those elements from the input
  1_@^    %   -1 raised to 0 (first iteration) or 1 (second), i.e. 1 or -1
  YS      %   Circular shift by 1 or -1 respectively
  9M      %   Push the logical index of affected input elements again
  (       %   Assign: put the shifted chars in their original positions
          % End for each. Implicitly display


问:
HexaGolf: Wordagons
See also: Rotatagons

Challenge

Given a string as input, output its wordagon.

Wordagons

A wordagon is a way of representing a string in a hexagon. Now, let's create a wordagon from the string hexa:

Firstly, you start with the first character in the string a place it in the centre:

```<code>h
</code>```

Then, you take the next character in the string and add a hexagonal layer:

```<code> e e
e h e
 e e
</code>```

Then, add the next layer:

```<code>  x x x
 x e e x
x e h e x
 x e e x
  x x x
</code>```

Finally, add the last layer:

```<code>   a a a a
  a x x x a
 a x e e x a
a x e h e x a
 a x e e x a
  a x x x a
   a a a a
</code>```

And you now have the wordagon for the string hexa.

Examples

Here's some I prepared earlier:

hello

```<code>    o o o o o
   o l l l l o
  o l l l l l o
 o l l e e l l o
o l l e h e l l o
 o l l e e l l o
  o l l l l l o
   o l l l l o
    o o o o o
</code>```

PPcg

```<code>   g g g g
  g c c c g
 g c P P c g
g c P P P c g
 g c P P c g
  g c c c g
   g g g g
</code>```

o *

```<code>  * * *
 *     *
*   o   *
 *     *
  * * *
</code>```

(T_T)

```<code>    ) ) ) ) )
   ) T T T T )
  ) T _ _ _ T )
 ) T _ T T _ T )
) T _ T ( T _ T )
 ) T _ T T _ T )
  ) T _ _ _ T )
   ) T T T T )
    ) ) ) ) )
</code>```

Note that trailing and/or leading newlines are allowed.

Winning

The shortest code in bytes wins.

答:
Python 2, 104 bytes

```<code>def f(s):
 for n in range(len(s)*2-1):x=abs(n-len(s)+1);print' '*x+' '.join(s[x+1:][::-1]+s[x]*x+s[x:])
</code>```

Title: HexaGolf: Wordagons

Body:
Python 2, 104 bytes

def f(s):
 for n in range(len(s)*2-1):x=abs(n-len(s)+1);print' '*x+' '.join(s[x+1:][::-1]+s[x]*x+s[x:])


问:
Lucas Vs. The Garage Door Remote

Disclaimer

While I know there is this particular related question, my question uses two garage doors, a randomizing component, and I'm also basing this on real life events, seeing my son accidentally lowered one of said garage doors whilst I was walking out of the garage last week... Nothing like a blow to the head to get the creative juices flowing! ;)

The Background

Lucas (my 15 month old son) likes to play with the garage remote. There are two buttons on this remote, one for the left garage door, and one for the right garage door. Both buttons work in the same manner; press once to get the door to start opening, press again to stop, press again to start closing, press again to stop again, and so on.

Lucas loves this remote, he'll randomly press one of the buttons, or both, or none at all. If both are pressed, no signal is sent, but a press of one button will send out a signal.

So, the code-golf challenge is divided on two parts:

Part One

Generate a 60 character long string representing Lucas random button presses over a minute. "Random" in this case means "with an equal chance of each input at each tick". The characters are as follows:

0: Lucas has either pressed no button, or has pressed both buttons. Either way, no signal has been sent.

1: The button for the left garage door has been pressed by Lucas

2: The button for the right garage door has been pressed by Lucas

Part Two

Using the string generated in Part One, simulate the opening and closing of the two-car garage using the numbers as triggers for opening, stopping and closing these doors.

My garage doors are pretty quick (see Disclaimer above as to why).  Once you press the button it takes four seconds to be fully open or closed.

So, if closed:

0 sec: 0% open (closed); when button is pressed, door starts opening

1 sec: 25% open

2 sec: 50% open

3 sec: 75% open

4 sec: 100% open, door stops

And therefore, if open:

0 sec: 100% open; when button is pressed, door starts closing

1 sec: 75% open

2 sec: 50% open

3 sec: 25% open

4 sec: 0% open (closed), door stops

If a particular door is in motion, a signal to that same door will stop it. The next signal sent to that same door after that will send it moving in the opposite direction. If a door is stopped when it has previously been in motion and is now fully open or fully closed when the "stop" signal is received, the door will register as "stopped" in the fully-open or fully-closed state, ready to move in the opposite direction when it receives a new signal.

With this simulation, both garage doors will be initially in the closed position. So, let's look at a 10 second list of commands and see what happens if Lucas was to perform them on the remote:

```<code>2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
</code>```

Output

The first part of the output requires the display of the 60 character long string of random "0", "1" and "2" characters generated from Part One. eg.
212022112021202211202120221120212022112021202211202120221120

Below this string, is the processing of these "signals" according to the rules mentioned above of how the garage doors will behave with each respective character (on a second by second basis). You should end up with 60 lines as a result below the initial display string.

Each of these processed lines will be in the form of:
N: (L:X% XXXXXXX, R:Y% YYYYYYY) where:

N is the nth character from the respective random string, which will be in the form of a 0, 1, or 2.

X% is the percentage of openness of the left door (there is no zero padding)

XXXXXXX is the status of the left door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".

Y% is the percentage of openness of the right door (there is no zero padding)

YYYYYYY is the status of the right door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".

Example shown below using 10 "signals" and 10 processed lines

```<code>2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
</code>```

This is code-golf, so the shortest code will be the clear winner. I've made this a little easy by using phrases like "opening", "stopped" and "closing", which are all seven letters... so you may want to work that into your strategy.

Best of luck!

答:
PHP, <s>254</s> <s>247</s> <s>246</s> <s>245</s> <s>235</s> <s>230</s> 226 bytes

beating ES again!

```<code>for($t=60;$t--;)$s.=rand()%3;echo$s;for(;++$t<60;print"
$c: ($o[1], $o[2])")for($i=3;--$i;$o[$i]='.LR'[$i].':'.$d[$i]*25 .'% '.[opening,stopped,closing][abs($z-1)])if(((1&$z=&$r[$i])&&!(3&$d[$i]+=2-$z))|$i&$c=$s[$t])$z=++$z%4;
</code>```

golfed down from these 311 (the first complete version, already had some golfing):

```<code><?for($i=60;$i--;)$s.=rand(0,2);echo$s;$d=$r=[0,0];$n=[L,R];$p=[stopped,opening,stopped,closing];for($t=-1;++$t<60;print"
$c: (".join(', ',$x).")")for($m=$c=$s[$t],$i=-1;$i++<1;){if($r[$i]&1)if(!($d[$i]+=2-$r[$i])||4==$d[$i])$m|=$i+1;if($m&$i+1)$r[$i]=(1+$r[$i])%4;$x[$i]="$n[$i]:".($d[$i]*25)."% ".$p[$r[$i]];}
</code>```

breakdown

```<code>for($t=60;$t--;)$s.=rand()%3;   // part 1               also initializes $t to -1
echo$s;
for(
    ;
    ++$t<60;
    print"\n$c: ($o[1], $o[2])" // print output
)
    for($i=3;--$i;  // loop $i from 2 to 1 (door number)
        // generate output
        $o[$i]='.LR'[$i].':'.$d[$i]*25 .'% '
        .[opening,stopped,closing][abs($z-1)]           // map 0123 to 1012
    )
        if(((1&$z=&$r[$i])  // if door in motion        ... and reference the array item
            &&!(3&              // 2. if end position   "&&" needed for short circuit
            $d[$i]+=2-$z        // 1. move door         2-$z maps 1,3 to 1,-1 = delta
            )
        )|$i&$c=$s[$t])     // 3. or if button $i pressed   "|" needed for no short circuit
            $z=++$z%4;          // rotate direction     ++$z%4 maps 0,1,2,3 to 1,2,3,0
        // generate output (loop post condition)
    // print output (loop post condition)
</code>```

Title: Lucas Vs. The Garage Door Remote

Body:
PHP, <s>254</s> <s>247</s> <s>246</s> <s>245</s> <s>235</s> <s>230</s> 226 bytes

beating ES again!

for($t=60;$t--;)$s.=rand()%3;echo$s;for(;++$t<60;print"
$c: ($o[1], $o[2])")for($i=3;--$i;$o[$i]='.LR'[$i].':'.$d[$i]*25 .'% '.[opening,stopped,closing][abs($z-1)])if(((1&$z=&$r[$i])&&!(3&$d[$i]+=2-$z))|$i&$c=$s[$t])$z=++$z%4;

golfed down from these 311 (the first complete version, already had some golfing):

<?for($i=60;$i--;)$s.=rand(0,2);echo$s;$d=$r=[0,0];$n=[L,R];$p=[stopped,opening,stopped,closing];for($t=-1;++$t<60;print"
$c: (".join(', ',$x).")")for($m=$c=$s[$t],$i=-1;$i++<1;){if($r[$i]&1)if(!($d[$i]+=2-$r[$i])||4==$d[$i])$m|=$i+1;if($m&$i+1)$r[$i]=(1+$r[$i])%4;$x[$i]="$n[$i]:".($d[$i]*25)."% ".$p[$r[$i]];}

breakdown

for($t=60;$t--;)$s.=rand()%3;   // part 1               also initializes $t to -1
echo$s;
for(
    ;
    ++$t<60;
    print"\n$c: ($o[1], $o[2])" // print output
)
    for($i=3;--$i;  // loop $i from 2 to 1 (door number)
        // generate output
        $o[$i]='.LR'[$i].':'.$d[$i]*25 .'% '
        .[opening,stopped,closing][abs($z-1)]           // map 0123 to 1012
    )
        if(((1&$z=&$r[$i])  // if door in motion        ... and reference the array item
            &&!(3&              // 2. if end position   "&&" needed for short circuit
            $d[$i]+=2-$z        // 1. move door         2-$z maps 1,3 to 1,-1 = delta
            )
        )|$i&$c=$s[$t])     // 3. or if button $i pressed   "|" needed for no short circuit
            $z=++$z%4;          // rotate direction     ++$z%4 maps 0,1,2,3 to 1,2,3,0
        // generate output (loop post condition)
    // print output (loop post condition)


问:
A Fragile Quine

A Fragile Quine

A fragile quine is a quine that satisfies the property of having each substring made by removing a single character, when evaluated, produces an error.

For example. If your program asdf is a quine, then for it to be fragile, the following programs must error:

```<code>sdf
adf
asf
asd
</code>```

Your program (and all of its substrings) must be fully deterministic, and must be in the same language. A program falling into an infinite loop (that is, failing to terminate), even if not eventually producing an error is considered to "produce an error" for the purposes of this challenge.

Standard loopholes apply, including the usual quine restrictions (e.g. not able to read own source code).

For example, print("foo") is not fragile. All these substrings must error:

```<code>rint("foo")
pint("foo")
prnt("foo")
prit("foo")
prin("foo")
print"foo")
print(foo")
print("oo")
print("fo")
print("fo")
print("foo)
print("foo"
</code>```

The ones that don't error are:

```<code>print("oo")
print("fo")
print("fo")
</code>```

So it is not fragile.

An important note on quines

By consensus, any possible quine must satisfy this:

It must be possible to identify a section of the program which encodes a different part of the program. ("Different" meaning that the two parts appear in different positions.)

Furthermore, a quine must not access its own source, directly or indirectly.

Example

Since I consider JavaScript's function#toString to be "reading it's own source code", I am disallowing it. However, if I weren't to bar it, here is a fragile quine in JavaScript:

```<code>f=(n=b=`f=${f}`)=>(a=(n)==`f=${f}`,n=0,a)&(n!=b)?b:q
</code>```

Tester

Here is a program that, given the source code of your program, generates all programs that must error.

let f = (s) =>
  [...Array(s.length).keys()].map(i =>
    s.slice(0, i) + s.slice(i + 1)).join("\n");

let update = () => {
  output.innerHTML = "";
  output.appendChild(document.createTextNode(f(input.value)));
};

input.addEventListener("change", update);

update();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#output {
  white-space: pre;
}

#input, #output {
  font-family: Consolas, monospace;
}</code>```

<input id="input" value="print('foo')">

```

答:
Python 3, 45 bytes

c='print(end="c=%r;exec(c"%c+c[8*4])';exec(c)
```

Switching to Python 3 so that the trailing newline can be easily removed.

I started out with a stupid structure that had 2 variables instead of 1, but switching to 1 variable only made it 4 bytes shorter.

-(4 + 3) bytes by Dennis.

Title: A Fragile Quine

Body:
Python 3, 45 bytes

c='print(end="c=%r;exec(c"%c+c[8*4])';exec(c)

Switching to Python 3 so that the trailing newline can be easily removed.

I started out with a stupid structure that had 2 variables instead of 1, but switching to 1 variable only made it 4 bytes shorter.

-(4 + 3) bytes by Dennis.


答:
Python, <s>91/92</s> 67 bytes

This was fun!

Now I know about assert:

s='s=%r;assert len(s)==34;print(s%%s)';assert len(s)==34;print(s%s)
```

If a char from string is removed, assert error. I would have done this sooner had I known of this feature, assert.

Title: A Fragile Quine

Body:
A Fragile Quine

A fragile quine is a quine that satisfies the property of having each substring made by removing a single character, when evaluated, produces an error.

For example. If your program asdf is a quine, then for it to be fragile, the following programs must error:

```<code>sdf
adf
asf
asd
</code>```

Your program (and all of its substrings) must be fully deterministic, and must be in the same language. A program falling into an infinite loop (that is, failing to terminate), even if not eventually producing an error is considered to "produce an error" for the purposes of this challenge.

Standard loopholes apply, including the usual quine restrictions (e.g. not able to read own source code).

For example, print("foo") is not fragile. All these substrings must error:

```<code>rint("foo")
pint("foo")
prnt("foo")
prit("foo")
prin("foo")
print"foo")
print(foo")
print("oo")
print("fo")
print("fo")
print("foo)
print("foo"
</code>```

The ones that don't error are:

```<code>print("oo")
print("fo")
print("fo")
</code>```

So it is not fragile.

An important note on quines

By consensus, any possible quine must satisfy this:

It must be possible to identify a section of the program which encodes a different part of the program. ("Different" meaning that the two parts appear in different positions.)

Furthermore, a quine must not access its own source, directly or indirectly.

Example

Since I consider JavaScript's function#toString to be "reading it's own source code", I am disallowing it. However, if I weren't to bar it, here is a fragile quine in JavaScript:

```<code>f=(n=b=`f=${f}`)=>(a=(n)==`f=${f}`,n=0,a)&(n!=b)?b:q
</code>```

Tester

Here is a program that, given the source code of your program, generates all programs that must error.

let f = (s) =>
  [...Array(s.length).keys()].map(i =>
    s.slice(0, i) + s.slice(i + 1)).join("\n");

let update = () => {
  output.innerHTML = "";
  output.appendChild(document.createTextNode(f(input.value)));
};

input.addEventListener("change", update);

update();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#output {
  white-space: pre;
}

#input, #output {
  font-family: Consolas, monospace;
}</code>```

<input id="input" value="print('foo')">

```

Body:
Python, <s>91/92</s> 67 bytes

This was fun!

Now I know about assert:

s='s=%r;assert len(s)==34;print(s%%s)';assert len(s)==34;print(s%s)

If a char from string is removed, assert error. I would have done this sooner had I known of this feature, assert.


问:
Slowly turn a string into another

The Challenge

Given two strings/an array of strings, output the first string slowly shrinking and expanding back into the second string.

You can assume the strings will always start with the same character.

Example

```<code>Input:
"Test", "Testing"

Output:
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing
</code>```

First you output the first word:

```<code>Test
</code>```

Then you keep removing one letter until the string is one character long:

```<code>Tes
Te
T
</code>```

Then keep adding one letter of the second word until it's done:

```<code>Te
Tes
Test
Testi
Testin
Testing
</code>```

(if both strings are one character long, then just output one of them once.)

Test Cases

```<code>"Hello!", "Hi."
Hello!
Hello
Hell
Hel
He
H
Hi
Hi.

"O", "O"

O

"z", "zz"

z
zz

".vimrc", ".minecraft"

.vimrc
.vimr
.vim
.vi
.v
.
.m
.mi
.min
.mine
.minec
.minecr
.minecra
.minecraf
.minecraft

"     ", "   "

SSSSS
SSSS
SSS
SS
S
SS
SSS

"0123456789", "02468"

0123456789
012345678
01234567
0123456
012345
01234
0123
012
01
0
02
024
0246
02468
</code>```

(note: on the space/fourth test case, replace the S with spaces)

Rules

This is code-golf, so shortest answer in bytes wins! Tiebreaker is most upvoted post. Winner will be chosen on 09/10/2016.

Standard loopholes are forbidden.

答:
J, 18 bytes

```<code>]\@],~[:}:[:|.]\@[
</code>```

Ungolfed:

```<code>]\@] ,~ [: }: [: |. ]\@[
</code>```

This is a 7-train:

```<code>]\@] ,~ ([: }: ([: |. ]\@[))
</code>```

The innermost train [: |. ]\@[ consists of a cap [: on the left, so we apply |. (reverse) to the result of ]\@[, which is ]\ (prefixes) over [ (left argument).

Here's what that looks like on the testing, test input:

```<code>   'testing' ([: |. ]\@]) 'test'
test
tes
te
t
</code>```

This gives us the first portion, almost. The 5-train outside of that is ([: }: ([: |. ]\@[)), which applies }: (betail, remove last element) to the above expression:

```<code>   'testing' ([: }: [: |. ]\@]) 'test'
test
tes
te
</code>```

(This is because we can't have a duplicate midpoint.)

The outer part is finally:

```<code>]\@] ,~ ([: }: ([: |. ]\@[))
</code>```

This is composed of ]\@] (prefixes of left argument) and ,~ (append what's to the left with what's to the right), leaving us with the desired result:

```<code>   'testing' (]\@] ,~ ([: }: ([: |. ]\@[))) 'test'
testing
testin
testi
test
tes
te
t
te
tes
test
</code>```

Test cases

```<code>   k =: ]\@] ,~ ([: }: ([: |. ]\@[))
   'o' k 'o'
o
   k~ 'o'
o
   'test' k 'test'
test
tes
te
t
te
tes
test
   k~ 'test'
test
tes
te
t
te
tes
test
   '. . .' k '...'
. . .
. .
. .
.
.
..
...
   'z' k 'zz'
z
zz
</code>```

Title: Slowly turn a string into another

Body:
J, 18 bytes

]\@],~[:}:[:|.]\@[

Ungolfed:

]\@] ,~ [: }: [: |. ]\@[

This is a 7-train:

]\@] ,~ ([: }: ([: |. ]\@[))

The innermost train [: |. ]\@[ consists of a cap [: on the left, so we apply |. (reverse) to the result of ]\@[, which is ]\ (prefixes) over [ (left argument).

Here's what that looks like on the testing, test input:

   'testing' ([: |. ]\@]) 'test'
test
tes
te
t

This gives us the first portion, almost. The 5-train outside of that is ([: }: ([: |. ]\@[)), which applies }: (betail, remove last element) to the above expression:

   'testing' ([: }: [: |. ]\@]) 'test'
test
tes
te

(This is because we can't have a duplicate midpoint.)

The outer part is finally:

]\@] ,~ ([: }: ([: |. ]\@[))

This is composed of ]\@] (prefixes of left argument) and ,~ (append what's to the left with what's to the right), leaving us with the desired result:

   'testing' (]\@] ,~ ([: }: ([: |. ]\@[))) 'test'
testing
testin
testi
test
tes
te
t
te
tes
test

Test cases

   k =: ]\@] ,~ ([: }: ([: |. ]\@[))
   'o' k 'o'
o
   k~ 'o'
o
   'test' k 'test'
test
tes
te
t
te
tes
test
   k~ 'test'
test
tes
te
t
te
tes
test
   '. . .' k '...'
. . .
. .
. .
.
.
..
...
   'z' k 'zz'
z
zz


答:
Python 2, <s>51</s> <s>50</s> 46 bytes

lambda s='lambda s=%r:s[22:]%%s%%s':s[22:]%s%s
```

Verify it on Ideone.

Title: A Fragile Quine

Body:
Python 2, <s>51</s> <s>50</s> 46 bytes

lambda s='lambda s=%r:s[22:]%%s%%s':s[22:]%s%s

Verify it on Ideone.


问:
Print numbers from 1 to 10
This might be a very simple challenge, but I am surprised it hasn't been done on code-golf yet:

Print all Integers from 1 to 10 inclusive in ascending order to standard output.

Your output format can be whatever your language supports. This includes arbitrary separators (commas, semicolons, newlines, combinations of those, etc., but no digits), and prefixes and postfixes (like [...]). However, you may not output any other numbers than 1 through 10. Your program may not take any input. Standard loopholes are disallowed.

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

Leaderboard

var QUESTION_ID=86075,OVERRIDE_USER=42570;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

```

答:
Seriously/Actually, 3 bytes

```<code>9uR
</code>```

Try it online: Seriously, Actually

Explanation:

```<code>9uR
9u   push 9, increment (10)
  R  range(1, 11) ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
</code>```

Title: Print numbers from 1 to 10

Body:
Seriously/Actually, 3 bytes

9uR

Try it online: Seriously, Actually

Explanation:

9uR
9u   push 9, increment (10)
  R  range(1, 11) ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])


答:
Ruby, 89 bytes

```<code>f=->n,q,s{b=s.scan(q).rotate n;s.gsub(q){b.shift}}
puts f[1,/[n-z]/i,f[-1,/[a-m]/i,gets]]
</code>```

Title: Double rotation

Body:
Challenge Description

Cycle all letters from the first part of the alphabet in one direction, and letters from the second half of the alphabet in the other. Other characters stay in place.

Examples

1: Hello world

```<code>Hello_world //Input
Hell     ld //Letters from first half of alphabet
    o wor   //Letters from second half of alphabet
     _      //Other characters
dHel     ll //Cycle first letters
    w oro   //Cycle second letters
     _      //Other characters stay
dHelw_oroll //Solution
</code>```

2: codegolf

```<code>codegolf
c deg lf
 o   o

f cde gl
 o   o

focdeogl
</code>```

3.: empty string

```<code>(empty string) //Input
(empty string) //Output
</code>```

Input

String you need to rotate. May be empty. Does not contain newlines.

Output

Rotated input string, trailing newline allowed

May be written to the screen or returned by a function.

Rules

No loopholes allowed

This is code-golf, so shortest code in bytes solving the problem wins

Program must return the correct solution

Body:
Ruby, 89 bytes

f=->n,q,s{b=s.scan(q).rotate n;s.gsub(q){b.shift}}
puts f[1,/[n-z]/i,f[-1,/[a-m]/i,gets]]


答:
JavaScript (ES6), 118 bytes

```<code>s=>[...Array((l=s.length-1)*2+1)].map((_,i,a)=>a.map((_,j)=>s[Math.max(i-l,l-i,j-l,i-j,l+l-i-j)]||``).join` `).join`\n`
</code>```

Where \n represents the literal newline character. Based on my answer to Hexplosive ASCII-art challenge although parts of the solution resemble @LevelRiverSt's Ruby answer. The various components of the Math.max produce the following output for l=3:

```<code>    i - l           l - i           j - l            i - j        l + l - i - j
- - - - - - -   3 3 3 3 3 3 3   - - - 0 1 2 3    0 - - - - - -    6 5 4 3 2 1 0
- - - - - - -   2 2 2 2 2 2 2   - - - 0 1 2 3    1 0 - - - - -    5 4 3 2 1 0 -
- - - - - - -   1 1 1 1 1 1 1   - - - 0 1 2 3    2 1 0 - - - -    4 3 2 1 0 - -
0 0 0 0 0 0 0   0 0 0 0 0 0 0   - - - 0 1 2 3    3 2 1 0 - - -    3 2 1 0 - - -
1 1 1 1 1 1 1   - - - - - - -   - - - 0 1 2 3    4 3 2 1 0 - -    2 1 0 - - - -
2 2 2 2 2 2 2   - - - - - - -   - - - 0 1 2 3    5 4 3 2 1 0 -    1 0 - - - - -
3 3 3 3 3 3 3   - - - - - - -   - - - 0 1 2 3    6 5 4 3 2 1 0    0 - - - - - -
</code>```

The maximum value is taken, and the values greater than l are removed, thus producing the hexagon shape, while the remaining values map to characters from the string:

```<code>6 5 4 3 3 3 3      3 3 3 3          a a a a
5 4 3 2 2 2 3     3 2 2 2 3        a x x x a
4 3 2 1 1 2 3    3 2 1 1 2 3      a x e e x a
3 2 1 0 1 2 3   3 2 1 0 1 2 3    a x e h e x a
4 3 2 1 1 2 3    3 2 1 1 2 3      a x e e x a
5 4 3 2 2 2 3     3 2 2 2 3        a x x x a
6 5 4 3 3 3 3      3 3 3 3          a a a a
</code>```

Title: HexaGolf: Wordagons

Body:
See also: Rotatagons

Challenge

Given a string as input, output its wordagon.

Wordagons

A wordagon is a way of representing a string in a hexagon. Now, let's create a wordagon from the string hexa:

Firstly, you start with the first character in the string a place it in the centre:

```<code>h
</code>```

Then, you take the next character in the string and add a hexagonal layer:

```<code> e e
e h e
 e e
</code>```

Then, add the next layer:

```<code>  x x x
 x e e x
x e h e x
 x e e x
  x x x
</code>```

Finally, add the last layer:

```<code>   a a a a
  a x x x a
 a x e e x a
a x e h e x a
 a x e e x a
  a x x x a
   a a a a
</code>```

And you now have the wordagon for the string hexa.

Examples

Here's some I prepared earlier:

hello

```<code>    o o o o o
   o l l l l o
  o l l l l l o
 o l l e e l l o
o l l e h e l l o
 o l l e e l l o
  o l l l l l o
   o l l l l o
    o o o o o
</code>```

PPcg

```<code>   g g g g
  g c c c g
 g c P P c g
g c P P P c g
 g c P P c g
  g c c c g
   g g g g
</code>```

o *

```<code>  * * *
 *     *
*   o   *
 *     *
  * * *
</code>```

(T_T)

```<code>    ) ) ) ) )
   ) T T T T )
  ) T _ _ _ T )
 ) T _ T T _ T )
) T _ T ( T _ T )
 ) T _ T T _ T )
  ) T _ _ _ T )
   ) T T T T )
    ) ) ) ) )
</code>```

Note that trailing and/or leading newlines are allowed.

Winning

The shortest code in bytes wins.

Body:
JavaScript (ES6), 118 bytes

s=>[...Array((l=s.length-1)*2+1)].map((_,i,a)=>a.map((_,j)=>s[Math.max(i-l,l-i,j-l,i-j,l+l-i-j)]||``).join` `).join`\n`

Where \n represents the literal newline character. Based on my answer to Hexplosive ASCII-art challenge although parts of the solution resemble @LevelRiverSt's Ruby answer. The various components of the Math.max produce the following output for l=3:

    i - l           l - i           j - l            i - j        l + l - i - j
- - - - - - -   3 3 3 3 3 3 3   - - - 0 1 2 3    0 - - - - - -    6 5 4 3 2 1 0
- - - - - - -   2 2 2 2 2 2 2   - - - 0 1 2 3    1 0 - - - - -    5 4 3 2 1 0 -
- - - - - - -   1 1 1 1 1 1 1   - - - 0 1 2 3    2 1 0 - - - -    4 3 2 1 0 - -
0 0 0 0 0 0 0   0 0 0 0 0 0 0   - - - 0 1 2 3    3 2 1 0 - - -    3 2 1 0 - - -
1 1 1 1 1 1 1   - - - - - - -   - - - 0 1 2 3    4 3 2 1 0 - -    2 1 0 - - - -
2 2 2 2 2 2 2   - - - - - - -   - - - 0 1 2 3    5 4 3 2 1 0 -    1 0 - - - - -
3 3 3 3 3 3 3   - - - - - - -   - - - 0 1 2 3    6 5 4 3 2 1 0    0 - - - - - -

The maximum value is taken, and the values greater than l are removed, thus producing the hexagon shape, while the remaining values map to characters from the string:

6 5 4 3 3 3 3      3 3 3 3          a a a a
5 4 3 2 2 2 3     3 2 2 2 3        a x x x a
4 3 2 1 1 2 3    3 2 1 1 2 3      a x e e x a
3 2 1 0 1 2 3   3 2 1 0 1 2 3    a x e h e x a
4 3 2 1 1 2 3    3 2 1 1 2 3      a x e e x a
5 4 3 2 2 2 3     3 2 2 2 3        a x x x a
6 5 4 3 3 3 3      3 3 3 3          a a a a


问:
When is their birthday?
Donald Knuth was born in 1938, on the 20th day of Capricorn.

The first day of Capricorn is the 22nd December.

Donald Knuth was born on the 10th of January (1938).

The challenge

Write a program or function which takes three inputs about a person (any other specified order is fine):

Their (calendar) year of birth (an integer)

Their sign of the zodiac (a string)

- may be whichever you choose from the following, so long as it is consistent:

all lower case except the first character;

all lower case; or

all upper case.

The (1-based) day of the zodiac period on which they were born (an integer)

...and provides two outputs (the other order is fine if specified):

The day of the month on which they were born (an integer)

Their month of birth (an integer)

More details

If your answer were a function, F, then for Donald Knuth we would run F(1938, 'Capricorn', 20) and receive the output (10, 1)

For the purposes of this challenge you do not need to shift the zodiac due to the shift between the Gregorian calendar and the tropical year, but you do need to account correctly for leap years.

February has 29 days rather than 28 on leap years.

A year is usually a leap year if it is divisible by 4 - the exceptions are when it is divisible by 100 but not 400 (so, 1600 and 2000 were, whereas 1700, 1800, and 1900 were not).

For reference the names of the signs of the zodiac and their inclusive ranges are:

```<code>Aries       21 March     – 20 April
Taurus      21 April     – 21 May
Gemini      22 May       – 21 June
Cancer      22 June      – 22 July
Leo         23 July      – 22 August
Virgo       23 August    – 23 September
Libra       24 September – 23 October
Scorpio     24 October   – 22 November
Sagittarius 23 November  – 21 December
Capricorn   22 December  – 20 January
Aquarius    21 January   – 19 February
Pisces      20 February  – 20 March
</code>```

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

No loopholes, yada yada; you know the drill.

Test cases

```<code>Charles Babbage   F(1791, 'Capricorn',  5) -->  (26, 12)
George Boole      F(1815, 'Scorpio',   10) -->  ( 2, 11)
Herman Hollerith  F(1860, 'Pisces',    10) -->  (29,  2)
Vannevar Bush     F(1890, 'Pisces',    20) -->  (11,  3)
Howard H. Aiken   F(1900, 'Pisces',    17) -->  ( 8,  3)  - note 1900 was not a leap year
Donald Knuth      F(1938, 'Capricorn', 20) -->  (10,  1)
<Future Famed>    F(2000, 'Pisces',    17) -->  ( 7,  3)  - note 2000 was a leap year
</code>```

答:
TSQL, 147 bytes

Golfed:

```<code>DECLARE @ DATETIME='2000',@s char(3)='Pisces',@d INT=17

SELECT @s=CHARINDEX(@s,'  PisAriTauGemCanLeoVirLibScoSagCap')/3,@=DATEADD(m,@s*1,@)+18+substring('101122334432',@s+1,1)*1+@d SELECT day(@),month(@)
</code>```

Ungolfed:

```<code>DECLARE @ DATETIME='2000',@s char(3)='Pisces',@d INT=17

SELECT
  @s=CHARINDEX(@s,'  PisAriTauGemCanLeoVirLibScoSagCap')/3,
  @=DATEADD(m,@s*1,@)+18+substring('101122334432',@s+1,1)*1+@d
SELECT day(@),month(@)
</code>```

Fiddle

Title: When is their birthday?

Body:
TSQL, 147 bytes

Golfed:

DECLARE @ DATETIME='2000',@s char(3)='Pisces',@d INT=17

SELECT @s=CHARINDEX(@s,'  PisAriTauGemCanLeoVirLibScoSagCap')/3,@=DATEADD(m,@s*1,@)+18+substring('101122334432',@s+1,1)*1+@d SELECT day(@),month(@)

Ungolfed:

DECLARE @ DATETIME='2000',@s char(3)='Pisces',@d INT=17

SELECT
  @s=CHARINDEX(@s,'  PisAriTauGemCanLeoVirLibScoSagCap')/3,
  @=DATEADD(m,@s*1,@)+18+substring('101122334432',@s+1,1)*1+@d
SELECT day(@),month(@)

Fiddle


Title: Double rotation

Body:
PHP, 189 bytes

Quite hard to golf... Here is my proposal:

for($p=preg_replace,$b=$p('#[^a-m]#i','',$a=$argv[1]),$i=strlen($b)-1,$b.=$b,$c=$p('#[^n-z]#i','',$a),$c.=$c;($d=$a[$k++])!=='';)echo strpos(z.$b,$d)?$b[$i++]:(strpos(a.$c,$d)?$c[++$j]:$d);


问:
Finding number of digits in an integer
Given an integer n as input write a program to output the numbers of digit in it.

Input

```<code>12346

456
</code>```

Output

```<code>5

3
</code>```

Constraint

```<code>n<=10^9
</code>```

答:
Python 2, 22 bytes

lambda a:len(`abs(a)`)
```

I actually built this myself, before seeing Wasi's answer! This is how I thought of it:

I need: a lambda.

len? False! What about n<0? Should the - be counted? False!

How to eliminate the - in just a few bytes? abs!

[Thinking ends]

Title: Finding number of digits in an integer

Body:
Python 2, 22 bytes

lambda a:len(`abs(a)`)

I actually built this myself, before seeing Wasi's answer! This is how I thought of it:

I need: a lambda.

len? False! What about n<0? Should the - be counted? False!

How to eliminate the - in just a few bytes? abs!

[Thinking ends]


答:
Haskell (lambdabot) - 409 bytes

```<code>p=(cycle[0,1,0,-1],0)
t(d:q,s)=(if d/=0&&(s+d<1||3<s+d)then q else d:q,s+d)
k i(a,b)=[o i,": (L:",j a,", ","R:",j b,")"]>>=id
j(d:_,s)=o(round$(fromIntegral s/4)*100)++"% "++words"closing stopped opening"!!(d+1)
s=scanl$ \(a,b)i->i(t a,t b)
main=do b<-(fmap(round.(*(2::Float))).take 60<$>randoms)<$>getStdGen;putStrLn.unlines$(o=<<b):(zipWith k b.w.s(p,p)$([id,f$f w,second$f w]!!)<$>b)
o=show;f=first;w=tail
</code>```

Title: Lucas Vs. The Garage Door Remote

Body:
Disclaimer

While I know there is this particular related question, my question uses two garage doors, a randomizing component, and I'm also basing this on real life events, seeing my son accidentally lowered one of said garage doors whilst I was walking out of the garage last week... Nothing like a blow to the head to get the creative juices flowing! ;)

The Background

Lucas (my 15 month old son) likes to play with the garage remote. There are two buttons on this remote, one for the left garage door, and one for the right garage door. Both buttons work in the same manner; press once to get the door to start opening, press again to stop, press again to start closing, press again to stop again, and so on.

Lucas loves this remote, he'll randomly press one of the buttons, or both, or none at all. If both are pressed, no signal is sent, but a press of one button will send out a signal.

So, the code-golf challenge is divided on two parts:

Part One

Generate a 60 character long string representing Lucas random button presses over a minute. "Random" in this case means "with an equal chance of each input at each tick". The characters are as follows:

0: Lucas has either pressed no button, or has pressed both buttons. Either way, no signal has been sent.

1: The button for the left garage door has been pressed by Lucas

2: The button for the right garage door has been pressed by Lucas

Part Two

Using the string generated in Part One, simulate the opening and closing of the two-car garage using the numbers as triggers for opening, stopping and closing these doors.

My garage doors are pretty quick (see Disclaimer above as to why).  Once you press the button it takes four seconds to be fully open or closed.

So, if closed:

0 sec: 0% open (closed); when button is pressed, door starts opening

1 sec: 25% open

2 sec: 50% open

3 sec: 75% open

4 sec: 100% open, door stops

And therefore, if open:

0 sec: 100% open; when button is pressed, door starts closing

1 sec: 75% open

2 sec: 50% open

3 sec: 25% open

4 sec: 0% open (closed), door stops

If a particular door is in motion, a signal to that same door will stop it. The next signal sent to that same door after that will send it moving in the opposite direction. If a door is stopped when it has previously been in motion and is now fully open or fully closed when the "stop" signal is received, the door will register as "stopped" in the fully-open or fully-closed state, ready to move in the opposite direction when it receives a new signal.

With this simulation, both garage doors will be initially in the closed position. So, let's look at a 10 second list of commands and see what happens if Lucas was to perform them on the remote:

```<code>2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
</code>```

Output

The first part of the output requires the display of the 60 character long string of random "0", "1" and "2" characters generated from Part One. eg.
212022112021202211202120221120212022112021202211202120221120

Below this string, is the processing of these "signals" according to the rules mentioned above of how the garage doors will behave with each respective character (on a second by second basis). You should end up with 60 lines as a result below the initial display string.

Each of these processed lines will be in the form of:
N: (L:X% XXXXXXX, R:Y% YYYYYYY) where:

N is the nth character from the respective random string, which will be in the form of a 0, 1, or 2.

X% is the percentage of openness of the left door (there is no zero padding)

XXXXXXX is the status of the left door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".

Y% is the percentage of openness of the right door (there is no zero padding)

YYYYYYY is the status of the right door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".

Example shown below using 10 "signals" and 10 processed lines

```<code>2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
</code>```

This is code-golf, so the shortest code will be the clear winner. I've made this a little easy by using phrases like "opening", "stopped" and "closing", which are all seven letters... so you may want to work that into your strategy.

Best of luck!

Body:
Haskell (lambdabot) - 409 bytes

p=(cycle[0,1,0,-1],0)
t(d:q,s)=(if d/=0&&(s+d<1||3<s+d)then q else d:q,s+d)
k i(a,b)=[o i,": (L:",j a,", ","R:",j b,")"]>>=id
j(d:_,s)=o(round$(fromIntegral s/4)*100)++"% "++words"closing stopped opening"!!(d+1)
s=scanl$ \(a,b)i->i(t a,t b)
main=do b<-(fmap(round.(*(2::Float))).take 60<$>randoms)<$>getStdGen;putStrLn.unlines$(o=<<b):(zipWith k b.w.s(p,p)$([id,f$f w,second$f w]!!)<$>b)
o=show;f=first;w=tail


答:
05AB1E, 31 bytes

```<code>R.pvy`¹gN-©×NFs.ø}Sðý®ð×ì})Â¦«»
</code>```

Explanation

Utilizing symmetry to only generate the top part of the hexagon,
then mirroring that to form the lower part.

```<code>R.pv                     }       # for each prefix of the reversed string
                                 # ['f', 'fl', 'flo', 'floG']
    y`                           # split into chars, ex: 'f', 'l', 'o'
      ¹gN-©×                     # repeat the last char len(input)-N times,
                                 # where N is the 0-based list index of the current prefix
                                 # ex: 'oo'
            NF   }               # N times do
              s.ø                # surround current char with the next char on stack
                                 # ex: 'floolf'
                  Sðý            # insert spaces between each letter, ex: 'f l o o l f'
                     ®ð×ì        # prefix string with len(input)-N spaces
                                 # ex: '  f l o o l f'
                          )      # wrap all strings in a list
                           Â¦    # create a reversed copy of the list and
                                 # remove the first item (as we only need the middle once)
                             «»  # concatenate the lists and merge with newlines
</code>```

Try it online!

Title: HexaGolf: Wordagons

Body:
05AB1E, 31 bytes

R.pvy`¹gN-©×NFs.ø}Sðý®ð×ì})Â¦«»

Explanation

Utilizing symmetry to only generate the top part of the hexagon,
then mirroring that to form the lower part.

R.pv                     }       # for each prefix of the reversed string
                                 # ['f', 'fl', 'flo', 'floG']
    y`                           # split into chars, ex: 'f', 'l', 'o'
      ¹gN-©×                     # repeat the last char len(input)-N times,
                                 # where N is the 0-based list index of the current prefix
                                 # ex: 'oo'
            NF   }               # N times do
              s.ø                # surround current char with the next char on stack
                                 # ex: 'floolf'
                  Sðý            # insert spaces between each letter, ex: 'f l o o l f'
                     ®ð×ì        # prefix string with len(input)-N spaces
                                 # ex: '  f l o o l f'
                          )      # wrap all strings in a list
                           Â¦    # create a reversed copy of the list and
                                 # remove the first item (as we only need the middle once)
                             «»  # concatenate the lists and merge with newlines

Try it online!


问:
Implement a Truth-Machine
A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

Gets a number (either 0 or 1) from STDIN.

If that number is 0, print out 0 and terminate.

If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

take input from STDIN or an acceptable alternative

If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program

must output to STDOUT or an acceptable alternative

If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.

when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory

the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of code-golf must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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 snippet:

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Woefully, 266 bytes

First answer in this language!

It's called woefully because the bytecounts are saddening

Woefully is a 2d language with no conditionals, except for the notz/bool command (pop a, push 1 if not zero, else push zero), and combining this with the move char pointer command yields control flow. In a truth machine, the values entered are already zero or one, and are only of two values, so is less complex than some other conditional programs, which kind of defeats the purpose of the truth machine :P

There are two pointers, the instruction pointer (ip), and the char pointer (cp), and it's hard to explain in one post, but the ip goes through the paths, cp stays stationary unless moved by instructions the ip executes.

Woefully has 2 stacks, all pushing is to A, except dupe and AtoB

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

Try it online!

Explanation (difficult from the size) Execution starts at the v, at the A path:

```<code>V   FI    \/  V shows initial char pointer pos, F the pos after movement
|A||X|||||Z|   if input is zero, I if it is 1. The path marked by \/ won't
||A||||||Z|    be executed until the first part has been done, and then only
|||A||||Z|  #X path halts program                          if input is zero
||||A||Z|   # A path pushes input     #Z path pushes one
|||||A||O|
|||||E|||O|
|||||E||||O|   #E path dupes, by peeking top of a stack, pushing to b stack
|||||E|||||O| #O path outputs TOS of A
|||||E||||||O|
|||||E|    ^End of path, go back to char pointer, still over this path
||||||F|      #F path pops a, moves the char pointer
|||||||F|
||||||G|
|||||G|
||||G|
|||G|      #G path pushes 4
||G|
|G|
||H|   #H pops a, moves char pointer by a. the char pointer is (again)
|||H|  #now over F or I, depending on input
|||X|  X are nops
||||X|
|||L|   L path pushes 1
||L|
|L|
|V| V path multiplies both TOS (A and B), pushes to A
|V|
|V|
|V|
||O|
|||O|    O path outputs tos of A
||||O|
|||||O|
||||||O|
End of path, go back to the char pointer. If input was zero, the char
pointer will be over the halting path, so program over, otherwise it's over
the next char, and goes to the infinite one river
</code>```

Note this is somewhat simplified: paths overlap on the corners they meet at.

Title: Implement a Truth-Machine

Body:
Woefully, 266 bytes

First answer in this language!

It's called woefully because the bytecounts are saddening

Woefully is a 2d language with no conditionals, except for the notz/bool command (pop a, push 1 if not zero, else push zero), and combining this with the move char pointer command yields control flow. In a truth machine, the values entered are already zero or one, and are only of two values, so is less complex than some other conditional programs, which kind of defeats the purpose of the truth machine :P

There are two pointers, the instruction pointer (ip), and the char pointer (cp), and it's hard to explain in one post, but the ip goes through the paths, cp stays stationary unless moved by instructions the ip executes.

Woefully has 2 stacks, all pushing is to A, except dupe and AtoB

| || ||||| |
|| |||||| |
||| |||| |
|||| || |
||||| || |
||||| ||| |
||||| |||| |
||||| ||||| |
||||| |||||| |
||||| |
|||||| |
||||||| |
|||||| |
||||| |
|||| |
||| |
|| |
| |
|| |
||| |
||| |
|||| |
||| |
|| |
| |
| |
| |
| |
| |
|| |
||| |
|||| |
||||| |
|||||| |

Try it online!

Explanation (difficult from the size) Execution starts at the v, at the A path:

V   FI    \/  V shows initial char pointer pos, F the pos after movement
|A||X|||||Z|   if input is zero, I if it is 1. The path marked by \/ won't
||A||||||Z|    be executed until the first part has been done, and then only
|||A||||Z|  #X path halts program                          if input is zero
||||A||Z|   # A path pushes input     #Z path pushes one
|||||A||O|
|||||E|||O|
|||||E||||O|   #E path dupes, by peeking top of a stack, pushing to b stack
|||||E|||||O| #O path outputs TOS of A
|||||E||||||O|
|||||E|    ^End of path, go back to char pointer, still over this path
||||||F|      #F path pops a, moves the char pointer
|||||||F|
||||||G|
|||||G|
||||G|
|||G|      #G path pushes 4
||G|
|G|
||H|   #H pops a, moves char pointer by a. the char pointer is (again)
|||H|  #now over F or I, depending on input
|||X|  X are nops
||||X|
|||L|   L path pushes 1
||L|
|L|
|V| V path multiplies both TOS (A and B), pushes to A
|V|
|V|
|V|
||O|
|||O|    O path outputs tos of A
||||O|
|||||O|
||||||O|
End of path, go back to the char pointer. If input was zero, the char
pointer will be over the halting path, so program over, otherwise it's over
the next char, and goes to the infinite one river

Note this is somewhat simplified: paths overlap on the corners they meet at.


答:
Go, 67 bytes

```<code>package main;import."fmt";func main(){s:="";Scan(&s);Print(len(s))}
</code>```

Title: Finding number of digits in an integer

Body:
Given an integer n as input write a program to output the numbers of digit in it.

Input

```<code>12346

456
</code>```

Output

```<code>5

3
</code>```

Constraint

```<code>n<=10^9
</code>```

Body:
Go, 67 bytes

package main;import."fmt";func main(){s:="";Scan(&s);Print(len(s))}


答:
R, 25 bytes

```<code>cat(nchar(scan("stdin")))
</code>```

Title: Finding number of digits in an integer

Body:
R, 25 bytes

cat(nchar(scan("stdin")))


问:
Is this a Smith number?

Challenge description

A Smith number is a composite number whose sum of digits is equal to the sum of sums of digits of its prime factors. Given an integer N, determine if it's a Smith number or not.

The first few Smith numbers are 4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438 (sequence A006753 in OEIS).

Sample input / output

```<code>18: False (sum of digits: 1 + 8 = 9; factors: 2, 3, 3; sum of digits of factors: 2 + 3 + 3 = 8)
22: True
13: False (meets the digit requirement, but is prime)
666: True (sum of digits: 6 + 6 + 6 = 18; factors: 2, 3, 3, 37; sum of digits of factors: 2 + 3 + 3 + 3 + 7 = 18)
-265: False (negative numbers can't be composite)
0: False (not composite)
1: False (not composite)
4937775: True
</code>```

Notes

Your code can be a function (method) or a full working program,

Instead of words like True and False, you can use any truthy and falsy values, as long as it's clear what they are,

This is a code-golf challenge, so make your code as short as possible!

答:
Java 7, <s>509</s> <s>506</s> <s>435</s> <s>426</s> <s>419</s> 230 bytes

```<code>boolean c(int n){return n<2|p(n)?0>1:d(n)==f(n);}int d(int n){return n>9?n%10+d(n/10):n;}int f(int n){int r=0,i;for(i=1;++i<=n;)for(;n%i<1;n/=i,r+=i>9?d(i):i);return r;}boolean p(int n){int i=2;while(i<n)n=n%i++<1?0:n;return n>1;}
</code>```

I should have listened to @BasicallyAlanTuring's comment..

This is one of those questions where I thought "Java+this=no", I upvoted for the idea though :P

Ah well.. Some programming languages use a single byte for the prime-factors or prime-check, but Java is certainly not one of them.

EDIT: Halved the amount of bytes now that I had some time to think about it.

Ungolfed (sort-off..) & test cases:

Try it here.

```<code>class M{
  static boolean c(int n){
    return n < 2 | p(n)
            ? 0 > 1 //false
            : d(n) == f(n);
  }

  // Sums digits of int
  static int d(int n) {
    return n > 9
            ? n%10 + d(n/10)
            : n;
  }

  // Convert int to sum of prime-factors
  static int f(int n) {
    int r = 0,
        i;
    for(i = 1; ++i <= n; ){
      for( ; n % i < 1; n /= i,
                        r += i > 9 ? d(i) : i);
    }
    return r;
  }

  // Checks if the int is a prime
  static boolean p(int n){
    int i = 2;
    while(i < n){
      n = n % i++ < 1
           ? 0
           : n;
    }
    return n > 1;
  }

  public static void main(String[] a){
    System.out.println(c(18));
    System.out.println(c(22));
    System.out.println(c(13));
    System.out.println(c(666));
    System.out.println(c(-256));
    System.out.println(c(0));
    System.out.println(c(1));
    System.out.println(c(4937775));
  }
}
</code>```

Output:

```<code>false
true
false
true
false
false
false
true
</code>```

Title: Is this a Smith number?

Body:
Java 7, <s>509</s> <s>506</s> <s>435</s> <s>426</s> <s>419</s> 230 bytes

boolean c(int n){return n<2|p(n)?0>1:d(n)==f(n);}int d(int n){return n>9?n%10+d(n/10):n;}int f(int n){int r=0,i;for(i=1;++i<=n;)for(;n%i<1;n/=i,r+=i>9?d(i):i);return r;}boolean p(int n){int i=2;while(i<n)n=n%i++<1?0:n;return n>1;}

I should have listened to @BasicallyAlanTuring's comment..

This is one of those questions where I thought "Java+this=no", I upvoted for the idea though :P

Ah well.. Some programming languages use a single byte for the prime-factors or prime-check, but Java is certainly not one of them.

EDIT: Halved the amount of bytes now that I had some time to think about it.

Ungolfed (sort-off..) & test cases:

Try it here.

class M{
  static boolean c(int n){
    return n < 2 | p(n)
            ? 0 > 1 //false
            : d(n) == f(n);
  }

  // Sums digits of int
  static int d(int n) {
    return n > 9
            ? n%10 + d(n/10)
            : n;
  }

  // Convert int to sum of prime-factors
  static int f(int n) {
    int r = 0,
        i;
    for(i = 1; ++i <= n; ){
      for( ; n % i < 1; n /= i,
                        r += i > 9 ? d(i) : i);
    }
    return r;
  }

  // Checks if the int is a prime
  static boolean p(int n){
    int i = 2;
    while(i < n){
      n = n % i++ < 1
           ? 0
           : n;
    }
    return n > 1;
  }

  public static void main(String[] a){
    System.out.println(c(18));
    System.out.println(c(22));
    System.out.println(c(13));
    System.out.println(c(666));
    System.out.println(c(-256));
    System.out.println(c(0));
    System.out.println(c(1));
    System.out.println(c(4937775));
  }
}

Output:

false
true
false
true
false
false
false
true


问:
Two Symbol Math

Introduction

The four basic math operators (+, -, *, /) can be reduced to just two, due to the fact that:

```<code>x + y = x - (-y)
x * y = x / (1/y), y != 0
x * 0 = 0/x
</code>```

Challenge

The challenge is to take input as a "string" containing:

Numbers

Single character variables ("x", "y")

The four basic math operators (+, -, *, /)

Parenthesis

and output a string manipulated so that it would produce the same mathematical result as the input, but containing only the mathematical symbols '-' and '/'

Specifics

Input can be in any acceptable form (file, STDIN, etc.) and may be represented as a string or character array (but not an array of arrays)

Output can be in any acceptable form (file, STDIN, etc.) and may be represented as a string or character array (but not an array of arrays)

You must recognize and maintain balanced parenthesis

Standard loopholes are disallowed

It is your choice if you want to represent x + y as x - -y or x - (-y)

You must maintain the order of operations

You never have to handle invalid input

Input can be empty or a single number/variable, in that case the program should output the input

Note: You do not have to use the substitutions in the introduction, so long as input = output, your program could change 2 * 2 to 8/2, if you wanted

You can assume that "0" is the only way a zero will appear in the equation (I.e. you don't have to handle 1 * (4 - 4))

Suggestion: to test your program, go to this website type in input = output, where input is the input, and output is the output, and if the result is "true" your program handled that case successfully (example, example)

Test Cases

Below are some test cases, input as a single string and output as a single string.

```<code>x + y
x - (-y)

x * y
x / (1/y)

x / y
x / y

x - y
x - y

1
1

5
5

-6
-6

+x
x

1 + (x * 4) - (512 * 3)
1 - (-(x / (1/4))) - (512 / (1/3))

1 - 3 / 4 + l / g
1 - 3/4 - (-(l / g))

5 * 0 / 2
0/5 / 2

(a + g) * 0
0/(a - (-g))
</code>```

Scoring

It's code-golf, so shortest answer in bytes wins. Ties are resolved by first-post.

答:
Dyalog APL, 42 bytes

This maintains APLs order of operations. Note that ÷x is 1÷x

'\+' '×'⎕R'--' '÷÷'('(.*)×0'⎕R'0÷\1'~∘' ')
```

TryAPL online!

( on the result of...

 ~∘' ' remove spaces

 '(.*)×0'⎕R'0÷\1' replace anything followed by "×0" with "0÷" followed by it

) evaluate...

'\+' '×'⎕R'--' '÷÷' replace "+" with "--" and "×" with "÷÷"

To verify:

Assign random non-zero numbers to x, y, l, g, and a.

Execute the original expressions.

Execute the modified expressions.

Compare the results.

Title: Two Symbol Math

Body:
Dyalog APL, 42 bytes

This maintains APLs order of operations. Note that ÷x is 1÷x

'\+' '×'⎕R'--' '÷÷'('(.*)×0'⎕R'0÷\1'~∘' ')

TryAPL online!

( on the result of...

 ~∘' ' remove spaces

 '(.*)×0'⎕R'0÷\1' replace anything followed by "×0" with "0÷" followed by it

) evaluate...

'\+' '×'⎕R'--' '÷÷' replace "+" with "--" and "×" with "÷÷"

To verify:

Assign random non-zero numbers to x, y, l, g, and a.

Execute the original expressions.

Execute the modified expressions.

Compare the results.


答:
C, 111 bytes

```<code>f(char*a, char*b){int l=strlen(a),k=1;while(*a){printf("%s\n",a);a[--l]=0;}while(b[k]) printf("%.*s\n",++k,b);}
</code>```

Ungolfed test

```<code>#include <stdio.h>
#include <string.h>

f(char*a, char*b) {
  int l=strlen(a), k=1;
  while(*a) {
    printf("%s\n",a);
    a[--l]=0;
  }
  while(b[k])
    printf("%.*s\n",++k,b);
}

int main() {
  char a[10] = {0};
  char b[10] = {0};

  for (int i=0; i<5; ++i) {
    a[i] = 'a' + i;
    b[i] = 'a' + i*2;
  }

  f(&(a[0]), &(b[0]));
}
</code>```

Title: Slowly turn a string into another

Body:
The Challenge

Given two strings/an array of strings, output the first string slowly shrinking and expanding back into the second string.

You can assume the strings will always start with the same character.

Example

```<code>Input:
"Test", "Testing"

Output:
Test
Tes
Te
T
Te
Tes
Test
Testi
Testin
Testing
</code>```

First you output the first word:

```<code>Test
</code>```

Then you keep removing one letter until the string is one character long:

```<code>Tes
Te
T
</code>```

Then keep adding one letter of the second word until it's done:

```<code>Te
Tes
Test
Testi
Testin
Testing
</code>```

(if both strings are one character long, then just output one of them once.)

Test Cases

```<code>"Hello!", "Hi."
Hello!
Hello
Hell
Hel
He
H
Hi
Hi.

"O", "O"

O

"z", "zz"

z
zz

".vimrc", ".minecraft"

.vimrc
.vimr
.vim
.vi
.v
.
.m
.mi
.min
.mine
.minec
.minecr
.minecra
.minecraf
.minecraft

"     ", "   "

SSSSS
SSSS
SSS
SS
S
SS
SSS

"0123456789", "02468"

0123456789
012345678
01234567
0123456
012345
01234
0123
012
01
0
02
024
0246
02468
</code>```

(note: on the space/fourth test case, replace the S with spaces)

Rules

This is code-golf, so shortest answer in bytes wins! Tiebreaker is most upvoted post. Winner will be chosen on 09/10/2016.

Standard loopholes are forbidden.

Body:
C, 111 bytes

f(char*a, char*b){int l=strlen(a),k=1;while(*a){printf("%s\n",a);a[--l]=0;}while(b[k]) printf("%.*s\n",++k,b);}

Ungolfed test

#include <stdio.h>
#include <string.h>

f(char*a, char*b) {
  int l=strlen(a), k=1;
  while(*a) {
    printf("%s\n",a);
    a[--l]=0;
  }
  while(b[k])
    printf("%.*s\n",++k,b);
}

int main() {
  char a[10] = {0};
  char b[10] = {0};

  for (int i=0; i<5; ++i) {
    a[i] = 'a' + i;
    b[i] = 'a' + i*2;
  }

  f(&(a[0]), &(b[0]));
}


问:
UNIX Uniq Uknow?

Challenge

You must write a program which takes a string and a flag as input and performs one of the following functions.

Input

If your language does not support command line arguments, you may take the arguments as input via STDIN.

The flag will be two characters: a dash and an ASCII character such as -d or -c.

Functions

The following is the list of functions which you must implement in your program. The title of each is the flag which corresponds to the function.

Counting: -c

This counts the number of duplicate lines in the input file. For example, if the input is:

```<code>aa
aa
bb
bb
bb
xx
</code>```

The output will be:

```<code>2 aa
3 bb
1 xx
</code>```

Because there are two lines of aa, three lines of bb, and one line of xx. The output should be separated by newlines.

Duplication: -d

This shows which lines are duplicates. For example, using the above example string (aa\naa\nbb\nbb\nbb\nxx), the output would be:

```<code>aa
bb
</code>```

Because these are lines which have been duplicated. You should only output each line once.

Duplication: -D

This is almost the same as -d except it outputs each line the number of times that it occurs in the input file. For example, using the example string the output will be:

```<code>aa
aa
bb
bb
bb
</code>```

Because aa occurs twice and bb occurs three times.

Unique: -u

Similar to above except it only prints unique lines. For example, using the example file, the output will be:

```<code>xx
</code>```

Because xx is the only unique line. Also, due to xx being unique, you will only ever have to output this once.

Example

Note that although the input string will not always be sorted, the output must be sorted alphabetically. For example, for the following input:

```<code>hello world
apple pie
zebra
dog
hello world
apple pie
apple pie
apple pie
</code>```

The output for each of the flags would be:

-c

```<code>4 apple pie
1 dog
2 hello world
1 zebra
</code>```

-d

```<code>apple pie
hello world
</code>```

-D

```<code>apple pie
apple pie
apple pie
apple pie
hello world
hello world
</code>```

-u

```<code>dog
zebra
</code>```

Rules

Your programs must not use the UNIX program uniq as, frankly, that is plain cheating.

All output should be to STDOUT.

The file will only ever contain lowercase, alphabetical characters, newlines and spaces:

```<code>2 aa
3 bb
1 xx
</code>```0

The output should be sorted alphabetically.

In case there is any confusion, programs written on any operating system can enter. The challenge is not limited to UNIX.

As per PPCG standard, functions and anonymous functions are allowed, taking input via their arguments and outputting via a returned string.

Winning

As this is code-golf, the shortest code in bytes wins.

答:
Lua, 270 Bytes

Well, that ended being way longer than I though it would, but I'm happy with it.

Takes in a filename via command-line and forms two array while reading it's content (t={line, repetitions} and T={index, line}). Sorts T then outputs via STDOUT depending on the flag.

```<code>f,m=...io.input(f)t={}T={}for l in io.lines()do
l=l.."\n"t[l]=t[l]and t[l]+1or 1T[#T+1]=t[l]<2 and l or nil
end
table.sort(T)o=""for i=1,#T
do
k=T[i]v=t[k]o=o..(m=="-c"and v.." "..k
or m=="-D"and k:rep(v)or
m=="-d"and v>1 and k
or m=="-u" and v<2 and k or'')end
print(o)
</code>```

Explanation

```<code>f,m=...                        -- shorthands for the inputs
io.input(f)                    -- set the file f as the current input stream
t={}                           -- set the array linking a line to its number of occurrence
T={}                           -- set the array containing each line once for sorting purpose
for l in io.lines()            -- iterate over each line in the file
do
    l=l.."\n"                  -- add a newline at the end of it
    t[l]=t[l]                  -- if it's not the first time we see this line
           and t[l]+1          -- increment its number of occurence
         or 1                  -- else set it to 1 occurence
    T[#T+1]=t[l]<2 and l or nil-- and set it in our listing
end
table.sort(T)                  -- sort the list of line
o=""                           -- initialise the output to an empty string
for i=1,#T                     -- iterate over each entry in T
do
    k=T[i]                     -- shorthand for the line's string
    v=t[k]                     -- shorthand for its number of occurence

    -- the following nested ternaries are basically a chained if/elseif
    o=o..                      -- at the end of our current output string
      (m=="-c"                 -- if the flag is -c(ount)
          and v.." "..k        -- add the number of occurrence and the corresponding string
        or m=="-D"             -- if the flag is -D(uplicates)
          and k:rep(v)         -- add v times the line
      or m=="-d" and v>1       -- if the flag is -d(uplicates) and it has appeared >2 times
          and k                -- add this line
      or m=="-u" and v<2       -- if the flag is -u(niq) and it has appeared only once
          and k                -- add this line
        or '')                 -- if neither of these cases are true, had an empty string
end
print(o)                       -- output what we formatted previously :)
</code>```

Title: UNIX Uniq Uknow?

Body:
Lua, 270 Bytes

Well, that ended being way longer than I though it would, but I'm happy with it.

Takes in a filename via command-line and forms two array while reading it's content (t={line, repetitions} and T={index, line}). Sorts T then outputs via STDOUT depending on the flag.

f,m=...io.input(f)t={}T={}for l in io.lines()do
l=l.."\n"t[l]=t[l]and t[l]+1or 1T[#T+1]=t[l]<2 and l or nil
end
table.sort(T)o=""for i=1,#T
do
k=T[i]v=t[k]o=o..(m=="-c"and v.." "..k
or m=="-D"and k:rep(v)or
m=="-d"and v>1 and k
or m=="-u" and v<2 and k or'')end
print(o)

Explanation

f,m=...                        -- shorthands for the inputs
io.input(f)                    -- set the file f as the current input stream
t={}                           -- set the array linking a line to its number of occurrence
T={}                           -- set the array containing each line once for sorting purpose
for l in io.lines()            -- iterate over each line in the file
do
    l=l.."\n"                  -- add a newline at the end of it
    t[l]=t[l]                  -- if it's not the first time we see this line
           and t[l]+1          -- increment its number of occurence
         or 1                  -- else set it to 1 occurence
    T[#T+1]=t[l]<2 and l or nil-- and set it in our listing
end
table.sort(T)                  -- sort the list of line
o=""                           -- initialise the output to an empty string
for i=1,#T                     -- iterate over each entry in T
do
    k=T[i]                     -- shorthand for the line's string
    v=t[k]                     -- shorthand for its number of occurence

    -- the following nested ternaries are basically a chained if/elseif
    o=o..                      -- at the end of our current output string
      (m=="-c"                 -- if the flag is -c(ount)
          and v.." "..k        -- add the number of occurrence and the corresponding string
        or m=="-D"             -- if the flag is -D(uplicates)
          and k:rep(v)         -- add v times the line
      or m=="-d" and v>1       -- if the flag is -d(uplicates) and it has appeared >2 times
          and k                -- add this line
      or m=="-u" and v<2       -- if the flag is -u(niq) and it has appeared only once
          and k                -- add this line
        or '')                 -- if neither of these cases are true, had an empty string
end
print(o)                       -- output what we formatted previously :)


答:
Python 2, 149 bytes

s=input();g=lambda(a,b):lambda c:a<c.lower()<b
for f in g('`n'),g('m{'):
 t='';u=filter(f,s)[-1:]
 for c in s:
  if f(c):c,u=u,c
  t=c+t
 s=t
print s
```

Title: Double rotation

Body:
Challenge Description

Cycle all letters from the first part of the alphabet in one direction, and letters from the second half of the alphabet in the other. Other characters stay in place.

Examples

1: Hello world

```<code>Hello_world //Input
Hell     ld //Letters from first half of alphabet
    o wor   //Letters from second half of alphabet
     _      //Other characters
dHel     ll //Cycle first letters
    w oro   //Cycle second letters
     _      //Other characters stay
dHelw_oroll //Solution
</code>```

2: codegolf

```<code>codegolf
c deg lf
 o   o

f cde gl
 o   o

focdeogl
</code>```

3.: empty string

```<code>(empty string) //Input
(empty string) //Output
</code>```

Input

String you need to rotate. May be empty. Does not contain newlines.

Output

Rotated input string, trailing newline allowed

May be written to the screen or returned by a function.

Rules

No loopholes allowed

This is code-golf, so shortest code in bytes solving the problem wins

Program must return the correct solution


答:
PHP - 202 bytes

```<code>$w=$argv[1];$l=$i=$a=strlen($w)-1;while(-$l<=$i){$s=join(" ",str_split(str_repeat($w[$l],($a-1)/2).substr($w,$a?$a:1,$l+1),1));echo str_pad("",$a).strrev($s).($a%2?" ":" {$w[$a]} ")."$s
";$a=abs(--$i);}
</code>```

Usage from command line:

```<code>php.exe -r "put the escaped code here" "put your desired word here"
</code>```

for example:

```<code>php.exe -r "$w=$argv[1];$l=$i=$a=strlen($w)-1;while(-$l<=$i){$s=join(\" \",str_split(str_repeat($w[$l],($a-1)/2).substr($w,$a?$a:1,$l+1),1));echo str_pad(\"\",$a).strrev($s).($a%2?\" \":\" {$w[$a]} \").\"$s\n\";$a=abs(--$i);}" "example"
</code>```

Test Suite.

Title: HexaGolf: Wordagons

Body:
See also: Rotatagons

Challenge

Given a string as input, output its wordagon.

Wordagons

A wordagon is a way of representing a string in a hexagon. Now, let's create a wordagon from the string hexa:

Firstly, you start with the first character in the string a place it in the centre:

```<code>h
</code>```

Then, you take the next character in the string and add a hexagonal layer:

```<code> e e
e h e
 e e
</code>```

Then, add the next layer:

```<code>  x x x
 x e e x
x e h e x
 x e e x
  x x x
</code>```

Finally, add the last layer:

```<code>   a a a a
  a x x x a
 a x e e x a
a x e h e x a
 a x e e x a
  a x x x a
   a a a a
</code>```

And you now have the wordagon for the string hexa.

Examples

Here's some I prepared earlier:

hello

```<code>    o o o o o
   o l l l l o
  o l l l l l o
 o l l e e l l o
o l l e h e l l o
 o l l e e l l o
  o l l l l l o
   o l l l l o
    o o o o o
</code>```

PPcg

```<code>   g g g g
  g c c c g
 g c P P c g
g c P P P c g
 g c P P c g
  g c c c g
   g g g g
</code>```

o *

```<code>  * * *
 *     *
*   o   *
 *     *
  * * *
</code>```

(T_T)

```<code>    ) ) ) ) )
   ) T T T T )
  ) T _ _ _ T )
 ) T _ T T _ T )
) T _ T ( T _ T )
 ) T _ T T _ T )
  ) T _ _ _ T )
   ) T T T T )
    ) ) ) ) )
</code>```

Note that trailing and/or leading newlines are allowed.

Winning

The shortest code in bytes wins.

Body:
PHP - 202 bytes

$w=$argv[1];$l=$i=$a=strlen($w)-1;while(-$l<=$i){$s=join(" ",str_split(str_repeat($w[$l],($a-1)/2).substr($w,$a?$a:1,$l+1),1));echo str_pad("",$a).strrev($s).($a%2?" ":" {$w[$a]} ")."$s
";$a=abs(--$i);}

Usage from command line:

php.exe -r "put the escaped code here" "put your desired word here"

for example:

php.exe -r "$w=$argv[1];$l=$i=$a=strlen($w)-1;while(-$l<=$i){$s=join(\" \",str_split(str_repeat($w[$l],($a-1)/2).substr($w,$a?$a:1,$l+1),1));echo str_pad(\"\",$a).strrev($s).($a%2?\" \":\" {$w[$a]} \").\"$s\n\";$a=abs(--$i);}" "example"

Test Suite.


问:
The Path to the Result
Input:

A grid of varying size only containing numbers in the range 00-99, the following four characters: ^; >; v; <, and spaces to fill (and new-lines of course).

Output:

The result of the sum (integer) when you follow the path.

How does this work?

You start at the arrow with the highest number, and follow the path the arrows point to.

For each of the four arrows we'll do a different arithmetic calculation:

> = Addition (+);

< = Subtraction (−);

^ = Multiplication (* or × or ·);

v = Real / Calculator Division (/ or ÷);

(NOTE: The symbols between parenthesis are just added as clarification. If your programming language uses a completely different symbol for the arithmetic operation than the examples, then that is of course completely acceptable.)

Challenge rules:

You can choose the input (to some extent). A string-array would be most logical I think, but a symbol/newline-separated single string is also fine. (Full functions as input that are simply executed in the actual code snippet aren't allowed!)

Trailing spaces for the input are optional.

Numbers 0-9 will have a leading 0 so all numbers plus arrow are of an equal three-character length.

The number & arrow will always have the following format: DDA (D being a digit; A being one of the four arrows).

You use the current value with the previous arithmetic operation (the example below explains this better).

The final arithmetic operation can be ignored because of the rule above.

It is possible to have DDA's in the input-grid that aren't being used in the path to the resulting sum.

There won't be any test-cases for arrows that form a loop.

There won't be any test-cases for dividing by 0.

There won't be any test-cases where dividing creates a decimal sum-result. You only have to worry about integers.

EDIT: Since there weren't any answer yet, I decided to change the grids slightly to perhaps make it easier. I know this is usually not recommended to do with challenges, but since no answers were given yet, I think this will make it slightly easier, giving more (/any) answers:
<s>The spaces between de DDA's are random. There could even be no spaces in between at all.</s> All DDA's and spaces are grouped per three. Also, it is possible to have no spaces between DDA's at all.

Example:

Input:

```<code>94>      66v
   05v   08<
         43>
   03>   00^
</code>```

Path it follows:

```<code>Path it follows   |   Current sum value
________________________________________
94>               |   94  (highest value)
66v               |   160 (+)
08<               |   20  (/)
05v               |   15  (-)
03>               |   5   (/)
00^               |   5   (+)
43>               |   215 (*)
                          '>' after 43 is ignored because it's the last number
</code>```

Output: 215

General Rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases:

```<code>94>      66v           ->     215
   05v   08<
         43>
   03>   00^

77>   80v55^02<        ->     -19
      20>   14^

22>11>15>80>14v        ->     -16
18^17>      10v
00^   90v43^02v
07^11<15<22v01<

99>98>97>96>95>94v     ->     102
93>92>   91v   03<
</code>```

答:
Python 2, <s>409</s> <s>390</s> 377 bytes

def f(p):
 p=map(lambda s:map(lambda d:d==3*(' ',)and(0,-1)or(int(d[0]+d[1]),'><^v'.index(d[2])),zip(s[::3],s[1::3],s[2::3])),p);x,y=max([(x,y)for x in range(len(p[0]))for y in range(len(p))],key=lambda(x,y):p[y][x][0]);r=o=0
 try:
  while 1:
   1/(y*x>=0);d=p[y][x]
   if-1<d[1]:r=eval('r%sd[0]'%'+-*/'[o]);o=d[1];a=(-(o==1),1)[o<1];b=(-(o==2),1)[o>2]
   x+=a;y+=b
 except:print r
```

<p>The second and third indent levels are a raw tab and a raw tab plus a space, respectively. Markdown mangles the raw tabs, so they've been replaced by two spaces.</p>

<p>Ungolfed:</p>

<pre class="lang-py prettyprint-override"><code>def follow(path):
  # Split path's strs into DDAs ((0, -1) for blank, else (int, int))
  path = map(
    lambda s: map(
      lambda dda: (0, -1) if dda == (' ', ' ', ' ') else (int(dda[0] + dda[1]), '><^v'.index(dda[2])),
      zip(s[::3], s[1::3], s[2::3])
    ),
    path
  )

  # Find highest DDA
  x, y = max([(x, y) for x in range(len(path[0])) for y in range(len(path))], key=lambda (x, y): path[y][x][0])

  result = 0
  op = 0  # addition
  try:
    # Keep following the path until we get an IndexError
    while True:
      if y < 0 or x < 0: raise IndexError

      dda = path[y][x]
      if dda[1] != -1:
        # It's not empty - do the operation & change direction
        const = dda[0]

        result = eval('result %s const' % '+-*/'[op])

        op = dda[1]

        dx = 1 if op == 0 else -1 if op == 1 else 0
        dy = 1 if op == 3 else -1 if op == 2 else 0

      # Move to the next thing
      x += dx
      y += dy
  except IndexError:
    # We've exited the path - return
    print result
</code>```

Ideone it! (all test cases)

Title: The Path to the Result

Body:
Python 2, <s>409</s> <s>390</s> 377 bytes

def f(p):
 p=map(lambda s:map(lambda d:d==3*(' ',)and(0,-1)or(int(d[0]+d[1]),'><^v'.index(d[2])),zip(s[::3],s[1::3],s[2::3])),p);x,y=max([(x,y)for x in range(len(p[0]))for y in range(len(p))],key=lambda(x,y):p[y][x][0]);r=o=0
 try:
  while 1:
   1/(y*x>=0);d=p[y][x]
   if-1<d[1]:r=eval('r%sd[0]'%'+-*/'[o]);o=d[1];a=(-(o==1),1)[o<1];b=(-(o==2),1)[o>2]
   x+=a;y+=b
 except:print r

The second and third indent levels are a raw tab and a raw tab plus a space, respectively. Markdown mangles the raw tabs, so they've been replaced by two spaces.

Ungolfed:

def follow(path):
  # Split path's strs into DDAs ((0, -1) for blank, else (int, int))
  path = map(
    lambda s: map(
      lambda dda: (0, -1) if dda == (' ', ' ', ' ') else (int(dda[0] + dda[1]), '><^v'.index(dda[2])),
      zip(s[::3], s[1::3], s[2::3])
    ),
    path
  )

  # Find highest DDA
  x, y = max([(x, y) for x in range(len(path[0])) for y in range(len(path))], key=lambda (x, y): path[y][x][0])

  result = 0
  op = 0  # addition
  try:
    # Keep following the path until we get an IndexError
    while True:
      if y < 0 or x < 0: raise IndexError

      dda = path[y][x]
      if dda[1] != -1:
        # It's not empty - do the operation & change direction
        const = dda[0]

        result = eval('result %s const' % '+-*/'[op])

        op = dda[1]

        dx = 1 if op == 0 else -1 if op == 1 else 0
        dy = 1 if op == 3 else -1 if op == 2 else 0

      # Move to the next thing
      x += dx
      y += dy
  except IndexError:
    # We've exited the path - return
    print result

Ideone it! (all test cases)


问:
Traveling on a flat Earth
Coordinates in the flat-Earth world consist of latitude (x) and longitude (y), which are integers in the range 0...9999. Much like Gaussian integers, but they are always written using this notation:

```<code>411S 370E
</code>```

That is, with S or N appended to the latitude, and E or W appended to the longitude, with space(s) between the two components.

Goal

Write a program (not a function) that reads two coordinates, separated by whitespace, and outputs their sum. The first coordinate is a starting point, the second one is a displacement, and the output is the resulting position.

Input/Output

Since this challenge is partially about formatting, I'll try to define the input and output formats unambiguously.

The preferred input format has 1 space between the coordinate components, no leading zeros, and a newline character between the two coordinates. The program must be able to read the preferred format.

The output can contain any amount of whitespace and leading zeros. If it's different from the preferred input format, the program must be able to read this format too.

Just to make it clear, the input cannot (will not) contain any additional formatting characters. Just spaces and newlines where needed.

Scoring

This is an experiment on a new winning condition. I'll choose the winner by accepting an answer in a few weeks. If a better answer appears afterwards, I'll change the accepted answer.

The score for the program is its byte count. The winning program is one that is shorter than 400 bytes, has the fewest byte count, but is written in the most verbose programming language. To determine the winner:

Remove programs with byte count 400 or more (they can participate but cannot win)

Consider only the shortest program for each programming language

The longest program wins

Polyglots compete against programs in all languages in which they are valid (e.g. if a program is valid in both bash and sh, it competes against programs in both languages).

Test cases

In the test cases, the first two lines are the input, and the third line is the output.

```<code>0S 0E
0S 0W
0N 0E
</code>```

(the direction of zero doesn't matter, both in input and output)

```<code>0S 9999E
9999N 9999W
9999N 0E
</code>```

(maximal values)

```<code>42S 314W
42N 2718W
0N 3032W
</code>```

(the direction of zero doesn't matter in the output)

```<code>5555N 8888W
7777S 0E
2222S 8888W
</code>```

(no negative values; change the direction if you need to change the sign)

```<code>0001N        4545W
0999N        5454W
1000N        9999W
</code>```

(if the program outputs leading zeros and several spaces, it must be able to read them; it must also be able to read input that doesn't contain them)

```<code>8888N 8888W
9999N 9999W
</code>```

(invalid input - any behavior is acceptable, including crash and infinite loop)

答:
PHP, 169 bytes

Inspired by @Paul Drewett:

```<code><?for($i=2;$i--;$e+=$p[1]*(substr($p[1],-1,1)<W?:-1))$n+=($p=explode(' ',trim(fgets(STDIN))))[0]*(substr($p[0],-1)<S?:-1);echo abs($n),'NS'[$n<0],' ',abs($e),'EW'[$e<0];
</code>```

breakdown

```<code>for($i=2;$i--;                                  // loop twice
    $e+=$p[1]*(substr($p[1],-1,1)<W?:-1)        // add longitude to result
)
    $n+=
        ($p=explode(' ',trim(fgets(STDIN))))    // read line, split at blank
    [0]*(substr($p[0],-1)<S?:-1)                // add latitude to result
    ;
echo abs($n),'NS'[$n<0],' ',abs($e),'EW'[$e<0]; // print result
</code>```

PHP, <s>206</s> <s>197</s> 195 bytes

literally speaking, "moste verbose" would probably be Mathematica or Mathlab?

```<code><?function i(){preg_match('#\d+(.) (\d+)(.)#',fgets(STDIN),$m);return[$m[0]*($m[1]<S?:-1),$m[2]*($m[3]<W?:-1)];}echo abs($v=($a=i())[0]+($b=i())[0]),'NS'[$v<0],' ',abs($v=$a[1]+$b[1]),'EW'[$v<0];
</code>```

output is pretty unformatted, not even a trainling newline

prints large numbers for too large result

Now, how can I double the size of this ...

breakdown

```<code>function i()
// read a pair of coordinates from STDIN, return signed values
{
    // read line from STDIN and take (number,character,number,character) from it
    // will produce something like ["111N 222E","N","222","E"]
    preg_match('#\d+(.) (\d+)(.)#',fgets(STDIN),$m);
    return[
        // using a numerical operation on $m[0] casts the string to number (int in this case)
        $m[0]*($m[1]<S?:-1) // convert latitude to signed int: multiply with -1 for $m[1]=='S'
        ,
        $m[2]*($m[3]<W?:-1) // convert longitude to signed int
    ];
}
$a=i();$b=i();  // read coordinates from STDIN
echo            // output:
    abs($v=$a[0]+$b[0])     // 1. unsigned sum of latitudes
    ,'NS'[$v<0]             // 2. direction depending on sign
    ,' ',                   // 3. delimiter
    abs($v=$a[1]+$b[1]),    // 4. unsigned sum of longitudes
    'EW'[$v<0]              // 5. direction depending on sign
;
</code>```

Title: Traveling on a flat Earth

Body:
PHP, 169 bytes

Inspired by @Paul Drewett:

<?for($i=2;$i--;$e+=$p[1]*(substr($p[1],-1,1)<W?:-1))$n+=($p=explode(' ',trim(fgets(STDIN))))[0]*(substr($p[0],-1)<S?:-1);echo abs($n),'NS'[$n<0],' ',abs($e),'EW'[$e<0];

breakdown

for($i=2;$i--;                                  // loop twice
    $e+=$p[1]*(substr($p[1],-1,1)<W?:-1)        // add longitude to result
)
    $n+=
        ($p=explode(' ',trim(fgets(STDIN))))    // read line, split at blank
    [0]*(substr($p[0],-1)<S?:-1)                // add latitude to result
    ;
echo abs($n),'NS'[$n<0],' ',abs($e),'EW'[$e<0]; // print result

PHP, <s>206</s> <s>197</s> 195 bytes

literally speaking, "moste verbose" would probably be Mathematica or Mathlab?

<?function i(){preg_match('#\d+(.) (\d+)(.)#',fgets(STDIN),$m);return[$m[0]*($m[1]<S?:-1),$m[2]*($m[3]<W?:-1)];}echo abs($v=($a=i())[0]+($b=i())[0]),'NS'[$v<0],' ',abs($v=$a[1]+$b[1]),'EW'[$v<0];

output is pretty unformatted, not even a trainling newline

prints large numbers for too large result

Now, how can I double the size of this ...

breakdown

function i()
// read a pair of coordinates from STDIN, return signed values
{
    // read line from STDIN and take (number,character,number,character) from it
    // will produce something like ["111N 222E","N","222","E"]
    preg_match('#\d+(.) (\d+)(.)#',fgets(STDIN),$m);
    return[
        // using a numerical operation on $m[0] casts the string to number (int in this case)
        $m[0]*($m[1]<S?:-1) // convert latitude to signed int: multiply with -1 for $m[1]=='S'
        ,
        $m[2]*($m[3]<W?:-1) // convert longitude to signed int
    ];
}
$a=i();$b=i();  // read coordinates from STDIN
echo            // output:
    abs($v=$a[0]+$b[0])     // 1. unsigned sum of latitudes
    ,'NS'[$v<0]             // 2. direction depending on sign
    ,' ',                   // 3. delimiter
    abs($v=$a[1]+$b[1]),    // 4. unsigned sum of longitudes
    'EW'[$v<0]              // 5. direction depending on sign
;


问:
Build a sandpile
An abelian sandpile, for our purposes, is an infinite grid with integer coordinates, initially empty of sand. After each second, a grain of sand is placed at (0,0). Whenever a grid cell has 4 or more grains of sand, it spills one grain of sand to each of its four neighbors simultaneously. The neighbors of (x,y) are (x-1,y), (x+1,y), (x,y-1), and (x,y+1).

When a cell spills, it may cause its neighbors to spill. Some facts:

This cascade will eventually stop.

The order in which the cells spill is irrelevant; the result will be the same.

Example

After 3 seconds, the grid looks like

```<code>.....
.....
..3..
.....
.....
</code>```

After 4 seconds:

```<code>.....
..1..
.1.1.
..1..
.....
</code>```

After 15 seconds:

```<code>.....
..3..
.333.
..3..
.....
</code>```

And after 16 seconds:

```<code>..1..
.212.
11.11
.212.
..1..
</code>```

The challenge

In as few bytes as possible, write a function that takes a single positive
integer t and outputs a picture of the sandpile after t seconds.

Input

A single positive integer t, in any format you choose.

Output

A picture of the sandpile after t seconds, using the characters

```<code> . 1 2 3
</code>```

Edit: Use any four distinct characters you like, or draw a picture. If you're not using ".123" or "0123", specify in your answer what the characters signify.

Unlike in the examples, your output should contain the minimal number of rows and columns necessary to show the nonzero part of the sandpile.

That is, for input 3, the output should be

```<code> 3
</code>```

For 4, the output should be

```<code> .1.
 1.1
 .1.
</code>```

Scoring

Standard golf scoring applies.

Rules

No language functions or libraries that already know what a sandpile is are allowed.

Edit: The output section has been edited, the character set restriction has been completely lifted. Use any four distinct characters or colors you like.

答:
Scala, 274 bytes

```<code>val t=args(0).toInt
val s=(Math.sqrt(t)+1).toInt
val (a,c)=(Array.ofDim[Int](s,s),s/2)
(1 to t).map{_=> ?(c,c)}
println(a.map{_.mkString}.mkString("\n"))
def?(b:Int,c:Int):Unit={
a(b)(c)+=1
if(a(b)(c)<4)return
a(b)(c)=0
?(b+1,c)
?(b-1,c)
?(b,c+1)
?(b,c-1)
}
</code>```

Usage:

scala sandpile.scala <iterations>

I don't think there is a lot to explain about this one. Basically it just adds one grain of sand to the center. Then checks if it is larger than 4, if so it'll spill over and check for all neighbours larger than 4, spill over, etc. It's quite fast.

Performance:

t=10000  72ms

t=20000  167ms

t=30000  419ms

t=40000  659ms

t=100000 3413ms

t=1000000 about 6 minutes

Title: Build a sandpile

Body:
Scala, 274 bytes

val t=args(0).toInt
val s=(Math.sqrt(t)+1).toInt
val (a,c)=(Array.ofDim[Int](s,s),s/2)
(1 to t).map{_=> ?(c,c)}
println(a.map{_.mkString}.mkString("\n"))
def?(b:Int,c:Int):Unit={
a(b)(c)+=1
if(a(b)(c)<4)return
a(b)(c)=0
?(b+1,c)
?(b-1,c)
?(b,c+1)
?(b,c-1)
}

Usage:

scala sandpile.scala <iterations>

I don't think there is a lot to explain about this one. Basically it just adds one grain of sand to the center. Then checks if it is larger than 4, if so it'll spill over and check for all neighbours larger than 4, spill over, etc. It's quite fast.

Performance:

t=10000  72ms

t=20000  167ms

t=30000  419ms

t=40000  659ms

t=100000 3413ms

t=1000000 about 6 minutes