答:
(lambdabot) Haskell - 49 bytes

```<code>f q=[x++show n|x<-reverse.tail$inits q,n<-[0..9]]
</code>```

Lambdabot is a IRC bot over at #haskell; it automatically imports a bunch of modules, including Data.List which is where inits live. And because a language is defined by its implementation, I can call this lambdabot haskell and not pay the bytes for the imports.

Regular Haskell:

```<code>import Data.List
f q=[x++show n|x<-reverse.tail$inits q,n<-[0..9]]
</code>```

Title: Invalid Invali Inval

Body:
(lambdabot) Haskell - 49 bytes

f q=[x++show n|x<-reverse.tail$inits q,n<-[0..9]]

Lambdabot is a IRC bot over at #haskell; it automatically imports a bunch of modules, including Data.List which is where inits live. And because a language is defined by its implementation, I can call this lambdabot haskell and not pay the bytes for the imports.

Regular Haskell:

import Data.List
f q=[x++show n|x<-reverse.tail$inits q,n<-[0..9]]


问:
Constructible n-gons
A constructible \$n\$-gon is a regular polygon with n sides that you can construct with only a compass and an unmarked ruler.

As stated by Gauss, the only \$n\$ for which a \$n\$-gon is constructible is a product of any number of distinct Fermat primes and a power of \$2\$ (ie. \$n = 2^k \times p_1 \times p_2 \times ...\$ with \$k\$ being an integer and every \$p_i\$ some distinct Fermat prime).

A Fermat prime is a prime which can be expressed as \$2^{2^n}+1\$ with \$n\$ a positive integer. The only known Fermat primes are for \$n = 0, 1, 2, 3 \text{ and } 4\$

The challenge

Given an integer \$n>2\$, say if the \$n\$-gon is constructible or not.

Specification

Your program or function should take an integer or a string representing said integer (either in unary, binary, decimal or any other base) and return or print a truthy or falsy value.

This is code-golf, so shortest answer wins, standard loopholes apply.

Relevant OEIS

Examples

```<code>3 -> True
9 -> False
17 -> True
1024 -> True
65537 -> True
67109888 -> True
67109889 -> False
</code>```

答:
Mathematica, 24 bytes

```<code>e=EulerPhi
e@e@#==e@#/2&
</code>```

Uses the following classification from OEIS:

Computable as numbers such that cototient-of-totient equals the totient-of-totient.

The totient φ(x) of an integer x is the number of positive integers below x that are coprime to x. The cototient is the number of positive integers that aren't, i.e. x-φ(x). If the totient is equal to the cototient, that means that the totient of φ(x) == x/2.

The more straightforward classification

These are also the numbers for which phi(n) is a power of 2.

ends up being a byte longer:

```<code>IntegerQ@Log2@EulerPhi@#&
</code>```

ContentLicense: CC BY-SA 4.0

Title: Constructible n-gons

Body:
Mathematica, 24 bytes

e=EulerPhi
e@e@#==e@#/2&

Uses the following classification from OEIS:

Computable as numbers such that cototient-of-totient equals the totient-of-totient.

The totient φ(x) of an integer x is the number of positive integers below x that are coprime to x. The cototient is the number of positive integers that aren't, i.e. x-φ(x). If the totient is equal to the cototient, that means that the totient of φ(x) == x/2.

The more straightforward classification

These are also the numbers for which phi(n) is a power of 2.

ends up being a byte longer:

IntegerQ@Log2@EulerPhi@#&

ContentLicense: CC BY-SA 3.0


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

答:
JavaScript, <s>418</s> <s>416</s> <s>406</s> <s>400</s> 393 bytes

Creates an anonymous function that displays the output on the console.

var f =
    t=>{a=(q,w)=>Math.max(q,w);c=_=>{x=a(p[0],x);y=a(p[1],y);m[p]=(g(p)+1)%4;if(!m[p]){s.push([p[0],p[1]]);}};x=y=0,m={};g=k=>{v=m[k];return!v?0:v;};m[o=[0,0]]=1;s=[];while(--t){m[o]=(m[o]+1)%4;if(!m[o]){s.push(o);}while(s.length){p=s.pop();p[0]++;c();p[0]-=2;c();p[0]++;p[1]++;c();p[1]-=2;c();p[1]++;}}s='';for(i=-x;i<=x;i++){for(j=-y;j<=y;j++){v=g([i,j]);s+=v==0?'.':v;}s+='\n';}console.log(s);}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="i" type="number"><input type="button" value="Run" onclick="var v = +document.getElementById('i').value; if (v>0) f(v)"></code>```

Title: Build a sandpile

Body:
JavaScript, <s>418</s> <s>416</s> <s>406</s> <s>400</s> 393 bytes

Creates an anonymous function that displays the output on the console.

var f =
    t=>{a=(q,w)=>Math.max(q,w);c=_=>{x=a(p[0],x);y=a(p[1],y);m[p]=(g(p)+1)%4;if(!m[p]){s.push([p[0],p[1]]);}};x=y=0,m={};g=k=>{v=m[k];return!v?0:v;};m[o=[0,0]]=1;s=[];while(--t){m[o]=(m[o]+1)%4;if(!m[o]){s.push(o);}while(s.length){p=s.pop();p[0]++;c();p[0]-=2;c();p[0]++;p[1]++;c();p[1]-=2;c();p[1]++;}}s='';for(i=-x;i<=x;i++){for(j=-y;j<=y;j++){v=g([i,j]);s+=v==0?'.':v;}s+='\n';}console.log(s);}

<input id="i" type="number"><input type="button" value="Run" onclick="var v = +document.getElementById('i').value; if (v>0) f(v)">


答:
Jelly, <s>7</s> 5 bytes

Thanks to Sp3000 for saving 2 bytes.

```<code>ÆṪBSỊ
</code>```

Uses the following classification:

These are also the numbers for which phi(n) is a power of 2.

Where phi is Euler's totient function.

```<code>ÆṪ        # Compute φ(n).
  B       # Convert to binary.
   S      # Sum bits.
    Ị     # Check whether it's less than or equal to 1. This can only be the
          # case if the binary representation was of the form [1 0 0 ... 0], i.e.
          e# a power of 2.
</code>```

Try it online!

Alternatively (credits to xnor):

```<code>ÆṪ’BP
ÆṪ        # Compute φ(n).
  ’       # Decrement.
   B      # Convert to binary.
    P     # Product. This is 1 iff all bits in the binary representation are
          # 1, which means that φ(n) is a power of 2.
</code>```

A direct port of my Mathematica answer is two bytes longer:

```<code>ÆṪ        # Compute φ(n).
  µ       # Start a new monadic chain, to apply to φ(n).
   ÆṪ     # Compute φ(φ(n)).
      H   # Compute φ(n)/2.
     =    # Check for equality.
</code>```

Title: Constructible n-gons

Body:
A constructible \$n\$-gon is a regular polygon with n sides that you can construct with only a compass and an unmarked ruler.

As stated by Gauss, the only \$n\$ for which a \$n\$-gon is constructible is a product of any number of distinct Fermat primes and a power of \$2\$ (ie. \$n = 2^k \times p_1 \times p_2 \times ...\$ with \$k\$ being an integer and every \$p_i\$ some distinct Fermat prime).

A Fermat prime is a prime which can be expressed as \$2^{2^n}+1\$ with \$n\$ a positive integer. The only known Fermat primes are for \$n = 0, 1, 2, 3 \text{ and } 4\$

The challenge

Given an integer \$n>2\$, say if the \$n\$-gon is constructible or not.

Specification

Your program or function should take an integer or a string representing said integer (either in unary, binary, decimal or any other base) and return or print a truthy or falsy value.

This is code-golf, so shortest answer wins, standard loopholes apply.

Relevant OEIS

Examples

```<code>3 -> True
9 -> False
17 -> True
1024 -> True
65537 -> True
67109888 -> True
67109889 -> False
</code>```

Body:
Jelly, <s>7</s> 5 bytes

Thanks to Sp3000 for saving 2 bytes.

ÆṪBSỊ

Uses the following classification:

These are also the numbers for which phi(n) is a power of 2.

Where phi is Euler's totient function.

ÆṪ        # Compute φ(n).
  B       # Convert to binary.
   S      # Sum bits.
    Ị     # Check whether it's less than or equal to 1. This can only be the
          # case if the binary representation was of the form [1 0 0 ... 0], i.e.
          e# a power of 2.

Try it online!

Alternatively (credits to xnor):

ÆṪ’BP
ÆṪ        # Compute φ(n).
  ’       # Decrement.
   B      # Convert to binary.
    P     # Product. This is 1 iff all bits in the binary representation are
          # 1, which means that φ(n) is a power of 2.

A direct port of my Mathematica answer is two bytes longer:

ÆṪ        # Compute φ(n).
  µ       # Start a new monadic chain, to apply to φ(n).
   ÆṪ     # Compute φ(φ(n)).
      H   # Compute φ(n)/2.
     =    # Check for equality.


问:
Help: Aliens Programmers only speak ASCII

Setting the Scene:

It is an average afternoon, as you unwind after a long day by engaging in your favorite pastime: answering the plethora of captivating questions on PPCG. It hasn't been a good day for you; those damned Pyth programmers keep getting best answer and it's killing your vibe. Suddenly, you notice a new question has been posted! You make up your mind; not this time CJammers. Furiously, you begin to type, birthing a stream of characters; a fetus of the glorious BrainFuck loop that your end product will be. You type and type. Faster! Faster still! You're so focused you don't even notice the lights on your screen start to flicker on and off. Suddenly, the monitor glows green, an alien like symbol branded upon the desktop. Using your impeccable skills you cat ~/Desktop/aliensymbol and get presented with a bunch of numbers, a message! Being the shrewd PPCG programmer that you are, you notice that it looks like ASCII. No matter for you, you print(chr(i) for i in file) and decipher the message. Your first thought: "I need to share this with the community!".

...

Who would've thought it? That the first people to make contact with aliens would be the humble programmers of PPCG. Why us? Maybe it is because we are the epitome of human intelligence. Or maybe because BrainFuck is about as close as we have to an alien language. Nevertheless, the aliens - being the ultra-intelligent life forms that they are - want to test whether they should classify the human race as  intelligent or not. As a test of our mental prowess, the aliens have asked us to send them a few computer programs to demonstrate that we are technologically cultured. The issue is, the only human language they understand is numerical ASCII!

Help humankind show those creatures who the real intellectual alpha is. We need to send them a script that will convert our text based source codes into their numerical ASCII versions. Unfortunately, due to our underdeveloped technology (thanks Obama), we must send as small a translating program as possible. Good thing they chose to contact PPCG!

The Challenge:

The premise of this challenge is simple: you are to write a program that will take any program's source code (or any general text file for that matter), and output a space separated version of it with an ASCII translation below each line. That is, given an input of a text file, you need to output each line of that file followed by a line containing the ASCII representation of each character in the line above it (with each number lining up with the character it represents).

An example will greatly clarify this. Taking the source code of the infamous hello world as the input:

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

int main() {
    printf("hello, world\n");
    return 0;
}
</code>```

your program should output:

```<code>#   i   n   c   l   u   d   e       <   s   t   d   i   o   .   h   >
35  105 110 99  108 117 100 101 32  60  115 116 100 105 111 46  104 62  10

10
i   n   t       m   a   i   n   (   )       {
105 110 116 32  109 97  105 110 40  41  32  123 10
                p   r   i   n   t   f   (   "   h   e   l   l   o   ,       w   o   r   l   d   \   n   "   )   ;
32  32  32  32  112 114 105 110 116 102 40  34  104 101 108 108 111 44  32  119 111 114 108 100 92  110 34  41  59  10
                r   e   t   u   r   n       0   ;
32  32  32  32  114 101 116 117 114 110 32  48  59  10
}
125 10
</code>```

Implementation Details:

You may choose to take the input in whatever form you wish (opening file, command line pipe, function parameter etc.) and you should output to stdout or return the output from a function.

Things to note

Each character in the output is separated by a '\t' to allow for the space of 3 digits in the line below to line up (we are going to assume your tab is set to 4 spaces or more).

The newlines are displayed on the line that the return key was pressed (notice the 10's in the example)

The '\t' and '\n' printing requirements are lax. Your output must, in the general sense, look pleasing to the eye (need to show those aliens we have aesthetic sense as well), and if you can bend the previous two points while maintaining visual integrity, you will be forgiven.

You can choose to assume whether or not there is a newline at the end of the last line.

Scoring

This is code-golf so shortest program wins. Note, even if your program isn't the shortest, but uses really neat tricks relative to the language you are using, many +1's to you!

Good luck. The intergalactic intelligence ranking of humanity rests on your shoulders.

Note: Please forgive the plot holes. I'm not a writer :D

答:
Haskell - 71 bytes

```<code>f q=unlines[(x>>=(++"\t").show.ord)++'\n':intersperse '\t'x|x<-lines q]
</code>```

Body:
Haskell - 71 bytes

f q=unlines[(x>>=(++"\t").show.ord)++'\n':intersperse '\t'x|x<-lines q]


答:
Retina, <s>51</s> 50 bytes

```<code>0+$

+`^(.*)(?=(.{16}|.{8}|....|..?)$)0*\1$
$1
^1$
</code>```

Input is in binary. The first two lines divide by a power of two, the next two divide by all known Fermat primes (if in fact the number is a product of Fermat primes). Edit: Saved 1 byte thanks to @Martin Ender♦.

Title: Constructible n-gons

Body:
Retina, <s>51</s> 50 bytes

0+$

+`^(.*)(?=(.{16}|.{8}|....|..?)$)0*\1$
$1
^1$

Input is in binary. The first two lines divide by a power of two, the next two divide by all known Fermat primes (if in fact the number is a product of Fermat primes). Edit: Saved 1 byte thanks to @Martin Ender♦.


问:
Find every digit from the largest column
Here's a relatively simple challenge for you:

Given a list of positive integers:

Line them up in a grid, and sum each column. For example, if the input was [123, 7, 49, 681], the grid would look like this:

```<code> 1  2  3
 7
 4  9
 6  8  1
</code>```

And the sum of each column would be [18, 19, 4]:

```<code> 1  2  3
 7
 4  9
 6  8  1
 --------
 18 19 4
</code>```

Find the maximum of these sums, which in this case would be 19, and then

Output every digit that is at the same index as this maximum column. In this case, that would be

```<code>2
9
8
</code>```

You do not have to output these numbers in any particular order.
Note that there are only three outputs, even though we had 4 inputs. In the case of a tie, pick the earliest index. For example, if the input was [25, 223, 302], your grid is:

```<code>2  5
2  2  3
3  0  2
-------
7  7  5
</code>```

You should output

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

You can print these numbers in any format you like. List format, newline separated, space separated, etc. You may not take the input as a 2D array of digits, e.g.

```<code>[[1, 2, 3],
[7],
[4, 9],
[6, 8, 1]
</code>```

But other than that, you can take input as a list of strings, a list of digits, or any other reasonable format.

You may also assume that all inputs will be valid and contain at least two numbers.

As usual, the shortest answer in bytes wins!

Test IO:

```<code>#Input                      #Output
[1, 11, 111, 1111]      --> [1, 1, 1, 1]
[1, 12, 123]            --> [2, 2]
[987654321, 111]        --> [9, 1]
[111, 123456789]        --> [9]
[4, 8, 15, 16, 23, 42]  --> [4, 8, 1, 1, 2, 4]
[4, 8, 12, 26, 27, 38]  --> [2, 6, 7, 8]
[24, 53]                --> [2, 5]
[12, 304, 506]          --> [4, 6]
[30, 285, 121]          --> [0, 8, 2]
</code>```

Body:
JavaScript (ES6), 90

(l,x)=>[...l+0].map((t,i)=>l.map(n=>(n=n[i])&&(v-=n,t.push(n)),v=t=[])|v>=x||(x=v,r=t))&&r

f=(l,x)=>[...l+0].map((t,i)=>l.map(n=>(n=n[i])&&(v-=n,t.push(n)),v=t=[])|v>=x||(x=v,r=t))&&r

;[
 [[123, 7, 49, 681]       , [2,9,8]]
,[[25, 223, 302]          , [2, 2, 3]]
,[[1, 11, 111, 1111]      , [1, 1, 1, 1]]
,[[1, 12, 123]            , [2, 2]]
,[[987654321, 111]        , [9, 1]]
,[[111, 123456789]        , [9]]
,[[4, 8, 15, 16, 23, 42]  , [4, 8, 1, 1, 2, 4]]
,[[4, 8, 12, 26, 27, 38]  , [2, 6, 7, 8]]
,[[24, 53]                , [2, 5]]
,[[12, 304, 506]          , [4, 6]]
,[[30, 285, 121]          , [0, 8, 2]]]
.forEach(t=>{
  var i=t[0], o=t[1], r, ok
  i=i.map(x=>x+'') // convert i to a string list
  r=f(i)
  ok = (r+'')==(o+'') // compare r and o as comma separated strings
  console.log(ok?'OK':'KO', i+' -> '+ r)

})


答:
Batch, 97 bytes

```<code>@set/pn=
@for /l %%a in (4,-1,0)do @set/a"p=1<<(1<<%%a),n/=p*!(n%%-~p)+1"
@cmd/cset/a"!(n-1&n)"
</code>```

Input is on stdin in decimal. This is actually 1 byte shorter than calculating the powers of powers of 2 iteratively. I saved 1 byte by using @xnor's power of 2 check.

Title: Constructible n-gons

Body:
Batch, 97 bytes

@set/pn=
@for /l %%a in (4,-1,0)do @set/a"p=1<<(1<<%%a),n/=p*!(n%%-~p)+1"
@cmd/cset/a"!(n-1&n)"

Input is on stdin in decimal. This is actually 1 byte shorter than calculating the powers of powers of 2 iteratively. I saved 1 byte by using @xnor's power of 2 check.


问:
Count from 1 to 100... in Roman Numerals
Write a program that count from 1 to 100 in Roman Numerals and print these numbers by standard output. Each one of the numbers must be separated by spaces.

You cannot use any built in function to transform to roman numerals nor external application or library to do so.

The desired result is

```<code>I II III IV V VI VII VIII IX X XI XII XIII XIV XV XVI XVII XVIII XIX XX XXI XXII XXIII XXIV XXV XXVI XXVII XXVIII XXIX XXX XXXI XXXII XXXIII XXXIV XXXV XXXVI XXXVII XXXVIII XXXIX XL XLI XLII XLIII XLIV XLV XLVI XLVII XLVIII XLIX L LI LII LIII LIV LV LVI LVII LVIII LIX LX LXI LXII LXIII LXIV LXV LXVI LXVII LXVIII LXIX LXX LXXI LXXII LXXIII LXXIV LXXV LXXVI LXXVII LXXVIII LXXIX LXXX LXXXI LXXXII LXXXIII LXXXIV LXXXV LXXXVI LXXXVII LXXXVIII LXXXIX XC XCI XCII XCIII XCIV XCV XCVI XCVII XCVIII XCIX C
</code>```

As it is a code golf challenge, shortest code wins.

答:
APL 128

I tried an indexing solution in APL:

```<code>r←⍬
i←1
l:r←r,' ',('   CXI LV CX'[,⍉((1+(4 4 2 2⊤0 16 20 22 24 32 36 38 39 28)[;1+(3⍴10)⊤i])×3)-4 3⍴2 1 0])~' '
→(100≥i←i+1)/l
r
</code>```

It can be 4 bytes shorter in index origin 0 instead of 1 but the real space hog is the generation of the index matrix via:

```<code>4 4 2 2⊤0 16 20 22 24 32 36 38 39 28
</code>```

So far I have not been able to generate the indices on the fly!

Body:
APL 128

I tried an indexing solution in APL:

r←⍬
i←1
l:r←r,' ',('   CXI LV CX'[,⍉((1+(4 4 2 2⊤0 16 20 22 24 32 36 38 39 28)[;1+(3⍴10)⊤i])×3)-4 3⍴2 1 0])~' '
→(100≥i←i+1)/l
r

It can be 4 bytes shorter in index origin 0 instead of 1 but the real space hog is the generation of the index matrix via:

4 4 2 2⊤0 16 20 22 24 32 36 38 39 28

So far I have not been able to generate the indices on the fly!


Title: Constructible n-gons

Body:
JavaScript (ES7), 61 bytes

n=>[...Array(5)].map((_,i)=>n%(i=2**2**i+1)?0:n/=i)&&!(n&n-1)


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

答:
Java, <s>168</s> 136 bytes

```<code>(s,d)->{int i=s.length()+1;while(i-->1)System.out.println(s.substring(0,i));while(i++<d.length())System.out.println(d.substring(0,i));};
</code>```

Ungolfed test program

```<code>public static void main(String[] args) {

    BiConsumer<String, String> biconsumer = (s, d) -> {
        int i = s.length() + 1;
        while (i-- > 1) {
            System.out.println(s.substring(0, i));
        }
        while (i++ < d.length()) {
            System.out.println(d.substring(0, i));
        }
    };

    biconsumer.accept("Test", "Testing123");

}
</code>```

Title: Slowly turn a string into another

Body:
Java, <s>168</s> 136 bytes

(s,d)->{int i=s.length()+1;while(i-->1)System.out.println(s.substring(0,i));while(i++<d.length())System.out.println(d.substring(0,i));};

Ungolfed test program

public static void main(String[] args) {

    BiConsumer<String, String> biconsumer = (s, d) -> {
        int i = s.length() + 1;
        while (i-- > 1) {
            System.out.println(s.substring(0, i));
        }
        while (i++ < d.length()) {
            System.out.println(d.substring(0, i));
        }
    };

    biconsumer.accept("Test", "Testing123");

}


答:
Haskell - 70 bytes

```<code>f x=foldl1(flip(.))[[(*2),succ,id,pred,id,(`div`2)]!!(ord n-42)|n<-x]0
</code>```

64 if I may take the input in RPN:

```<code>f x=foldl1(.)[[(*2),succ,id,pred,id,(`div`2)]!!(ord n-42)|n<-x]0
</code>```

In addition to + - * / my implementation also support , and ., both of which does nothing. It crashes for any other input.

Title: Simple integer operation calculator

Body:
Implement a simple integer operation scriptable calculator.

Concept

The accumulator starts at 0 and has operations performed on it. At the end of the program output the value of the accumulator.

Operations:

+ adds 1 to the accumulator

- subtracts 1 from the accumulator

* multiplies the accumulator by 2

/ divides the accumulator by 2

Sample script

The input ++**--/ should give the output 3.

Example implementation

```<code>def calc(s)
    i = 0
    s.chars.each do |o|
        case o
            when '+'
                i += 1
            when '-'
                i -= 1
            when '*'
                i *= 2
            when '/'
                i /= 2
        end
    end
    return i
end
</code>```

Rules

This is code-golf, so lowest answer in bytes wins, but is not selected.

Creative implementations are encouraged.

Standard loopholes are prohibited.

You get the program via stdin or arguments, and you can output the answer via return value or stdout.

Have fun.

Division truncates down because it is integer division.

The program -/ returns -1.

Test cases

```<code>*///*-*+-+
-1
/*+/*+++/*///*/+-+//*+-+-/----*-*-+++*+**+/*--///+*-/+//*//-+++--++/-**--/+--/*-/+*//*+-*-*/*+*+/+*-
-17
+++-+--/-*/---++/-+*-//+/++-*--+*+/*/*/++--++-+//++--*/***-*+++--+-*//-*/+*/+-*++**+--*/*//-*--**-/-*+**-/*-**/*+*-*/--+/+/+//-+*/---///+**////-*//+-+-/+--/**///*+//+++/+*++**++//**+**+-*/+/*/*++-/+**+--+*++++/-*-/*+--/++*/-++/-**++++/-/+/--*/-/+---**//*///-//*+-*----+//--/-/+*/-+++-+*-*+*+-/-//*-//+/*-+//+/+/*-/-/+//+**/-****/-**-//+/+-+/*-+*++*/-/++*/-//*--+*--/-+-+/+/**/-***+/-/++-++*+*-+*+*-+-//+/-++*+/*//*-+/+*/-+/-/*/-/-+*+**/*//*+/+---+*+++*+/+-**/-+-/+*---/-*+/-++*//*/-+-*+--**/-////*/--/*--//-**/*++*+/*+/-+/--**/*-+*+/+-*+*+--*///+-++/+//+*/-+/**--//*/+++/*+*////+-*-//--*+/*/-+**/*//+*+-//+--+*-+/-**-*/+//*+---*+//*/+**/*--/--+/*-*+*++--*+//+*+-++--+-*-*-+--**+/+*-/+*+-/---+-*+-+-/++/+*///*/*-+-*//-+-++/++/*/-++/**--+-////-//+/*//+**/*+-+/+/+///*+*///*-/+/*/-//-*-**//-/-+--+/-*--+-++**++//*--/*++--*-/-///-+/+//--+*//-**-/*-*/+*/-*-*//--++*//-*/++//+/-++-+-*/*-+++**-/-*++++**+-+++-+-***-+//+-/**-+/*+****-*+++*/-*-/***/-/*+/*****++*+/-/-**-+-*-*-++**/*+-/*-+*++-/+/-++*-/*-****-*
18773342
</code>```

Body:
Haskell - 70 bytes

f x=foldl1(flip(.))[[(*2),succ,id,pred,id,(`div`2)]!!(ord n-42)|n<-x]0

64 if I may take the input in RPN:

f x=foldl1(.)[[(*2),succ,id,pred,id,(`div`2)]!!(ord n-42)|n<-x]0

In addition to + - * / my implementation also support , and ., both of which does nothing. It crashes for any other input.


问:
Invalid Invali Inval
This idea is loosely based upon @TùxCräftîñg's chat message.

Take a look at the below example sequence:

INVALID0, INVALID1, INVALID2 INVALID3, INVALID4... INVALID9

After INVALID9, it goes on like this:

INVALI0, INVALI1, INVALI2, INVALI3... INVALI9

And after INVALI9, it's like this:

INVAL0,INVAL1, INVAL2, INVAL3... INVAL9

After, INVAL9, it's like this:

INVA0, INVA1, INVA2, INVA3, ... INVA9

Notice how we we kept removing a letter from the word INVALID each time.

You'll keep repeating this until you reach a single letter, that is, the letter I:

I0, I1, I2, I3, I4 ... I9

Now, your task is, to take an input of a word, and produce a sequence from it like the above example. Your code must also work with single letters, and in that case the resulting sequence will be shorter.

You may choose any input and output format that you prefer (with or without a separator, as you wish), but you must specify which one you have chosen.

The sequence needs to be in the exact specified order.

The shortest code, in bytes, that successfully completes this challenge, wins the challenge.

Full sequence in the above example:

```<code>INVALID0, INVALID1, INVALID2, INVALID3, INVALID4, INVALID5, INVALID6, INVALID7, INVALID8, INVALID9, INVALI0, INVALI1, INVALI2, INVALI3, INVALI4, INVALI5, INVALI6, INVALI7, INVALI8, INVALI9, INVAL0, INVAL1, INVAL2, INVAL3, INVAL4, INVAL5, INVAL6, INVAL7, INVAL8, INVAL9, INVA0, INVA1, INVA2, INVA3, INVA4, INVA5, INVA6, INVA7, INVA8, INVA9, INV0, INV1, INV2, INV3, INV4, INV5, INV6, INV7, INV8, INV9, IN0, IN1, IN2, IN3, IN4, IN5, IN6, IN7, IN8, IN9, I0, I1, I2, I3, I4, I5, I6, I7, I8, I9
</code>```

Other examples:

Input: MAYBE (Uppercase and lowercase don't matter)

Output:

```<code>MAYBE0, MAYBE1, MAYBE2, MAYBE3, MAYBE4, MAYBE5, MAYBE6, MAYBE7, MAYBE8, MAYBE9, MAYB0, MAYB1, MAYB2, MAYB3, MAYB4, MAYB5, MAYB6, MAYB7, MAYB8, MAYB9, MAY0, MAY1, MAY2, MAY3, MAY4, MAY5, MAY6, MAY7, MAY8, MAY9, MA0, MA1, MA2, MA3, MA4, MA5, MA6, MA7, MA8, MA9, M0, M1, M2, M3, M4, M5, M6, M7, M8, M9
</code>```

Input: AFTER

Output:

```<code>AFTER0, AFTER1, AFTER2, AFTER3, AFTER4, AFTER5, AFTER6, AFTER7, AFTER8, AFTER9, AFTE0, AFTE1, AFTE2, AFTE3, AFTE4, AFTE5, AFTE6, AFTE7, AFTE8, AFTE9, AFT0, AFT1, AFT2, AFT3, AFT4, AFT5, AFT6, AFT7, AFT8, AFT9, AF0, AF1, AF2, AF3, AF4, AF5, AF6, AF7, AF8, AF9, A0, A1, A2, A3, A4, A5, A6, A7, A8, A9
</code>```

Input: WHAT ARE YOU DOING

```<code>WHAT ARE YOU DOING0, WHAT ARE YOU DOING1, WHAT ARE YOU DOING2, WHAT ARE YOU DOING3, WHAT ARE YOU DOING4, WHAT ARE YOU DOING5, WHAT ARE YOU DOING6, WHAT ARE YOU DOING7, WHAT ARE YOU DOING8, WHAT ARE YOU DOING9, WHAT ARE YOU DOIN0, WHAT ARE YOU DOIN1, WHAT ARE YOU DOIN2, WHAT ARE YOU DOIN3, WHAT ARE YOU DOIN4, WHAT ARE YOU DOIN5, WHAT ARE YOU DOIN6, WHAT ARE YOU DOIN7, WHAT ARE YOU DOIN8, WHAT ARE YOU DOIN9, WHAT ARE YOU DOI0, WHAT ARE YOU DOI1, WHAT ARE YOU DOI2, WHAT ARE YOU DOI3, WHAT ARE YOU DOI4, WHAT ARE YOU DOI5, WHAT ARE YOU DOI6, WHAT ARE YOU DOI7, WHAT ARE YOU DOI8, WHAT ARE YOU DOI9, WHAT ARE YOU DO0, WHAT ARE YOU DO1, WHAT ARE YOU DO2, WHAT ARE YOU DO3, WHAT ARE YOU DO4, WHAT ARE YOU DO5, WHAT ARE YOU DO6, WHAT ARE YOU DO7, WHAT ARE YOU DO8, WHAT ARE YOU DO9, WHAT ARE YOU D0, WHAT ARE YOU D1, WHAT ARE YOU D2, WHAT ARE YOU D3, WHAT ARE YOU D4, WHAT ARE YOU D5, WHAT ARE YOU D6, WHAT ARE YOU D7, WHAT ARE YOU D8, WHAT ARE YOU D9, WHAT ARE YOU 0, WHAT ARE YOU 1, WHAT ARE YOU 2, WHAT ARE YOU 3, WHAT ARE YOU 4, WHAT ARE YOU 5, WHAT ARE YOU 6, WHAT ARE YOU 7, WHAT ARE YOU 8, WHAT ARE YOU 9, WHAT ARE YOU0, WHAT ARE YOU1, WHAT ARE YOU2, WHAT ARE YOU3, WHAT ARE YOU4, WHAT ARE YOU5, WHAT ARE YOU6, WHAT ARE YOU7, WHAT ARE YOU8, WHAT ARE YOU9, WHAT ARE YO0, WHAT ARE YO1, WHAT ARE YO2, WHAT ARE YO3, WHAT ARE YO4, WHAT ARE YO5, WHAT ARE YO6, WHAT ARE YO7, WHAT ARE YO8, WHAT ARE YO9, WHAT ARE Y0, WHAT ARE Y1, WHAT ARE Y2, WHAT ARE Y3, WHAT ARE Y4, WHAT ARE Y5, WHAT ARE Y6, WHAT ARE Y7, WHAT ARE Y8, WHAT ARE Y9, WHAT ARE 0, WHAT ARE 1, WHAT ARE 2, WHAT ARE 3, WHAT ARE 4, WHAT ARE 5, WHAT ARE 6, WHAT ARE 7, WHAT ARE 8, WHAT ARE 9, WHAT ARE0, WHAT ARE1, WHAT ARE2, WHAT ARE3, WHAT ARE4, WHAT ARE5, WHAT ARE6, WHAT ARE7, WHAT ARE8, WHAT ARE9, WHAT AR0, WHAT AR1, WHAT AR2, WHAT AR3, WHAT AR4, WHAT AR5, WHAT AR6, WHAT AR7, WHAT AR8, WHAT AR9, WHAT A0, WHAT A1, WHAT A2, WHAT A3, WHAT A4, WHAT A5, WHAT A6, WHAT A7, WHAT A8, WHAT A9, WHAT 0, WHAT 1, WHAT 2, WHAT 3, WHAT 4, WHAT 5, WHAT 6, WHAT 7, WHAT 8, WHAT 9, WHAT0, WHAT1, WHAT2, WHAT3, WHAT4, WHAT5, WHAT6, WHAT7, WHAT8, WHAT9, WHA0, WHA1, WHA2, WHA3, WHA4, WHA5, WHA6, WHA7, WHA8, WHA9, WH0, WH1, WH2, WH3, WH4, WH5, WH6, WH7, WH8, WH9, W0, W1, W2, W3, W4, W5, W6, W7, W8, W9
</code>```

Leaderboard

var QUESTION_ID=92156,OVERRIDE_USER=58717;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

```

答:
Java 7, <s>105</s> 98 bytes

```<code>void c(String s){for(int x=0,l=s.length();x<l*10;)System.out.print(s.substring(0,l-x/10)+x++%10);}
</code>```

-7 bytes thanks to @Poke.

Ungolfed:

```<code>void c(String s){
  for(int x = 0, l = s.length(); x < l*10; ){
    System.out.print(s.substring(0, l - x/10) + x++ % 10);
  }
}
</code>```

Test code:

Try it here.

```<code>class M{
  static void c(String s){for(int x=0,l=s.length();x<l*10;)System.out.print(s.substring(0,l-x/10)+x++%10);}

  public static void main(String[] a){
    c("INVALID");
    System.out.println();
    c("MAYBE");
    System.out.println();
    c("AFTER");
    System.out.println();
    c("WHAT ARE YOU DOING");
  }
}
</code>```

Output:

```<code>INVALID0INVALID1INVALID2INVALID3INVALID4INVALID5INVALID6INVALID7INVALID8INVALID9INVALID0INVALID1INVALID2INVALID3INVALID4INVALID5INVALID6INVALID7INVALID8INVALID9INVALI0INVALI1INVALI2INVALI3INVALI4INVALI5INVALI6INVALI7INVALI8INVALI9INVAL0INVAL1INVAL2INVAL3INVAL4INVAL5INVAL6INVAL7INVAL8INVAL9INVA0INVA1INVA2INVA3INVA4INVA5INVA6INVA7INVA8INVA9INV0INV1INV2INV3INV4INV5INV6INV7INV8INV9IN0IN1IN2IN3IN4IN5IN6IN7IN8IN9I0I1I2I3I4I5I6I7I8I9
MAYBE0MAYBE1MAYBE2MAYBE3MAYBE4MAYBE5MAYBE6MAYBE7MAYBE8MAYBE9MAYBE0MAYBE1MAYBE2MAYBE3MAYBE4MAYBE5MAYBE6MAYBE7MAYBE8MAYBE9MAYB0MAYB1MAYB2MAYB3MAYB4MAYB5MAYB6MAYB7MAYB8MAYB9MAY0MAY1MAY2MAY3MAY4MAY5MAY6MAY7MAY8MAY9MA0MA1MA2MA3MA4MA5MA6MA7MA8MA9M0M1M2M3M4M5M6M7M8M9
AFTER0AFTER1AFTER2AFTER3AFTER4AFTER5AFTER6AFTER7AFTER8AFTER9AFTER0AFTER1AFTER2AFTER3AFTER4AFTER5AFTER6AFTER7AFTER8AFTER9AFTE0AFTE1AFTE2AFTE3AFTE4AFTE5AFTE6AFTE7AFTE8AFTE9AFT0AFT1AFT2AFT3AFT4AFT5AFT6AFT7AFT8AFT9AF0AF1AF2AF3AF4AF5AF6AF7AF8AF9A0A1A2A3A4A5A6A7A8A9
WHAT ARE YOU DOING0WHAT ARE YOU DOING1WHAT ARE YOU DOING2WHAT ARE YOU DOING3WHAT ARE YOU DOING4WHAT ARE YOU DOING5WHAT ARE YOU DOING6WHAT ARE YOU DOING7WHAT ARE YOU DOING8WHAT ARE YOU DOING9WHAT ARE YOU DOING0WHAT ARE YOU DOING1WHAT ARE YOU DOING2WHAT ARE YOU DOING3WHAT ARE YOU DOING4WHAT ARE YOU DOING5WHAT ARE YOU DOING6WHAT ARE YOU DOING7WHAT ARE YOU DOING8WHAT ARE YOU DOING9WHAT ARE YOU DOIN0WHAT ARE YOU DOIN1WHAT ARE YOU DOIN2WHAT ARE YOU DOIN3WHAT ARE YOU DOIN4WHAT ARE YOU DOIN5WHAT ARE YOU DOIN6WHAT ARE YOU DOIN7WHAT ARE YOU DOIN8WHAT ARE YOU DOIN9WHAT ARE YOU DOI0WHAT ARE YOU DOI1WHAT ARE YOU DOI2WHAT ARE YOU DOI3WHAT ARE YOU DOI4WHAT ARE YOU DOI5WHAT ARE YOU DOI6WHAT ARE YOU DOI7WHAT ARE YOU DOI8WHAT ARE YOU DOI9WHAT ARE YOU DO0WHAT ARE YOU DO1WHAT ARE YOU DO2WHAT ARE YOU DO3WHAT ARE YOU DO4WHAT ARE YOU DO5WHAT ARE YOU DO6WHAT ARE YOU DO7WHAT ARE YOU DO8WHAT ARE YOU DO9WHAT ARE YOU D0WHAT ARE YOU D1WHAT ARE YOU D2WHAT ARE YOU D3WHAT ARE YOU D4WHAT ARE YOU D5WHAT ARE YOU D6WHAT ARE YOU D7WHAT ARE YOU D8WHAT ARE YOU D9WHAT ARE YOU 0WHAT ARE YOU 1WHAT ARE YOU 2WHAT ARE YOU 3WHAT ARE YOU 4WHAT ARE YOU 5WHAT ARE YOU 6WHAT ARE YOU 7WHAT ARE YOU 8WHAT ARE YOU 9WHAT ARE YOU0WHAT ARE YOU1WHAT ARE YOU2WHAT ARE YOU3WHAT ARE YOU4WHAT ARE YOU5WHAT ARE YOU6WHAT ARE YOU7WHAT ARE YOU8WHAT ARE YOU9WHAT ARE YO0WHAT ARE YO1WHAT ARE YO2WHAT ARE YO3WHAT ARE YO4WHAT ARE YO5WHAT ARE YO6WHAT ARE YO7WHAT ARE YO8WHAT ARE YO9WHAT ARE Y0WHAT ARE Y1WHAT ARE Y2WHAT ARE Y3WHAT ARE Y4WHAT ARE Y5WHAT ARE Y6WHAT ARE Y7WHAT ARE Y8WHAT ARE Y9WHAT ARE 0WHAT ARE 1WHAT ARE 2WHAT ARE 3WHAT ARE 4WHAT ARE 5WHAT ARE 6WHAT ARE 7WHAT ARE 8WHAT ARE 9WHAT ARE0WHAT ARE1WHAT ARE2WHAT ARE3WHAT ARE4WHAT ARE5WHAT ARE6WHAT ARE7WHAT ARE8WHAT ARE9WHAT AR0WHAT AR1WHAT AR2WHAT AR3WHAT AR4WHAT AR5WHAT AR6WHAT AR7WHAT AR8WHAT AR9WHAT A0WHAT A1WHAT A2WHAT A3WHAT A4WHAT A5WHAT A6WHAT A7WHAT A8WHAT A9WHAT 0WHAT 1WHAT 2WHAT 3WHAT 4WHAT 5WHAT 6WHAT 7WHAT 8WHAT 9WHAT0WHAT1WHAT2WHAT3WHAT4WHAT5WHAT6WHAT7WHAT8WHAT9WHA0WHA1WHA2WHA3WHA4WHA5WHA6WHA7WHA8WHA9WH0WH1WH2WH3WH4WH5WH6WH7WH8WH9W0W1W2W3W4W5W6W7W8W9
</code>```

Title: Invalid Invali Inval

Body:
Java 7, <s>105</s> 98 bytes

void c(String s){for(int x=0,l=s.length();x<l*10;)System.out.print(s.substring(0,l-x/10)+x++%10);}

-7 bytes thanks to @Poke.

Ungolfed:

void c(String s){
  for(int x = 0, l = s.length(); x < l*10; ){
    System.out.print(s.substring(0, l - x/10) + x++ % 10);
  }
}

Test code:

Try it here.

class M{
  static void c(String s){for(int x=0,l=s.length();x<l*10;)System.out.print(s.substring(0,l-x/10)+x++%10);}

  public static void main(String[] a){
    c("INVALID");
    System.out.println();
    c("MAYBE");
    System.out.println();
    c("AFTER");
    System.out.println();
    c("WHAT ARE YOU DOING");
  }
}

Output:

INVALID0INVALID1INVALID2INVALID3INVALID4INVALID5INVALID6INVALID7INVALID8INVALID9INVALID0INVALID1INVALID2INVALID3INVALID4INVALID5INVALID6INVALID7INVALID8INVALID9INVALI0INVALI1INVALI2INVALI3INVALI4INVALI5INVALI6INVALI7INVALI8INVALI9INVAL0INVAL1INVAL2INVAL3INVAL4INVAL5INVAL6INVAL7INVAL8INVAL9INVA0INVA1INVA2INVA3INVA4INVA5INVA6INVA7INVA8INVA9INV0INV1INV2INV3INV4INV5INV6INV7INV8INV9IN0IN1IN2IN3IN4IN5IN6IN7IN8IN9I0I1I2I3I4I5I6I7I8I9
MAYBE0MAYBE1MAYBE2MAYBE3MAYBE4MAYBE5MAYBE6MAYBE7MAYBE8MAYBE9MAYBE0MAYBE1MAYBE2MAYBE3MAYBE4MAYBE5MAYBE6MAYBE7MAYBE8MAYBE9MAYB0MAYB1MAYB2MAYB3MAYB4MAYB5MAYB6MAYB7MAYB8MAYB9MAY0MAY1MAY2MAY3MAY4MAY5MAY6MAY7MAY8MAY9MA0MA1MA2MA3MA4MA5MA6MA7MA8MA9M0M1M2M3M4M5M6M7M8M9
AFTER0AFTER1AFTER2AFTER3AFTER4AFTER5AFTER6AFTER7AFTER8AFTER9AFTER0AFTER1AFTER2AFTER3AFTER4AFTER5AFTER6AFTER7AFTER8AFTER9AFTE0AFTE1AFTE2AFTE3AFTE4AFTE5AFTE6AFTE7AFTE8AFTE9AFT0AFT1AFT2AFT3AFT4AFT5AFT6AFT7AFT8AFT9AF0AF1AF2AF3AF4AF5AF6AF7AF8AF9A0A1A2A3A4A5A6A7A8A9
WHAT ARE YOU DOING0WHAT ARE YOU DOING1WHAT ARE YOU DOING2WHAT ARE YOU DOING3WHAT ARE YOU DOING4WHAT ARE YOU DOING5WHAT ARE YOU DOING6WHAT ARE YOU DOING7WHAT ARE YOU DOING8WHAT ARE YOU DOING9WHAT ARE YOU DOING0WHAT ARE YOU DOING1WHAT ARE YOU DOING2WHAT ARE YOU DOING3WHAT ARE YOU DOING4WHAT ARE YOU DOING5WHAT ARE YOU DOING6WHAT ARE YOU DOING7WHAT ARE YOU DOING8WHAT ARE YOU DOING9WHAT ARE YOU DOIN0WHAT ARE YOU DOIN1WHAT ARE YOU DOIN2WHAT ARE YOU DOIN3WHAT ARE YOU DOIN4WHAT ARE YOU DOIN5WHAT ARE YOU DOIN6WHAT ARE YOU DOIN7WHAT ARE YOU DOIN8WHAT ARE YOU DOIN9WHAT ARE YOU DOI0WHAT ARE YOU DOI1WHAT ARE YOU DOI2WHAT ARE YOU DOI3WHAT ARE YOU DOI4WHAT ARE YOU DOI5WHAT ARE YOU DOI6WHAT ARE YOU DOI7WHAT ARE YOU DOI8WHAT ARE YOU DOI9WHAT ARE YOU DO0WHAT ARE YOU DO1WHAT ARE YOU DO2WHAT ARE YOU DO3WHAT ARE YOU DO4WHAT ARE YOU DO5WHAT ARE YOU DO6WHAT ARE YOU DO7WHAT ARE YOU DO8WHAT ARE YOU DO9WHAT ARE YOU D0WHAT ARE YOU D1WHAT ARE YOU D2WHAT ARE YOU D3WHAT ARE YOU D4WHAT ARE YOU D5WHAT ARE YOU D6WHAT ARE YOU D7WHAT ARE YOU D8WHAT ARE YOU D9WHAT ARE YOU 0WHAT ARE YOU 1WHAT ARE YOU 2WHAT ARE YOU 3WHAT ARE YOU 4WHAT ARE YOU 5WHAT ARE YOU 6WHAT ARE YOU 7WHAT ARE YOU 8WHAT ARE YOU 9WHAT ARE YOU0WHAT ARE YOU1WHAT ARE YOU2WHAT ARE YOU3WHAT ARE YOU4WHAT ARE YOU5WHAT ARE YOU6WHAT ARE YOU7WHAT ARE YOU8WHAT ARE YOU9WHAT ARE YO0WHAT ARE YO1WHAT ARE YO2WHAT ARE YO3WHAT ARE YO4WHAT ARE YO5WHAT ARE YO6WHAT ARE YO7WHAT ARE YO8WHAT ARE YO9WHAT ARE Y0WHAT ARE Y1WHAT ARE Y2WHAT ARE Y3WHAT ARE Y4WHAT ARE Y5WHAT ARE Y6WHAT ARE Y7WHAT ARE Y8WHAT ARE Y9WHAT ARE 0WHAT ARE 1WHAT ARE 2WHAT ARE 3WHAT ARE 4WHAT ARE 5WHAT ARE 6WHAT ARE 7WHAT ARE 8WHAT ARE 9WHAT ARE0WHAT ARE1WHAT ARE2WHAT ARE3WHAT ARE4WHAT ARE5WHAT ARE6WHAT ARE7WHAT ARE8WHAT ARE9WHAT AR0WHAT AR1WHAT AR2WHAT AR3WHAT AR4WHAT AR5WHAT AR6WHAT AR7WHAT AR8WHAT AR9WHAT A0WHAT A1WHAT A2WHAT A3WHAT A4WHAT A5WHAT A6WHAT A7WHAT A8WHAT A9WHAT 0WHAT 1WHAT 2WHAT 3WHAT 4WHAT 5WHAT 6WHAT 7WHAT 8WHAT 9WHAT0WHAT1WHAT2WHAT3WHAT4WHAT5WHAT6WHAT7WHAT8WHAT9WHA0WHA1WHA2WHA3WHA4WHA5WHA6WHA7WHA8WHA9WH0WH1WH2WH3WH4WH5WH6WH7WH8WH9W0W1W2W3W4W5W6W7W8W9


答:
C#, <s>107</s> 102 Bytes

```<code>string f(string i){var o="";while(i!=""){for(int k=0;k<=9;)o+=i+k++;i=i.Remove(i.Length-1);}return o;}
</code>```

Ungolfed

```<code>string f(string i)
{
   string o = "";
   while(i != "")
   {
      for (int k = 0; k <= 9;)
         o += i + k++;
      i = i.Remove(i.Length - 1);
   }
   return o;
}
</code>```

Title: Invalid Invali Inval

Body:
This idea is loosely based upon @TùxCräftîñg's chat message.

Take a look at the below example sequence:

INVALID0, INVALID1, INVALID2 INVALID3, INVALID4... INVALID9

After INVALID9, it goes on like this:

INVALI0, INVALI1, INVALI2, INVALI3... INVALI9

And after INVALI9, it's like this:

INVAL0,INVAL1, INVAL2, INVAL3... INVAL9

After, INVAL9, it's like this:

INVA0, INVA1, INVA2, INVA3, ... INVA9

Notice how we we kept removing a letter from the word INVALID each time.

You'll keep repeating this until you reach a single letter, that is, the letter I:

I0, I1, I2, I3, I4 ... I9

Now, your task is, to take an input of a word, and produce a sequence from it like the above example. Your code must also work with single letters, and in that case the resulting sequence will be shorter.

You may choose any input and output format that you prefer (with or without a separator, as you wish), but you must specify which one you have chosen.

The sequence needs to be in the exact specified order.

The shortest code, in bytes, that successfully completes this challenge, wins the challenge.

Full sequence in the above example:

```<code>INVALID0, INVALID1, INVALID2, INVALID3, INVALID4, INVALID5, INVALID6, INVALID7, INVALID8, INVALID9, INVALI0, INVALI1, INVALI2, INVALI3, INVALI4, INVALI5, INVALI6, INVALI7, INVALI8, INVALI9, INVAL0, INVAL1, INVAL2, INVAL3, INVAL4, INVAL5, INVAL6, INVAL7, INVAL8, INVAL9, INVA0, INVA1, INVA2, INVA3, INVA4, INVA5, INVA6, INVA7, INVA8, INVA9, INV0, INV1, INV2, INV3, INV4, INV5, INV6, INV7, INV8, INV9, IN0, IN1, IN2, IN3, IN4, IN5, IN6, IN7, IN8, IN9, I0, I1, I2, I3, I4, I5, I6, I7, I8, I9
</code>```

Other examples:

Input: MAYBE (Uppercase and lowercase don't matter)

Output:

```<code>MAYBE0, MAYBE1, MAYBE2, MAYBE3, MAYBE4, MAYBE5, MAYBE6, MAYBE7, MAYBE8, MAYBE9, MAYB0, MAYB1, MAYB2, MAYB3, MAYB4, MAYB5, MAYB6, MAYB7, MAYB8, MAYB9, MAY0, MAY1, MAY2, MAY3, MAY4, MAY5, MAY6, MAY7, MAY8, MAY9, MA0, MA1, MA2, MA3, MA4, MA5, MA6, MA7, MA8, MA9, M0, M1, M2, M3, M4, M5, M6, M7, M8, M9
</code>```

Input: AFTER

Output:

```<code>AFTER0, AFTER1, AFTER2, AFTER3, AFTER4, AFTER5, AFTER6, AFTER7, AFTER8, AFTER9, AFTE0, AFTE1, AFTE2, AFTE3, AFTE4, AFTE5, AFTE6, AFTE7, AFTE8, AFTE9, AFT0, AFT1, AFT2, AFT3, AFT4, AFT5, AFT6, AFT7, AFT8, AFT9, AF0, AF1, AF2, AF3, AF4, AF5, AF6, AF7, AF8, AF9, A0, A1, A2, A3, A4, A5, A6, A7, A8, A9
</code>```

Input: WHAT ARE YOU DOING

```<code>WHAT ARE YOU DOING0, WHAT ARE YOU DOING1, WHAT ARE YOU DOING2, WHAT ARE YOU DOING3, WHAT ARE YOU DOING4, WHAT ARE YOU DOING5, WHAT ARE YOU DOING6, WHAT ARE YOU DOING7, WHAT ARE YOU DOING8, WHAT ARE YOU DOING9, WHAT ARE YOU DOIN0, WHAT ARE YOU DOIN1, WHAT ARE YOU DOIN2, WHAT ARE YOU DOIN3, WHAT ARE YOU DOIN4, WHAT ARE YOU DOIN5, WHAT ARE YOU DOIN6, WHAT ARE YOU DOIN7, WHAT ARE YOU DOIN8, WHAT ARE YOU DOIN9, WHAT ARE YOU DOI0, WHAT ARE YOU DOI1, WHAT ARE YOU DOI2, WHAT ARE YOU DOI3, WHAT ARE YOU DOI4, WHAT ARE YOU DOI5, WHAT ARE YOU DOI6, WHAT ARE YOU DOI7, WHAT ARE YOU DOI8, WHAT ARE YOU DOI9, WHAT ARE YOU DO0, WHAT ARE YOU DO1, WHAT ARE YOU DO2, WHAT ARE YOU DO3, WHAT ARE YOU DO4, WHAT ARE YOU DO5, WHAT ARE YOU DO6, WHAT ARE YOU DO7, WHAT ARE YOU DO8, WHAT ARE YOU DO9, WHAT ARE YOU D0, WHAT ARE YOU D1, WHAT ARE YOU D2, WHAT ARE YOU D3, WHAT ARE YOU D4, WHAT ARE YOU D5, WHAT ARE YOU D6, WHAT ARE YOU D7, WHAT ARE YOU D8, WHAT ARE YOU D9, WHAT ARE YOU 0, WHAT ARE YOU 1, WHAT ARE YOU 2, WHAT ARE YOU 3, WHAT ARE YOU 4, WHAT ARE YOU 5, WHAT ARE YOU 6, WHAT ARE YOU 7, WHAT ARE YOU 8, WHAT ARE YOU 9, WHAT ARE YOU0, WHAT ARE YOU1, WHAT ARE YOU2, WHAT ARE YOU3, WHAT ARE YOU4, WHAT ARE YOU5, WHAT ARE YOU6, WHAT ARE YOU7, WHAT ARE YOU8, WHAT ARE YOU9, WHAT ARE YO0, WHAT ARE YO1, WHAT ARE YO2, WHAT ARE YO3, WHAT ARE YO4, WHAT ARE YO5, WHAT ARE YO6, WHAT ARE YO7, WHAT ARE YO8, WHAT ARE YO9, WHAT ARE Y0, WHAT ARE Y1, WHAT ARE Y2, WHAT ARE Y3, WHAT ARE Y4, WHAT ARE Y5, WHAT ARE Y6, WHAT ARE Y7, WHAT ARE Y8, WHAT ARE Y9, WHAT ARE 0, WHAT ARE 1, WHAT ARE 2, WHAT ARE 3, WHAT ARE 4, WHAT ARE 5, WHAT ARE 6, WHAT ARE 7, WHAT ARE 8, WHAT ARE 9, WHAT ARE0, WHAT ARE1, WHAT ARE2, WHAT ARE3, WHAT ARE4, WHAT ARE5, WHAT ARE6, WHAT ARE7, WHAT ARE8, WHAT ARE9, WHAT AR0, WHAT AR1, WHAT AR2, WHAT AR3, WHAT AR4, WHAT AR5, WHAT AR6, WHAT AR7, WHAT AR8, WHAT AR9, WHAT A0, WHAT A1, WHAT A2, WHAT A3, WHAT A4, WHAT A5, WHAT A6, WHAT A7, WHAT A8, WHAT A9, WHAT 0, WHAT 1, WHAT 2, WHAT 3, WHAT 4, WHAT 5, WHAT 6, WHAT 7, WHAT 8, WHAT 9, WHAT0, WHAT1, WHAT2, WHAT3, WHAT4, WHAT5, WHAT6, WHAT7, WHAT8, WHAT9, WHA0, WHA1, WHA2, WHA3, WHA4, WHA5, WHA6, WHA7, WHA8, WHA9, WH0, WH1, WH2, WH3, WH4, WH5, WH6, WH7, WH8, WH9, W0, W1, W2, W3, W4, W5, W6, W7, W8, W9
</code>```

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
C#, <s>107</s> 102 Bytes

string f(string i){var o="";while(i!=""){for(int k=0;k<=9;)o+=i+k++;i=i.Remove(i.Length-1);}return o;}

Ungolfed

string f(string i)
{
   string o = "";
   while(i != "")
   {
      for (int k = 0; k <= 9;)
         o += i + k++;
      i = i.Remove(i.Length - 1);
   }
   return o;
}


答:
GNU sed, <s>57</s> 45 + 2(rn flags) = 47 bytes

```<code>:;1{/../p};2G;2h;s/.(\n.*)?$//;/./t;g;s/.$//p
</code>```

Run:

echo -e "Test\nTesting" | sed -rnf morphing_string.sed
```

The input should be the two strings separated by a newline. The code is run by sed for each line.

The loop : deletes one character from the end of the string iteratively. The output related to the first string is printed directly, except the first character: 1{/../p}. The output for the second string is stored in hold space in reverse order (2G;2h) during deletion and printed at the end.

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:
GNU sed, <s>57</s> 45 + 2(rn flags) = 47 bytes

:;1{/../p};2G;2h;s/.(\n.*)?$//;/./t;g;s/.$//p

Run:

echo -e "Test\nTesting" | sed -rnf morphing_string.sed

The input should be the two strings separated by a newline. The code is run by sed for each line.

The loop : deletes one character from the end of the string iteratively. The output related to the first string is printed directly, except the first character: 1{/../p}. The output for the second string is stored in hold space in reverse order (2G;2h) during deletion and printed at the end.


答:
C, 100 bytes

```<code>n;f(char*c,char*s){n=strlen(c);while(n)printf("%.*s\n",n--,c);for(n=1;s[n++];)printf("%.*s\n",n,s);}
</code>```

Ungolfed test

```<code>#include <stdio.h>
#include <string.h>
n;
f(char*c,char*s)
{
    n=strlen(c);
    while(n)
        printf("%.*s\n",n--,c);
    for(n=1;s[n++];)
        printf("%.*s\n",n,s);
}

int main(void)
{
    char * s1 = "Test";
    char * s2 = "Testing";
    f(s1, s2);
    return 0;
}
</code>```

Title: Slowly turn a string into another

Body:
C, 100 bytes

n;f(char*c,char*s){n=strlen(c);while(n)printf("%.*s\n",n--,c);for(n=1;s[n++];)printf("%.*s\n",n,s);}

Ungolfed test

#include <stdio.h>
#include <string.h>
n;
f(char*c,char*s)
{
    n=strlen(c);
    while(n)
        printf("%.*s\n",n--,c);
    for(n=1;s[n++];)
        printf("%.*s\n",n,s);
}

int main(void)
{
    char * s1 = "Test";
    char * s2 = "Testing";
    f(s1, s2);
    return 0;
}


问:
Incrementing Numbers, Over Multiple Sessions
Good Evening Golf Agents,

Your mission is on behalf of notorious entertainment giant Eviltronic Arts. As part of their nefarious plan for world enslavement and entertainment, they must sell as many copies of SimStation V as possible. This means that the software must mysteriously stop working, after starting it a few times.

Your goal is to write a program that counts the amount of times it has been run. The program must do nothing other then write the integer to stdout. The first time it is run, it should return "1". The next "2" and so on. The program must be able to at least reach the number "14", but there is no required upper limit.

However, your program must not write any new files. Accessing itself, or the registry, or even the internet is absolutely OK. But some of our users are suspicious of new files, and will merely overwrite them! The nerve! Defeating the limitations on software they legitimately purchased!

The program can not assume a stable interpreter or shell - the program must still work if the entire interpreter nay shell nay computer is restarted between running.

As it must be as undetectable as possible, the shortest source code will win.

Good luck agents. The entertainment industry is counting on you.

答:
Haskell - 36 bytes

```<code>main=do appendFile"a.hs""+1";print$1
</code>```

Simply adds +1 to the end of the source file, which is assumed to be named a.hs. The .hs extension is mandatory in both ghc and ghci.

Body:
Haskell - 36 bytes

main=do appendFile"a.hs""+1";print$1

Simply adds +1 to the end of the source file, which is assumed to be named a.hs. The .hs extension is mandatory in both ghc and ghci.


问:
Rolling three dice and show the probabilities
Roll 3 dice, count the two highest two values and add them to the result. Every 1 must be rolled once again.

Now show the average throw after 1000000 tries and the probabilities for each result occurring:

Desired Result:

avg(9.095855)

  2: 0.0023

  3: 0.0448

  4: 1.1075

  5: 2.8983

  6: 6.116

  7: 10.1234

  8: 15.4687

  9: 18.9496

  10: 19.3575

  11: 16.0886

  12: 9.8433

答:
Seems to be a basic problem with the calculation and results I am seeing here.

If you must reroll the dice (all 3 or just one) when you get a 1 showing up, then the lowest possible sum of die faces you could ever have would be 4.  That is, any face that shows a 1 will be rerolled.  Which specifically requires that the lowest possible face is a 2.  You could avoid the rerolling by generating random values from 2 .. 6, but that might be missing the point.

What this means:  If you are reporting values for 2 or 3 as the sum of the faces, these are 1+1 and 2+1 respectively, the specification excludes this possibility.

That is, unless the "you must reroll the dice" only applies to the first instance of a 1.  In which case, you may have a 1+1, and 2+1 case (so you'd get sums of 2 and 3 as possible answers).


答:
Python 2, <s>195 +1 +24 = 220</s> 217

```<code>from pylab import*
ifrom scipy.signal import convolve2d as c
k=(arange(9)%2).reshape(3,3)
def f(n):g=zeros((n,n),int);g[n/2,n/2]=n;exec"g=c(g/4,k,'same')+g%4;"*n;return g[any(g,0)].T[any(g,0)]
</code>```

output for n=16

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

there is a LOT of unnecessary padding and iterations, by using n as a "good-enough" upper bound, but n=200 still completed in a second and n=500 in about 12 seconds

ungolfed

```<code>from pylab import*
from scipy.signal import convolve2d as c
k=array([0,1,0],
        [1,0,1],
        [0,1,0])
def f(n):
  g=zeros((n,n))                 # big grid of zeros, way bigger than necessary
  g[n/2,n/2]=n                   # put n grains in the middle
  exec"g=c(g/4,k,'same')+g%4;"*n # leave places with <4 grains as is, convolve the rest with the kernel k, repeat until convergence (and then some more)
  return g[any(g,0)].T[any(g,0)] # removes surrounding 0-rows and columns
</code>```

replacing return x by imshow(x) adds one character and outputs an ugly interpolated image, adding imshow(x,'gray',None,1,'nearest') removes the blurry interpolation bringing the output up to specs

Title: Build a sandpile

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

Body:
Python 2, <s>195 +1 +24 = 220</s> 217

from pylab import*
ifrom scipy.signal import convolve2d as c
k=(arange(9)%2).reshape(3,3)
def f(n):g=zeros((n,n),int);g[n/2,n/2]=n;exec"g=c(g/4,k,'same')+g%4;"*n;return g[any(g,0)].T[any(g,0)]

output for n=16

array([[0, 0, 1, 0, 0],
       [0, 2, 1, 2, 0],
       [1, 1, 0, 1, 1],
       [0, 2, 1, 2, 0],
       [0, 0, 1, 0, 0]])

there is a LOT of unnecessary padding and iterations, by using n as a "good-enough" upper bound, but n=200 still completed in a second and n=500 in about 12 seconds

ungolfed

from pylab import*
from scipy.signal import convolve2d as c
k=array([0,1,0],
        [1,0,1],
        [0,1,0])
def f(n):
  g=zeros((n,n))                 # big grid of zeros, way bigger than necessary
  g[n/2,n/2]=n                   # put n grains in the middle
  exec"g=c(g/4,k,'same')+g%4;"*n # leave places with <4 grains as is, convolve the rest with the kernel k, repeat until convergence (and then some more)
  return g[any(g,0)].T[any(g,0)] # removes surrounding 0-rows and columns

replacing return x by imshow(x) adds one character and outputs an ugly interpolated image, adding imshow(x,'gray',None,1,'nearest') removes the blurry interpolation bringing the output up to specs


Title: Build a sandpile

Body:
Perl, <s>157</s> 147 bytes

Includes +1 for -p

Run with the count on STDIN, prints the map using 0123 to STDOUT:

sandpile.pl <<< 16

sandpile.pl:

#!/usr/bin/perl -p
map{++substr$_,y///c/2-1,1;/4
/?$.+=s%^|\z%0 x$..$/%eg+!s/\b/0/g:s^.^$&%4+grep{3<substr$\,0|$_+"@+",1}-$.-2,-2,0,$.^eg while/[4-7]/}($\="0
")x$_}{


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

答:
Java 8, <s>29</s> 28 bytes

```<code>i->(""+(i<0?-i:i)).length();
</code>```

Ungolfed test program

```<code>public static void main(String[] args) {
    IntFunction<Integer> func = i -> ("" + (i < 0 ? -i : i)).length();

    System.out.println(func.apply(12345)); //5
}
</code>```

Title: Finding number of digits in an integer

Body:
Java 8, <s>29</s> 28 bytes

i->(""+(i<0?-i:i)).length();

Ungolfed test program

public static void main(String[] args) {
    IntFunction<Integer> func = i -> ("" + (i < 0 ? -i : i)).length();

    System.out.println(func.apply(12345)); //5
}


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

答:
JavaScript (V8), <s> 170 164 </s> 140 bytes

Expects (array_of_strings)(flag_string). Prints the output.

a=>c=>[...new Set(a)].sort().map(k=>(a.map(v=>n+=v==k,n=0),o={c:n+' '+k,d:n>1&&k,D:n>1&&Array(n).fill(k).join`
`,u:n<2&&k}[c[1]])&&print(o))
```

Try it online!

Title: UNIX Uniq Uknow?

Body:
JavaScript (V8), <s> 170 164 </s> 140 bytes

Expects (array_of_strings)(flag_string). Prints the output.

a=>c=>[...new Set(a)].sort().map(k=>(a.map(v=>n+=v==k,n=0),o={c:n+' '+k,d:n>1&&k,D:n>1&&Array(n).fill(k).join`
`,u:n<2&&k}[c[1]])&&print(o))

Try it online!


问:
Chuck Norris vs Travelling Salesman

Introduction

Almost everyone is familiar with the Travelling Salesman Problem (TSP). The task is to, given a list of N cities, find the minimum Hamiltonian cycle which is to say the shortest path that visits each city and comes full-circle back to the start. That is not what this challenge is about. This challenge is to implement Chuck Norris' solution to the TSP:

Chuck Norris solved the Travelling Salesman problem in O(1) time: break salesman into N pieces; kick each piece to a different city.

Challenge

In order to solve the TSP in this way, we need a sufficiently durable Salesman that won't shy away from frivolities like dismemberment; a number of cities to visit; a set of products to sell; a concrete method for dismemberment; and a calculation for scoring.

Specification

Cities

N is the number of cites our Salesman will visit

Salesman

The main program or function

Written in language X

With length mod N equal to 0

Products

The full names of the elements on the Periodic Table

This includes the newly accepted names of elements

Dismemberment

Slicing the Salesman into N continuous pieces of equal length

Each piece is should be a valid function or program in language X

Output

When executed the Salesman should output Chuck Norris and the sliced pieces should each output a distinct product

Only extra trailing white space is acceptable

Scoring

The length, L, of the Salesman in bytes divided by the number of cities, N, squared.

Score = L/(N*N)

Smallest score wins

Please include 3 significant figures when posting your decimal score

Examples

This Salesman visits 3 cities so N=3 and and it has a length of 9 so L=9. Thus the score for this answer would be S = 9 / (3 * 3) = 9/9 = 1.

Note that the Salesman and each sliced piece (of which there are 3), should all be valid programs or functions in the same language.

```<code>Program      -> Output
-------         ------
aaaBBBccc    -> Chuck Norris

aaa          -> Helium
BBB          -> Iridium
ccc          -> Tennessine
</code>```

N=4 and L=20 so S=20/16=1.25

```<code>Program                 -> Output
-------                    ------
aaaaaBBBBBcccccDDDDD    -> Chuck Norris

aaaaa                   -> Hydrogen
BBBBB                   -> Cadmium
ccccc                   -> Mercury
DDDDD                   -> Iron
</code>```

答:
Python, L = 2596, N = 118, Score = 0.186

The length of each slice is 22 so that makes this pretty lengthy.

lambda:"Gold"; print"""";print "Carbon     "print   "Thorium     "print   "Curium      "print "Calcium       "print "Nickel        "print      "Zinc     "print    "Neon       "print "Boron         "print   "Iron        "print  "Cerium       "print "Barium        "print "Caesium       """[9::22];lambda:"Tin"[0];lambda:"Lead    "#print"Argon          "print"Radon          "print"Xenon          "print"Erbium         "print"Cobalt         "print"Copper         "print"Helium         "print"Indium         "print"Iodine         "print"Osmium         "print"Oxygen         "print"Radium         "print"Silver         "print"Sodium         "print"Sulfur         "print"Arsenic        "print"Bismuth        "print"Bohrium        "print"Bromine        "print"Cadmium        "print"Dubnium        "print"Fermium        "print"Gallium        "print"Hafnium        "print"Hassium        "print"Holmium        "print"Iridium        "print"Krypton        "print"Lithium        "print"Mercury        "print"Niobium        "print"Rhenium        "print"Rhodium        "print"Silicon        "print"Terbium        "print"Thulium        "print"Uranium        "print"Yttrium        "print"Actinium       "print"Antimony       "print"Astatine       "print"Chlorine       "print"Chromium       "print"Europium       "print"Fluorine       "print"Francium       "print"Hydrogen       "print"Lutetium       "print"Nitrogen       "print"Nobelium       "print"Platinum       "print"Polonium       "print"Rubidium       "print"Samarium       "print"Scandium       "print"Selenium       "print"Tantalum       "print"Thallium       "print"Titanium       "print"Tungsten       "print"Vanadium       "print"Nihonium       "print"Aluminium      "print"Americium      "print"Berkelium      "print"Beryllium      "print"Flerovium      "print"Germanium      "print"Lanthanum      "print"Magnesium      "print"Manganese      "print"Neodymium      "print"Neptunium      "print"Palladium      "print"Plutonium      "print"Potassium      "print"Ruthenium      "print"Strontium      "print"Tellurium      "print"Ytterbium      "print"Zirconium      "print"Moscovium      "print"Oganesson      "print"Dysprosium     "print"Gadolinium     "print"Lawrencium     "print"Meitnerium     "print"Molybdenum     "print"Phosphorus     "print"Promethium     "print"Seaborgium     "print"Technetium     "print"Tennessine     "print"Californium    "print"Copernicium    "print"Einsteinium    "print"Livermorium    "print"Mendelevium    "print"Roentgenium    "print"Darmstadtium   "print"Praseodymium   "print"Protactinium   "print"Rutherfordium  "
```

<p>Here is the Salesman after the slicing and dicing:</p>

<pre class="lang-py prettyprint-override"><code>lambda:"Gold"; print""  # <-- This is a function
"";print "Carbon     "
print   "Thorium     "
print   "Curium      "
print "Calcium       "
print "Nickel        "
print      "Zinc     "
print    "Neon       "
print "Boron         "
print   "Iron        "
print  "Cerium       "
print "Barium        "
print "Caesium       "
""[9::22];lambda:"Tin"  # <-- This is a function and the choke point
[0];lambda:"Lead    "#  # <-- This is a function
print"Argon          "
print"Radon          "
print"Xenon          "
print"Erbium         "
print"Cobalt         "
print"Copper         "
print"Helium         "
print"Indium         "
print"Iodine         "
print"Osmium         "
print"Oxygen         "
print"Radium         "
print"Silver         "
print"Sodium         "
print"Sulfur         "
print"Arsenic        "
print"Bismuth        "
print"Bohrium        "
print"Bromine        "
print"Cadmium        "
print"Dubnium        "
print"Fermium        "
print"Gallium        "
print"Hafnium        "
print"Hassium        "
print"Holmium        "
print"Iridium        "
print"Krypton        "
print"Lithium        "
print"Mercury        "
print"Niobium        "
print"Rhenium        "
print"Rhodium        "
print"Silicon        "
print"Terbium        "
print"Thulium        "
print"Uranium        "
print"Yttrium        "
print"Actinium       "
print"Antimony       "
print"Astatine       "
print"Chlorine       "
print"Chromium       "
print"Europium       "
print"Fluorine       "
print"Francium       "
print"Hydrogen       "
print"Lutetium       "
print"Nitrogen       "
print"Nobelium       "
print"Platinum       "
print"Polonium       "
print"Rubidium       "
print"Samarium       "
print"Scandium       "
print"Selenium       "
print"Tantalum       "
print"Thallium       "
print"Titanium       "
print"Tungsten       "
print"Vanadium       "
print"Nihonium       "
print"Aluminium      "
print"Americium      "
print"Berkelium      "
print"Beryllium      "
print"Flerovium      "
print"Germanium      "
print"Lanthanum      "
print"Magnesium      "
print"Manganese      "
print"Neodymium      "
print"Neptunium      "
print"Palladium      "
print"Plutonium      "
print"Potassium      "
print"Ruthenium      "
print"Strontium      "
print"Tellurium      "
print"Ytterbium      "
print"Zirconium      "
print"Moscovium      "
print"Oganesson      "
print"Dysprosium     "
print"Gadolinium     "
print"Lawrencium     "
print"Meitnerium     "
print"Molybdenum     "
print"Phosphorus     "
print"Promethium     "
print"Seaborgium     "
print"Technetium     "
print"Tennessine     "
print"Californium    "
print"Copernicium    "
print"Einsteinium    "
print"Livermorium    "
print"Mendelevium    "
print"Roentgenium    "
print"Darmstadtium   "
print"Praseodymium   "
print"Protactinium   "
print"Rutherfordium  "
</code>```

Update

[16-09-08] Sublime added an extra space when joining to a line that ends in a comment character

[16-09-08] Made each slice 22 characters long and added gif

Title: Chuck Norris vs Travelling Salesman

Body:
Python, L = 2596, N = 118, Score = 0.186

The length of each slice is 22 so that makes this pretty lengthy.

lambda:"Gold"; print"""";print "Carbon     "print   "Thorium     "print   "Curium      "print "Calcium       "print "Nickel        "print      "Zinc     "print    "Neon       "print "Boron         "print   "Iron        "print  "Cerium       "print "Barium        "print "Caesium       """[9::22];lambda:"Tin"[0];lambda:"Lead    "#print"Argon          "print"Radon          "print"Xenon          "print"Erbium         "print"Cobalt         "print"Copper         "print"Helium         "print"Indium         "print"Iodine         "print"Osmium         "print"Oxygen         "print"Radium         "print"Silver         "print"Sodium         "print"Sulfur         "print"Arsenic        "print"Bismuth        "print"Bohrium        "print"Bromine        "print"Cadmium        "print"Dubnium        "print"Fermium        "print"Gallium        "print"Hafnium        "print"Hassium        "print"Holmium        "print"Iridium        "print"Krypton        "print"Lithium        "print"Mercury        "print"Niobium        "print"Rhenium        "print"Rhodium        "print"Silicon        "print"Terbium        "print"Thulium        "print"Uranium        "print"Yttrium        "print"Actinium       "print"Antimony       "print"Astatine       "print"Chlorine       "print"Chromium       "print"Europium       "print"Fluorine       "print"Francium       "print"Hydrogen       "print"Lutetium       "print"Nitrogen       "print"Nobelium       "print"Platinum       "print"Polonium       "print"Rubidium       "print"Samarium       "print"Scandium       "print"Selenium       "print"Tantalum       "print"Thallium       "print"Titanium       "print"Tungsten       "print"Vanadium       "print"Nihonium       "print"Aluminium      "print"Americium      "print"Berkelium      "print"Beryllium      "print"Flerovium      "print"Germanium      "print"Lanthanum      "print"Magnesium      "print"Manganese      "print"Neodymium      "print"Neptunium      "print"Palladium      "print"Plutonium      "print"Potassium      "print"Ruthenium      "print"Strontium      "print"Tellurium      "print"Ytterbium      "print"Zirconium      "print"Moscovium      "print"Oganesson      "print"Dysprosium     "print"Gadolinium     "print"Lawrencium     "print"Meitnerium     "print"Molybdenum     "print"Phosphorus     "print"Promethium     "print"Seaborgium     "print"Technetium     "print"Tennessine     "print"Californium    "print"Copernicium    "print"Einsteinium    "print"Livermorium    "print"Mendelevium    "print"Roentgenium    "print"Darmstadtium   "print"Praseodymium   "print"Protactinium   "print"Rutherfordium  "

Here is the Salesman after the slicing and dicing:

lambda:"Gold"; print""  # <-- This is a function
"";print "Carbon     "
print   "Thorium     "
print   "Curium      "
print "Calcium       "
print "Nickel        "
print      "Zinc     "
print    "Neon       "
print "Boron         "
print   "Iron        "
print  "Cerium       "
print "Barium        "
print "Caesium       "
""[9::22];lambda:"Tin"  # <-- This is a function and the choke point
[0];lambda:"Lead    "#  # <-- This is a function
print"Argon          "
print"Radon          "
print"Xenon          "
print"Erbium         "
print"Cobalt         "
print"Copper         "
print"Helium         "
print"Indium         "
print"Iodine         "
print"Osmium         "
print"Oxygen         "
print"Radium         "
print"Silver         "
print"Sodium         "
print"Sulfur         "
print"Arsenic        "
print"Bismuth        "
print"Bohrium        "
print"Bromine        "
print"Cadmium        "
print"Dubnium        "
print"Fermium        "
print"Gallium        "
print"Hafnium        "
print"Hassium        "
print"Holmium        "
print"Iridium        "
print"Krypton        "
print"Lithium        "
print"Mercury        "
print"Niobium        "
print"Rhenium        "
print"Rhodium        "
print"Silicon        "
print"Terbium        "
print"Thulium        "
print"Uranium        "
print"Yttrium        "
print"Actinium       "
print"Antimony       "
print"Astatine       "
print"Chlorine       "
print"Chromium       "
print"Europium       "
print"Fluorine       "
print"Francium       "
print"Hydrogen       "
print"Lutetium       "
print"Nitrogen       "
print"Nobelium       "
print"Platinum       "
print"Polonium       "
print"Rubidium       "
print"Samarium       "
print"Scandium       "
print"Selenium       "
print"Tantalum       "
print"Thallium       "
print"Titanium       "
print"Tungsten       "
print"Vanadium       "
print"Nihonium       "
print"Aluminium      "
print"Americium      "
print"Berkelium      "
print"Beryllium      "
print"Flerovium      "
print"Germanium      "
print"Lanthanum      "
print"Magnesium      "
print"Manganese      "
print"Neodymium      "
print"Neptunium      "
print"Palladium      "
print"Plutonium      "
print"Potassium      "
print"Ruthenium      "
print"Strontium      "
print"Tellurium      "
print"Ytterbium      "
print"Zirconium      "
print"Moscovium      "
print"Oganesson      "
print"Dysprosium     "
print"Gadolinium     "
print"Lawrencium     "
print"Meitnerium     "
print"Molybdenum     "
print"Phosphorus     "
print"Promethium     "
print"Seaborgium     "
print"Technetium     "
print"Tennessine     "
print"Californium    "
print"Copernicium    "
print"Einsteinium    "
print"Livermorium    "
print"Mendelevium    "
print"Roentgenium    "
print"Darmstadtium   "
print"Praseodymium   "
print"Protactinium   "
print"Rutherfordium  "

Update

[16-09-08] Sublime added an extra space when joining to a line that ends in a comment character

[16-09-08] Made each slice 22 characters long and added gif


Title: Invalid Invali Inval

Body:
Haskell, <s>49</s> 46 bytes

f=(>>=(<$>['0'..'9']).snoc).reverse.tail.inits


Title: Slowly turn a string into another

Body:
PHP, <s>117</s> 109 bytes

for($i=strlen($a=$argv[1]);$i>1;)echo" ".substr($a,0,$i--);
for(;$j<strlen($b=$argv[2]);)echo" ".$c.=$b[$j++];

<s>

for($i=strlen($a=$argv[1]);$i>1;)echo substr($a,0,$i--)." ";
for(;$i<=strlen($b=$argv[2]);)echo substr($b,0,$i++)." ";

</s>

PHP, 107 bytes (not working with strings containing 0)

for($a=$argv[1];$a[$i];)echo substr($a.a,0,-++$i)." ";
for($b=$argv[2];$b[$j];)echo substr($b,0,++$j+1)." ";


问:
Tree traversal.
Write the shortest code that traverses a tree, breadth-first.

Input

any way you like

Output

a list of "names" of the nodes in correct order.

ContentLicense: CC BY-SA 2.5

Title: Tree traversal.

Body:
Python - 59 chars

This one returns a generator, but modifies T, so you may want to pass in a copy

def f(T):
 t=iter(T)
 for i in t:yield i;T+=next(t)+next(t)

testing

              4
             / \
            /   \
           /     \
          2       9
         / \     / \
        1   3   6   10
               / \
              5   7
                   \
                    8

>>> T=[4,[2,[1,[],[]],[3,[],[]]],[9,[6,[5,[],[]],[7,[],[8,[],[]]]],[10,[],[]]]]
>>> f(T)
<generator object f at 0x87a31bc>
>>> list(_)
[4, 2, 9, 1, 3, 6, 10, 5, 7, 8]


Title: Rolling three dice and show the probabilities

Body:
Roll 3 dice, count the two highest two values and add them to the result. Every 1 must be rolled once again.

Now show the average throw after 1000000 tries and the probabilities for each result occurring:

Desired Result:

avg(9.095855)

  2: 0.0023

  3: 0.0448

  4: 1.1075

  5: 2.8983

  6: 6.116

  7: 10.1234

  8: 15.4687

  9: 18.9496

  10: 19.3575

  11: 16.0886

  12: 9.8433

Body:
map{@f=(sort((&r,&r,&r)[1,2]));$d[$f[0]+$f[1]]++}(1..1E6);
map{$s+=$d[$_]*$_}(0..$#d);print"avg(".$s/1E6.")\n";map{print"$_:
".$d[$_]/1E4."\n"}(0..$#d);
sub r{$x=1+int(rand 6);$x>1?$x:&r}

    ~/play/golf/dice$ perl dice.pl
    avg(8.000533)
    0: 0
    1: 0
    2: 0
    3: 0
    4: 3.9796
    5: 8.0376
    6: 11.9607
    7: 16.0064
    8: 20.0094
    9: 15.9636
    10: 12.0582
    11: 8.0057
    12: 3.9788


答:
C#, 129 bytes

```<code>void f(string i, string j){for(int k=i.Length,l=0;i!=j;){Console.Write(i+'\n');i=k>1?i.Remove(--k):i+j[k+l++];}Console.Write(i);}
</code>```

Ungolfed

```<code>void f(string i, string j)
{
   for (int k = i.Length, l = 0; i != j; )
   {
      Console.Write(i+'\n');
      i = k > 1 ? i.Remove(--k) : i + j[k + l++];
   }
   Console.Write(i);
}
</code>```

Title: Slowly turn a string into another

Body:
C#, 129 bytes

void f(string i, string j){for(int k=i.Length,l=0;i!=j;){Console.Write(i+'\n');i=k>1?i.Remove(--k):i+j[k+l++];}Console.Write(i);}

Ungolfed

void f(string i, string j)
{
   for (int k = i.Length, l = 0; i != j; )
   {
      Console.Write(i+'\n');
      i = k > 1 ? i.Remove(--k) : i + j[k + l++];
   }
   Console.Write(i);
}


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

答:
Mathematica <s>100</s> 219 bytes

If ASCII-Art need not be Terminal-Art this should be valid.

My earlier submission mistakenly drew a star rather than a hexagon.
I can't see how I was so off!

```<code>c = CirclePoints@6;
f@s_:=Graphics[{Text[s~StringPart~1,{0,0}],Flatten@Table[Text[StringPart[s,n+1],#]&/@Subdivide[Sequence@@#,n]&/@Partition[Riffle[(n)CirclePoints@6,RotateLeft[n CirclePoints@6]],2],{n,1,StringLength@s-1}]},BaseStyle->20]
</code>```

CirclePoints@6 returns the vertices of a unit hexagon, assuming that the center is at the origin.

Subdivideing the coordinates for neighboring vertices finds equally spaced positions along the respective edge.

A counter from 1 through the StringLength -1 of the input string allows each layer of the wordagon to be handled separately.

As n increases, so does the respective distance of each vertex from the origin.

Text[s~StringPart~1,{0,0}] prints the first letter of the input at the origin.

f@"Wordagon"

For the curious, this is what the star version looked like.
I know, it was way off the mark. It only showed the letters at the hexagon's vertices.

```<code>Graphics@Table[Text[Style[StringPart[#, r + 1], 54], r {Cos@t, Sin@t}], {t, 0, 2π, π/3}, {r, 0, StringLength@# - 1}] &["Hexa"]
</code>```

Title: HexaGolf: Wordagons

Body:
Mathematica <s>100</s> 219 bytes

If ASCII-Art need not be Terminal-Art this should be valid.

My earlier submission mistakenly drew a star rather than a hexagon.
I can't see how I was so off!

c = CirclePoints@6;
f@s_:=Graphics[{Text[s~StringPart~1,{0,0}],Flatten@Table[Text[StringPart[s,n+1],#]&/@Subdivide[Sequence@@#,n]&/@Partition[Riffle[(n)CirclePoints@6,RotateLeft[n CirclePoints@6]],2],{n,1,StringLength@s-1}]},BaseStyle->20]

CirclePoints@6 returns the vertices of a unit hexagon, assuming that the center is at the origin.

Subdivideing the coordinates for neighboring vertices finds equally spaced positions along the respective edge.

A counter from 1 through the StringLength -1 of the input string allows each layer of the wordagon to be handled separately.

As n increases, so does the respective distance of each vertex from the origin.

Text[s~StringPart~1,{0,0}] prints the first letter of the input at the origin.

f@"Wordagon"

For the curious, this is what the star version looked like.
I know, it was way off the mark. It only showed the letters at the hexagon's vertices.

Graphics@Table[Text[Style[StringPart[#, r + 1], 54], r {Cos@t, Sin@t}], {t, 0, 2π, π/3}, {r, 0, StringLength@# - 1}] &["Hexa"]


问:
Steps of Permutation
Write a function which takes a set of integers and prints every permutation of the set, and the swap performed in between each step

Input

a set of integers, for example (0, 1, 2)

Output

the list of permutations and swaps in the format
(set)
(swap)
(set)
...

Test case

```<code>Input:
(3, 1, 5)

Output:
(3, 1, 5)
(3, 1)
(1, 3, 5)
(3, 5)
(1, 5, 3)
(1, 3)
(3, 5, 1)
(3, 5)
(5, 3, 1)
(3, 1)
(5, 1, 3)
</code>```

Rules

You can format the set of numbers however you want.

You can do the swaps in any order

You can repeat permutations and swaps in order to get a new one

Your code doesn't have to actually perform the swaps, the output just needs to show what swap was made between your last output and your current one

Your code only needs to function for sets with 2 or more elements

The set you're given will have no repeating elements (e.g. (0, 1, 1, 2) is invalid)

This is code-golf, so shortest code wins!

答:
Haskell - 135 bytes

```<code>p=permutations;f=filter
q(a:b:xs)=(\x->f(uncurry(/=)).zip x)a b:q(b:xs);q _=[]
l=head.f(all((==2).length).q).p.p
f=zip.l<*>map head.q.l
</code>```

output:

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

I am using the standard permutations function, which is not based on swaps, so I am taking the permutations of the permutations and finding one that happens to be a chain of swaps.

Title: Steps of Permutation

Body:
Haskell - 135 bytes

p=permutations;f=filter
q(a:b:xs)=(\x->f(uncurry(/=)).zip x)a b:q(b:xs);q _=[]
l=head.f(all((==2).length).q).p.p
f=zip.l<*>map head.q.l

output:

> f [3,1,5]
[([3,1,5],(3,1)),([1,3,5],(3,5)),([1,5,3],(1,5)),([5,1,3],(1,3)),([5,3,1],(5,3))]

I am using the standard permutations function, which is not based on swaps, so I am taking the permutations of the permutations and finding one that happens to be a chain of swaps.


答:
Python 2, 83 bytes

s=input()
l=len(s)
while 1:l-=1;y=abs(l);print' '*y+' '.join(s[:y:-1]+s[y]*y+s[y:])
```

<p>Prints the wordagon and then crashes (which only prints to STDERR).</p>

<p>Example:</p>

```% python2.7 wordagon.py <<<'"abcde"' 2&>/dev/null
    e e e e e
   e d d d d e
  e d c c c d e
 e d c b b c d e
e d c b a b c d e
 e d c b b c d e
  e d c c c d e
   e d d d d e
    e e e e e
```

xnor saved 5 bytes. Thanks!

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:
Python 2, 83 bytes

s=input()
l=len(s)
while 1:l-=1;y=abs(l);print' '*y+' '.join(s[:y:-1]+s[y]*y+s[y:])

Prints the wordagon and then crashes (which only prints to STDERR).

Example:

% python2.7 wordagon.py <<<'"abcde"' 2&>/dev/null
    e e e e e
   e d d d d e
  e d c c c d e
 e d c b b c d e
e d c b a b c d e
 e d c b b c d e
  e d c c c d e
   e d d d d e
    e e e e e

xnor saved 5 bytes. Thanks!


答:
C++, 120 bytes

```<code>[](string s,string t){int n=s.length(),k=t.length(),l=n,j=0;s+=t;while(n?n:++j<k)cout<<s.substr(n?0:l,n?n--:1+j)<<endl;}
</code>```

Ungolfed test

```<code>#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main(void)
{
    string s1 = "Test";
    string s2 = "Testing";
    auto f = [](string s, string t)
    {
        int n = s.length(),
            k = t.length(),
            l = n,
            j = 0;
        s += t;
        while (n?n:++j<k)
            cout << s.substr( n?0:l, n?n--:1+j) << endl;
    };
    f(s1, s2);
    return 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++, 120 bytes

[](string s,string t){int n=s.length(),k=t.length(),l=n,j=0;s+=t;while(n?n:++j<k)cout<<s.substr(n?0:l,n?n--:1+j)<<endl;}

Ungolfed test

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main(void)
{
    string s1 = "Test";
    string s2 = "Testing";
    auto f = [](string s, string t)
    {
        int n = s.length(),
            k = t.length(),
            l = n,
            j = 0;
        s += t;
        while (n?n:++j<k)
            cout << s.substr( n?0:l, n?n--:1+j) << endl;
    };
    f(s1, s2);
    return 0;
}


答:
C (gcc), <s>102</s> <s>97</s> <s>95</s> 93 bytes

n;f(char*a,char*b){for(n=strlen(a);n;puts(a))a[n--]=0;for(a=b+1;*a++;*a=n)n=*a,*a=0,puts(b);}
```

Try it online!

The first loop overwrites the string with 0 bytes starting from the end, and uses puts() to print the string. The second loop can't just overwrite from the beginning, it has to store the old value so it can put it back; the 0 byte is just walking towards the end.

Thanks to @homersimpson and @ceilingcat for each shaving off 2 bytes!

Title: Slowly turn a string into another

Body:
C (gcc), <s>102</s> <s>97</s> <s>95</s> 93 bytes

n;f(char*a,char*b){for(n=strlen(a);n;puts(a))a[n--]=0;for(a=b+1;*a++;*a=n)n=*a,*a=0,puts(b);}

Try it online!

The first loop overwrites the string with 0 bytes starting from the end, and uses puts() to print the string. The second loop can't just overwrite from the beginning, it has to store the old value so it can put it back; the 0 byte is just walking towards the end.

Thanks to @homersimpson and @ceilingcat for each shaving off 2 bytes!


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

答:
Retina, 55 bytes

```<code>O$i`[a-m](?=.*([a-m]))?
$1
O$i`((?<![n-z].*))?[n-z]
$#1
</code>```

Try it online!

Uses two sorting stages to rotate the first- and second-half letters separately.

Title: Double rotation

Body:
Retina, 55 bytes

O$i`[a-m](?=.*([a-m]))?
$1
O$i`((?<![n-z].*))?[n-z]
$#1

Try it online!

Uses two sorting stages to rotate the first- and second-half letters separately.


答:
CJam, 41 bytes

```<code>lee_{'N,_el^:A&},_1m>er_{ADf+&},_1m<erWf=
</code>```

Try it online!

Uses a similar approach to my vowel shuffling answer.

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:
CJam, 41 bytes

lee_{'N,_el^:A&},_1m>er_{ADf+&},_1m<erWf=

Try it online!

Uses a similar approach to my vowel shuffling answer.


答:
Now a more optimized version, with a shifted RNG (no reroll), and shortened statistics calcs, also exploiting the ordering due to the ascii nature of single integers.

```<code>map{@f=(sort((&r,&r,&r)[1,2]));$i=$f[0]+$f[1];$d[$i]++;$s+=$i}(1..1E6);
print"avg(".$s/1E6.")\n";map{print"$_: ".$d[$_]/1E4."\n"}(0..$#d);
sub r{2+int(rand 5)}
</code>```

As you can see, printing uses almost as much space as computing here.  If you'd like a simpler output, this would save characters.

```<code>avg(8.000901)
0: 0
1: 0
2: 0
3: 0
4: 4.0007
5: 7.9769
6: 11.9652
7: 16.0226
8: 20.0156
9: 16.0389
10: 11.9983
11: 7.9861
12: 3.9957
</code>```

Body:
Now a more optimized version, with a shifted RNG (no reroll), and shortened statistics calcs, also exploiting the ordering due to the ascii nature of single integers.

map{@f=(sort((&r,&r,&r)[1,2]));$i=$f[0]+$f[1];$d[$i]++;$s+=$i}(1..1E6);
print"avg(".$s/1E6.")\n";map{print"$_: ".$d[$_]/1E4."\n"}(0..$#d);
sub r{2+int(rand 5)}

As you can see, printing uses almost as much space as computing here.  If you'd like a simpler output, this would save characters.

avg(8.000901)
0: 0
1: 0
2: 0
3: 0
4: 4.0007
5: 7.9769
6: 11.9652
7: 16.0226
8: 20.0156
9: 16.0389
10: 11.9983
11: 7.9861
12: 3.9957