问:
Image Smoothie!
Input into your program a black and white image. (png, jpg, etc)

Convert the image to a 2D matrix of pixels, where each index is the grayscale value of the image.

Take each index of the matrix and average the 8 pixels around it. Then replace that index with the average.

For example if you had:

```<code>120 80  60
20  10  30
40  100 05
</code>```

If you were finding the average for 10, the result would be 56.875, which is (120,80,60,30,05,100,40,20)/8.

Round to up to the nearest integer (57) and replace the index. The result of this iteration would be

```<code>120 80  60
20  57  30
40  100 05
</code>```

If you are finding the average for a pixel on an edge then only take values that are valid. In the example above if you were finding the average for 20 You would only consider 120, 80, 57, 100, and 40 which is 79.4 rounded to 80.

You may start at any index of the graph but it must be in order. For example you could do

```<code>[0][0], [0][1], ... [0][n], then [1][0], [1][1],... [1][n]
</code>```

Once the averaging is complete, convert the matrix back into a new image.

Display the new image as the output of the program. (Or save it and add it in your solution). The result of your code should be a blurry looking image but much smoother than the original.

Example Input

Example Output

Example Input two

Example Output two

Please provide your code and start and end image results.

Q/A

1Q. If one of the 8 neighbors has already been changed, should the average be calculated based on this new value, or based on the original values? That is, does the order of calculation affect the end result?

1A Yes, You should change each index with new values from any potential indices done before. That is why you need to go left-right, top-bottom etc. In order.

2Q. Could you clarify what is meant by "must be in order"? Does this mean that only raster order/reading order is acceptable? Or does it mean that the order must be the same each time the code is run? Would a spiral be valid? Or a shuffled order that is always the same?

2A. You should go left to right, right to left, top to bottom, or bottom to top. I.E. Do all of the 0th row, do all of the 1st row,... do all of the nth row

答:
J, <s>90</s> 82 bytes

```<code>[:((=i.@$){"0 1],"+3 3((+/>.@%#)@(_-.~(<<<4){,);._3)_,.~_,._,~_,])&.>/(#<@-#\)@,,<
</code>```

This iterates over pixels from left-to-right, then top-to-bottom.

You can see the progression of values here.

```<code>   |. ((=i.@$){"0 1],"+3 3((+/>.@%#)@(_-.~(<<<4){,);._3)_,.~_,._,~_,])&.>/\. ((#<@-#\)@,,<) 120 80 60 , 20 10 30 ,: 40 100 5
┌──────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬────────┬────────┐
│120  80 60│37  80 60│37  32 60│37  32 24│37  32 24│37  32 24│37  32 24│37  32 24│37 32 24│37 32 24│
│ 20  10 30│20  10 30│20  10 30│20  10 30│44  10 30│44  39 30│44  39 40│44  39 40│44 39 40│44 39 40│
│ 40 100  5│40 100  5│40 100  5│40 100  5│40 100  5│40 100  5│40 100  5│61 100  5│61 38  5│61 38 39│
└──────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴────────┴────────┘
</code>```

The output for the first sample image is (converting from an array of pixels to a bmp)

Title: Image Smoothie!

Body:
J, <s>90</s> 82 bytes

[:((=i.@$){"0 1],"+3 3((+/>.@%#)@(_-.~(<<<4){,);._3)_,.~_,._,~_,])&.>/(#<@-#\)@,,<

This iterates over pixels from left-to-right, then top-to-bottom.

You can see the progression of values here.

   |. ((=i.@$){"0 1],"+3 3((+/>.@%#)@(_-.~(<<<4){,);._3)_,.~_,._,~_,])&.>/\. ((#<@-#\)@,,<) 120 80 60 , 20 10 30 ,: 40 100 5
┌──────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬────────┬────────┐
│120  80 60│37  80 60│37  32 60│37  32 24│37  32 24│37  32 24│37  32 24│37  32 24│37 32 24│37 32 24│
│ 20  10 30│20  10 30│20  10 30│20  10 30│44  10 30│44  39 30│44  39 40│44  39 40│44 39 40│44 39 40│
│ 40 100  5│40 100  5│40 100  5│40 100  5│40 100  5│40 100  5│40 100  5│61 100  5│61 38  5│61 38 39│
└──────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴────────┴────────┘

The output for the first sample image is (converting from an array of pixels to a bmp)


问:
Make an ASCII bat fly around an ASCII moon
Background

Here is a Halloween related challenge.

As you may have seen from my last challenge I quite like what I term as ascii art animations, that is not just draw a pattern but draw a pattern that progresses. This idea came to me after I was asked a couple of years ago to liven up a (rather dull) presentation by making random ascii bats fly across the screen on Halloween. Needless to say I duly obliged (I was being paid for it) but it made me think that there is more to life than random bats. Inspired by this I would like to propose this challenge.

Challenge

Make a bat fly around the moon.

Here is a bat:

```<code>^o^
</code>```

Here is the moon:

```<code>     mmm
   mmmmmmm
  mmmmmmmmm
   mmmmmmm
     mmm
</code>```

You must show every stage of the bats flight (see output).

Input

None

Output

```<code>      ^o^
      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

      mmm^o^
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

      mmm
    mmmmmmm^o^
   mmmmmmmmm
    mmmmmmm
      mmm

      mmm
    mmmmmmm
   mmmmmmmmm^o^
    mmmmmmm
      mmm

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm^o^
      mmm

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm^o^

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm
      ^o^

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
   ^o^mmm

      mmm
    mmmmmmm
   mmmmmmmmm
 ^o^mmmmmmm
      mmm

      mmm
    mmmmmmm
^o^mmmmmmmmm
    mmmmmmm
      mmm

      mmm
 ^o^mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

   ^o^mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

      ^o^
      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm
</code>```

Rules

No reading from external files or websites

You may submit a full program or a function

Extra spaces and/or newlines are fine by me

Standard loopholes banned as usual

The bat must finish back at the top of the moon

Please feel free to clear the screen between frames if you wish however this is not a requirement. Output as shown above is fine

As this is code golf, the winner will be the answer with the lowest byte count although any answer is welcome

Sample

Reference implementation in totally ungolfed Python 2 (620 bytes but just to prove that it can be done. May golf it later).

```<code>b='^o^'
m=['                     ',
'         mmm         ',
'       mmmmmmm       ',
'      mmmmmmmmm      ',
'       mmmmmmm       ',
'         mmm         ',
'                     ']
p=[(9,12),(12,15),(14,17),(15,18),(14,17),(12,15),(9,12),(6,9),(4,7),(3,6),(4,7),(6,9),(9,12)]
d=0
for z in range(7):
    x=map(str,m[z])
    c="".join(x[:p[z][0]]) + b + "".join(x[p[z][1]:])+"\n"
    print "\n".join(m[:z]) + "\n" + c+"\n".join(m[z+1:])
for z in range(6)[::-1]:
    x=map(str,m[z])
    c="".join(x[:p[z+6][0]]) + b + "".join(x[p[z+6][1]:])+"\n"
    print "\n".join(m[:z]) + "\n" + c+"\n".join(m[z+1:])
</code>```

Result

Although @Jonathan obviously wins on byte count with Jelly, I am going to mark the Brainfuck answer from @Oyarsa as the accepted answer purely because I think that anyone who can actually do something like this in such a crazy language deserves +15 rep no matter how many bytes it takes. This is not because I have any problem with golfing languages. See my answer to a question regarding this on meta if you have any doubts. Many thanks and respect to all who contributed in whatever language.

答:
JavaScript (ES6), <s>109</s> <s>144</s> <s>140</s> 138 bytes

f=(k=13,b=y=>(y-k)%12?'   ':'^o^')=>k--?[0,3,7,9,7,3,0].map((n,y)=>' '.repeat(5-n/2+!n)+b(y)+'m'.repeat(n)+b(n?-y:.1)).join`
`+`
`+f(k):''

console.log(f());```
</div>
</div>
</p>
<h3>Animated version</h3>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=(k,b=y=>(y-k)%12?'   ':'^o^')=>[0,3,7,9,7,3,0].map((n,y)=>' '.repeat(5-n/2+!n)+b(-y)+'m'.repeat(n)+b(n?y:.1)).join`
`

var k =0;
setInterval(function() { o.innerHTML = f(k++) }, 150);</code>```

```</code>```

ContentLicense: CC BY-SA 3.0

Body:
JavaScript (ES6), <s>109</s> <s>144</s> <s>140</s> 138 bytes

f=(k=13,b=y=>(y-k)%12?'   ':'^o^')=>k--?[0,3,7,9,7,3,0].map((n,y)=>' '.repeat(5-n/2+!n)+b(y)+'m'.repeat(n)+b(n?-y:.1)).join`
`+`
`+f(k):''

console.log(f());

Animated version

f=(k,b=y=>(y-k)%12?'   ':'^o^')=>[0,3,7,9,7,3,0].map((n,y)=>' '.repeat(5-n/2+!n)+b(-y)+'m'.repeat(n)+b(n?y:.1)).join`
`

var k =0;
setInterval(function() { o.innerHTML = f(k++) }, 150);

<pre id=o></pre>


问:
Export The $PATH Variable, Line-By-Line
Inspired by this question on AskUbuntu.

Your job is extremely simple. Take the PATH environment variable (echo $PATH) and export it such that each entry (separated by the : character) is on its own line.

For example, if the PATH is /bin:/usr/bin:/usr/local/bin, your program should output:

```<code>/bin
/usr/bin
/usr/local/bin
</code>```

Your program may not return a leading newline, but it may return a single trailing newline. You do not need to check if the PATH is right, or that the directory exists. Your program should take no input, meaning that your program is responsible for getting the PATH itself. You may safely assume that objects in the PATH do not contain : or newlines. However, spaces are fair game.

Reference implementations are present in the answers to the question above.

Rules

This is (obviously) code-golf, so the shortest answer will win the prized green checkmark.

The accepted answer will be tested to make sure it's actually legit.

Both Windows and *nix entries are accepted.

However, if you don't explicitly specify Windows, I will try running it in Linux and fail. (If it's obvious (hi, Batch!), you don't need to specify explicitly.)

Only have one solution per answer. If you have both a Windows and *nix version, I will count the shorter one.

If two answers have the same length, I will give priority to the one with the higher vote total. If they have the same vote total, I will count the older one. If the time posted is the same, I will choose the one that executes faster. If they execute in the same amount of time, I don't know.

Leaderboard

var QUESTION_ID=96334,OVERRIDE_USER=15422;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

```

答:
Groovy, 43 Bytes

```<code>System.env['PATH'].replaceAll(":","\n")
</code>```

Title: Export The $PATH Variable, Line-By-Line

Body:
Groovy, 43 Bytes

System.env['PATH'].replaceAll(":","\n")


问:
Generate a 6 character string from a 15 character alphabet
In one of our projects at work, we recently discovered a particularly large method for generating a 6 character string from a 15 character alphabet. A few of us claimed "I bet we can get that in one line" which started a little internal game of code golf.

Your task is to beat us, which I have no doubt won't take long!

The original algorithm used the alphabet 0-9A-E, but we've experimented with other alphabets. There are therefore three subtasks.

Generate a 6 character string randomly selecting from an arbitrary hardcoded 15 character alphabet like ABC123!@TPOI098. (This is just an example, and should be customizable without affecting the byte count.)

Generate a 6 character string randomly selecting from a 15 character alphabet 0123456789ABCDE.

Generate a 6 character string randomly selecting from a 15 character alphabet of your choice (printable characters only please).

Each character should have equal chance of selection and repetition should be possible.

The best we have been able to manage for each of the subtasks is:

"ABC123!@TPOI098" - 24 bytes

"0123456789ABCDE" - 21 bytes

Custom alphabet   -  13 bytes

Your score is the sum of the bytes in each subtask's solution. i.e. our score is currently 58.

We've attempted using among others, CJam and Ruby. The original was in C#. Use any language you like, but we'll be interested to see solutions in these languages particularly

答:
PowerShell v2+, 45 + 44 + 37 = 126 bytes

Fixed alphabet, 45 bytes

```<code>-join(0..5|%{'ABC123!@TPOI098'[(Random)%15]})
</code>```

Nearly-hexadecimal alphabet, 44 bytes

```<code>-join[char[]](0..5|%{Random(48..57+65..69)})
</code>```

Custom alphabet (A to O), 37 bytes

```<code>-join[char[]](0..5|%{Random(65..79)})
</code>```

All of these follow the same pattern -- loop from 0 to 5, each iteration selecting a Random character or ASCII value, casting that as a char-array if necessary, and -joining it together into a string. That string is left on the pipeline, and output is implicit.

Examples

```<code>PS C:\Tools\Scripts\golfing> -join(0..5|%{'ABC123!@TPOI098'[(Random)%15]})
32ATB3

PS C:\Tools\Scripts\golfing> -join(0..5|%{'ABC123!@TPOI098'[(Random)%15]})
III@B2

PS C:\Tools\Scripts\golfing> -join(0..5|%{'ABC123!@TPOI098'[(Random)%15]})
@302O@

PS C:\Tools\Scripts\golfing> -join[char[]](0..5|%{Random(48..57+65..69)})
74E117

PS C:\Tools\Scripts\golfing> -join[char[]](0..5|%{Random(48..57+65..69)})
09D7DD

PS C:\Tools\Scripts\golfing> -join[char[]](0..5|%{Random(65..79)})
COJDFI

PS C:\Tools\Scripts\golfing> -join[char[]](0..5|%{Random(65..79)})
EAKCNJ
</code>```

Body:
PowerShell v2+, 45 + 44 + 37 = 126 bytes

Fixed alphabet, 45 bytes

-join(0..5|%{'ABC123!@TPOI098'[(Random)%15]})

Nearly-hexadecimal alphabet, 44 bytes

-join[char[]](0..5|%{Random(48..57+65..69)})

Custom alphabet (A to O), 37 bytes

-join[char[]](0..5|%{Random(65..79)})

All of these follow the same pattern -- loop from 0 to 5, each iteration selecting a Random character or ASCII value, casting that as a char-array if necessary, and -joining it together into a string. That string is left on the pipeline, and output is implicit.

Examples

PS C:\Tools\Scripts\golfing> -join(0..5|%{'ABC123!@TPOI098'[(Random)%15]})
32ATB3

PS C:\Tools\Scripts\golfing> -join(0..5|%{'ABC123!@TPOI098'[(Random)%15]})
III@B2

PS C:\Tools\Scripts\golfing> -join(0..5|%{'ABC123!@TPOI098'[(Random)%15]})
@302O@

PS C:\Tools\Scripts\golfing> -join[char[]](0..5|%{Random(48..57+65..69)})
74E117

PS C:\Tools\Scripts\golfing> -join[char[]](0..5|%{Random(48..57+65..69)})
09D7DD

PS C:\Tools\Scripts\golfing> -join[char[]](0..5|%{Random(65..79)})
COJDFI

PS C:\Tools\Scripts\golfing> -join[char[]](0..5|%{Random(65..79)})
EAKCNJ


问:
Nest a string inside an array n times
You must produce a function which nests a string s inside an array, n times

```<code>>>> N("stackoverflow",2)
[['stackoverflow']]
</code>```

Parameters:

s - An ascii string

n - An integer >= 0

Rules

Shortest code wins.

The output will be a nested array, list or tuple (or similar type based off an array)

Test Cases

```<code>>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]
</code>```

Inspired by: Nesting a string inside a list n times ie list of a list of a list

答:
Pyke, 3 bytes

```<code>V]1
</code>```

Try it here!

Title: Nest a string inside an array n times

Body:
Pyke, 3 bytes

V]1

Try it here!


答:
Ruby: 23 bytes

```<code>->n,s{n.times{s=[s]};s}
</code>```

This is updated to make it a callable Proc rather than the original snippet. I'd be interested to know whether there's a way to have s implicitly returned rather than having to explicitly return it.

Title: Nest a string inside an array n times

Body:
You must produce a function which nests a string s inside an array, n times

```<code>>>> N("stackoverflow",2)
[['stackoverflow']]
</code>```

Parameters:

s - An ascii string

n - An integer >= 0

Rules

Shortest code wins.

The output will be a nested array, list or tuple (or similar type based off an array)

Test Cases

```<code>>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]
</code>```

Inspired by: Nesting a string inside a list n times ie list of a list of a list

Body:
Ruby: 23 bytes

->n,s{n.times{s=[s]};s}

This is updated to make it a callable Proc rather than the original snippet. I'd be interested to know whether there's a way to have s implicitly returned rather than having to explicitly return it.


问:
Real Chebyshev Rotation
This is a challenge inspired by Chebyshev Rotation. I suggest looking at answers there to get inspiration for this challenge.

Given a point on the plane there is a unique square (a rectangle with equal sides) that is centered on the origin and intersects that point (interactive demo):

Given a point p and a distance d, return the point obtained by moving distance d from p, counter-clockwise (and clockwise for negative  d), along the perimeter of the square centered on the origin that intersects p. Your answer must be accurate to at least 4 decimal digits.

Testcases:

```<code>(0, 0), 100 -> (0, 0)
(1, 1), 81.42 -> (-0.4200, 1.0000)
(42.234, 234.12), 2303.34 -> (-234.1200, 80.0940)
(-23, -39.234), -234.3 -> (39.2340, -21.8960)
</code>```

The following test cases are from the original challenge by Martin Ender, and all are with d = 1:

```<code>(0, 0)       -> (0, 0)
(1, 0)       -> (1, 1)
(1, 1)       -> (0, 1)
(0, 1)       -> (-1, 1)
(-1, 1)      -> (-1, 0)
(-1, 0)      -> (-1, -1)
(-1, -1)     -> (0, -1)
(0, -1)      -> (1, -1)
(1, -1)      -> (1, 0)
(95, -12)    -> (95, -11)
(127, 127)   -> (126, 127)
(-2, 101)    -> (-3, 101)
(-65, 65)    -> (-65, 64)
(-127, 42)   -> (-127, 41)
(-9, -9)     -> (-8, -9)
(126, -127)  -> (127, -127)
(105, -105)  -> (105, -104)
</code>```

答:
Python 2, <s>363</s> <s>335</s> <s>296</s> <s>266</s> <s>262</s> <s>258</s> <s>256</s> 233 Bytes

Woo, 130 bytes lost! Thanks to Neil for saving 4 bytes, Nathan Merrill for saving 2 bytes, and xnor for saving a ridiculous 23 bytes!

The general idea is this: We can reduce the distance traveled by taking it's the modulus of it against the perimeter of the square. The perimeter is defined as 8 times the largest of the two coordinates, since the point must rest on it. Then, after modulus is taken we are guaranteed to have no overlap. It also guarantees we only ever have to move counter-clockwise, since modulus gives a positive result.

From there, I simply use what we know from the given x and y-coordinates to figure out where we are: top, bottom, left, right, or in a corner, and determine the direction, which can be one of 0, 1, 2, 3:

0 --> we are on the 'top', moving 'left'
1 --> we are on the 'left', moving 'down'
2 --> we are on the 'bottom', moving 'right'
3 --> we are on the 'right', moving 'up'
```

<p>After this, it is as simple as looping while we still have distance to travel, and based on the direction we subtract or add to the appropriate coordinate, and tell the loop which direction we are going next.</p>

<pre class="lang-py prettyprint-override"><code>p,d=input()
x,y=p
s=max(x,y,-x,-y)
d=d%(s*8or 1)
r=[(y<s)*[2,[3,x>-s][x<s]][y>-s],[2*(y<0),3*(y<=0)][x>0]][y*y==x*x]
while s>0<d:f=1-2*(r<2);m=abs(f*s-p[r%2]);j=d>m;p[r%2]=[p[r%2]+f*d,f*s][j];r=-~r%4;d=(d-m)*j
print"%.4f "*2%tuple(p)
</code>```

While quite long, it certainly works. Here's some example I/O:

[0, 0], 100 --> 0.0000 0.0000
[1, 1], 81.42 --> -0.4200 1.0000
[42.234, 234.12], 2303.34 --> -234.1200 80.0940
[-23, -39.234], -234.3 --> 39.2340 -21.8960
```

Try it online or run test cases.

Title: Real Chebyshev Rotation

Body:
Python 2, <s>363</s> <s>335</s> <s>296</s> <s>266</s> <s>262</s> <s>258</s> <s>256</s> 233 Bytes

Woo, 130 bytes lost! Thanks to Neil for saving 4 bytes, Nathan Merrill for saving 2 bytes, and xnor for saving a ridiculous 23 bytes!

The general idea is this: We can reduce the distance traveled by taking it's the modulus of it against the perimeter of the square. The perimeter is defined as 8 times the largest of the two coordinates, since the point must rest on it. Then, after modulus is taken we are guaranteed to have no overlap. It also guarantees we only ever have to move counter-clockwise, since modulus gives a positive result.

From there, I simply use what we know from the given x and y-coordinates to figure out where we are: top, bottom, left, right, or in a corner, and determine the direction, which can be one of 0, 1, 2, 3:

0 --> we are on the 'top', moving 'left'
1 --> we are on the 'left', moving 'down'
2 --> we are on the 'bottom', moving 'right'
3 --> we are on the 'right', moving 'up'

After this, it is as simple as looping while we still have distance to travel, and based on the direction we subtract or add to the appropriate coordinate, and tell the loop which direction we are going next.

p,d=input()
x,y=p
s=max(x,y,-x,-y)
d=d%(s*8or 1)
r=[(y<s)*[2,[3,x>-s][x<s]][y>-s],[2*(y<0),3*(y<=0)][x>0]][y*y==x*x]
while s>0<d:f=1-2*(r<2);m=abs(f*s-p[r%2]);j=d>m;p[r%2]=[p[r%2]+f*d,f*s][j];r=-~r%4;d=(d-m)*j
print"%.4f "*2%tuple(p)

While quite long, it certainly works. Here's some example I/O:

[0, 0], 100 --> 0.0000 0.0000
[1, 1], 81.42 --> -0.4200 1.0000
[42.234, 234.12], 2303.34 --> -234.1200 80.0940
[-23, -39.234], -234.3 --> 39.2340 -21.8960

Try it online or run test cases.


问:
Determine if a coin system is Canonical
The Cashier's Algorithm is an algorithm for making change in the minimal number of coins that works quite well for most currency systems.  However like most greedy algorithms it is not without its flaws.  If a currency system is set up just right (or just wrong) there are certain values in which the Cashier's Algorithm will fail to find the optimal change.

Take the following example:

We have 4¢, 3¢, and 1¢ coins.  We want to make 6¢.

The Cashier's Algorithm will first select as many of the largest coin (one 4¢ to start) and subtract and repeat.  This will result in one 4¢ coin and two 1¢ coins, for a total of 3 coins.

Unfortunately for the Algorithm there is a way to make 6¢ with only two coins (two 3¢ coins).

A system of change will be considered canonical iff for all integer values the Cashier's Algorithm will find the optimal number of coins.

Task

You task will be to take a system as a either an unordered container or sorted ordered container of integers representing coin values and output a truthy value if the system input is canonical and falsy otherwise.

Your program should work for all systems that can create any value.  (i.e. all systems will have a 1¢ coin)

This is code golf least bytes wins.

Test cases

This list is by no means exhaustive, your program should work for all valid input

```<code>1, 3, 4       -> 0
1, 5, 10, 25  -> 1
1, 6, 10, 25  -> 0
1, 2, 3       -> 1
1, 8, 17, 30  -> 0
1, 3, 8, 12   -> 0
1, 2, 8, 13   -> 0
1, 2, 4, 6, 8 -> 1
</code>```

答:
Perl, 69 bytes

Includes +2 for -pa

Give coins in descending order on STDIN. You can optionally leave out the 1 coin.

```<code>coins.pl <<< "4 3 1"
</code>```

coins.pl:

```<code>#!/usr/bin/perl -pa
$_=!map{grep$`>=$_&&($n=$G[$`-$_]+1)<($G[$`]||=$n),@F,/$/}1..2*"@F"
</code>```

Builds up the number of coins used by the cashiers algorithm in @G for amounts 1 to twice the largest coin. For each amount checks that if that amount is reduced by 1 coin value the cashiers algorithm needs at most 1 less coin. If not this is a counterexample (or there was an earlier counterexample). I could stop at the first counterexample but that takes more bytes. So the time complexity is O(max_coin * coins) and space complexity is O(max_coin)

Title: Determine if a coin system is Canonical

Body:
Perl, 69 bytes

Includes +2 for -pa

Give coins in descending order on STDIN. You can optionally leave out the 1 coin.

coins.pl <<< "4 3 1"

coins.pl:

#!/usr/bin/perl -pa
$_=!map{grep$`>=$_&&($n=$G[$`-$_]+1)<($G[$`]||=$n),@F,/$/}1..2*"@F"

Builds up the number of coins used by the cashiers algorithm in @G for amounts 1 to twice the largest coin. For each amount checks that if that amount is reduced by 1 coin value the cashiers algorithm needs at most 1 less coin. If not this is a counterexample (or there was an earlier counterexample). I could stop at the first counterexample but that takes more bytes. So the time complexity is O(max_coin * coins) and space complexity is O(max_coin)


答:
Groovy, <s>33</s> <s>37</s> 34 Bytes

Groovy's inject method is weird, but essentially is the fold method.

```<code>{a,n->(0..<n).inject(a){i,r->[i]}}
</code>```

<s>Edited to make it valid for n=0 using ternary.</s>

Edited again with ..< to make the integer range an empty set when n=0 thanks to @manatwork.

Title: Nest a string inside an array n times

Body:
Groovy, <s>33</s> <s>37</s> 34 Bytes

Groovy's inject method is weird, but essentially is the fold method.

{a,n->(0..<n).inject(a){i,r->[i]}}

<s>Edited to make it valid for n=0 using ternary.</s>

Edited again with ..< to make the integer range an empty set when n=0 thanks to @manatwork.


问:
Tips for golfing in 05AB1E
Do you have any tips for code-golfing in 05AB1E, a golfing language created by Adnan?

Your tips should be at least somewhat specific to 05AB1E.

Please post one tip per answer.

答:
Pop or get

As in other stack-based languages, 05AB1E's functions usually pop (consume) their inputs from the stack and push their outputs onto the stack.

However, some functions get their inputs from the stack without consuming them. An example is the head function, ¬, which produces the first element from the input list. See an example program here: ¬+. This adds the first number of the input list to each number of that list.

To know which functions pop and which get, see the corresponding column in the function information file.

Title: Tips for golfing in 05AB1E


问:
Find the Infinity Words!
(Note: This is a spin-off of my previous challenge Find the Swirling Words!)

Definition of Infinity Word:

If you connect with curves all the characters of an Infinity Word on the alphabet (A-Z) you obtain the infinity symbol ∞ like in the diagrams below.

All the even connection must be down, all the odd connections must be up.

You can ignore upper/lowercase or consider/convert all to upper case or all to lower case.

The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, or symbols.

Each word must be exactly 5 characters. Words > 5 or < 5 are not valid.

If a word has double consecutive characters, the word is not valid, like "FLOOD" or "QUEEN".

All the Infinity Words start and end with the same character.

Here there are some examples:

Task:

Write a full program or function that will take a word from standard input and will output if is an Infinity Word or not. The output can be true/false, 1/0, 1/Null, etc.

Test cases:

```<code>Infinity Words:
ALPHA, EAGLE, HARSH, NINON, PINUP, RULER, THEFT, WIDOW

NOT Infinity Words:
CUBIC, ERASE, FLUFF, LABEL, MODEM, RADAR, RIVER, SWISS, TRUST,
KNEES, QUEEN, GROOVE, ONLY, CHARACTER, OFF, IT, ORTHO
</code>```

Rules:

Shortest code wins.

Optional Task:

Find, as a list, as many Infinity Words as you can in an English dictionary. You can take for example as reference the complete list of English words here.

Title: Find the Infinity Words!

Body:
PHP, 102 Bytes

for(;$i<strlen($w=$argv[1]);)$s.=($w[$i++]<=>$w[$i])+1;echo preg_match("#^(2200|0022|2002|0220)#",$s);


答:
05AB1E, <s>69</s> <s>62</s> 60 bytes

Saved 2 bytes thanks to Adnan.

```<code>3ð×…^o^)U13FNV0379730vð5y>;ï-y_+×N(Y-12%_Xè'my×NY-12%_y&XèJ,
</code>```

Try it online!

Explanation

3ð×…^o^)U stores the list ["   ","^o^"] in X for later use.

13FNV loops over the 13 stages [0 .. 12] and stores the current iteration index in Y.

0379730v loops over the rows of each stage,

where N is the row index and y is the current number of m's.

We start by adding floor(5/(y+1))-(y==0) spaces to each row with ð5y>;ï-y_+×.

We then determine if there should be a bat or 3 spaces before the m's.

If (-N-Y)%12 == 0 is true we add a bat, else 3 spaces.

This expression (N(Y-12%_Xè) will place bats in stages 0,6-12.

Then we place y m's with 'my×.

Now we determine if there should be a bat or 3 spaces after the m's.

The code NY-12%_y&Xè will place a bat if ((N-Y)%12 == 0) and y!=0 is true, else 3 spaces.

This will place the bats on stages 1-5.

Finally we join the whole row into a string and print with a newline: J,.

Title: Make an ASCII bat fly around an ASCII moon

Body:
Background

Here is a Halloween related challenge.

As you may have seen from my last challenge I quite like what I term as ascii art animations, that is not just draw a pattern but draw a pattern that progresses. This idea came to me after I was asked a couple of years ago to liven up a (rather dull) presentation by making random ascii bats fly across the screen on Halloween. Needless to say I duly obliged (I was being paid for it) but it made me think that there is more to life than random bats. Inspired by this I would like to propose this challenge.

Challenge

Make a bat fly around the moon.

Here is a bat:

```<code>^o^
</code>```

Here is the moon:

```<code>     mmm
   mmmmmmm
  mmmmmmmmm
   mmmmmmm
     mmm
</code>```

You must show every stage of the bats flight (see output).

Input

None

Output

```<code>      ^o^
      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

      mmm^o^
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

      mmm
    mmmmmmm^o^
   mmmmmmmmm
    mmmmmmm
      mmm

      mmm
    mmmmmmm
   mmmmmmmmm^o^
    mmmmmmm
      mmm

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm^o^
      mmm

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm^o^

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm
      ^o^

      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
   ^o^mmm

      mmm
    mmmmmmm
   mmmmmmmmm
 ^o^mmmmmmm
      mmm

      mmm
    mmmmmmm
^o^mmmmmmmmm
    mmmmmmm
      mmm

      mmm
 ^o^mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

   ^o^mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm

      ^o^
      mmm
    mmmmmmm
   mmmmmmmmm
    mmmmmmm
      mmm
</code>```

Rules

No reading from external files or websites

You may submit a full program or a function

Extra spaces and/or newlines are fine by me

Standard loopholes banned as usual

The bat must finish back at the top of the moon

Please feel free to clear the screen between frames if you wish however this is not a requirement. Output as shown above is fine

As this is code golf, the winner will be the answer with the lowest byte count although any answer is welcome

Sample

Reference implementation in totally ungolfed Python 2 (620 bytes but just to prove that it can be done. May golf it later).

```<code>b='^o^'
m=['                     ',
'         mmm         ',
'       mmmmmmm       ',
'      mmmmmmmmm      ',
'       mmmmmmm       ',
'         mmm         ',
'                     ']
p=[(9,12),(12,15),(14,17),(15,18),(14,17),(12,15),(9,12),(6,9),(4,7),(3,6),(4,7),(6,9),(9,12)]
d=0
for z in range(7):
    x=map(str,m[z])
    c="".join(x[:p[z][0]]) + b + "".join(x[p[z][1]:])+"\n"
    print "\n".join(m[:z]) + "\n" + c+"\n".join(m[z+1:])
for z in range(6)[::-1]:
    x=map(str,m[z])
    c="".join(x[:p[z+6][0]]) + b + "".join(x[p[z+6][1]:])+"\n"
    print "\n".join(m[:z]) + "\n" + c+"\n".join(m[z+1:])
</code>```

Result

Although @Jonathan obviously wins on byte count with Jelly, I am going to mark the Brainfuck answer from @Oyarsa as the accepted answer purely because I think that anyone who can actually do something like this in such a crazy language deserves +15 rep no matter how many bytes it takes. This is not because I have any problem with golfing languages. See my answer to a question regarding this on meta if you have any doubts. Many thanks and respect to all who contributed in whatever language.

Body:
05AB1E, <s>69</s> <s>62</s> 60 bytes

Saved 2 bytes thanks to Adnan.

3ð×…^o^)U13FNV0379730vð5y>;ï-y_+×N(Y-12%_Xè'my×NY-12%_y&XèJ,

Try it online!

Explanation

3ð×…^o^)U stores the list ["   ","^o^"] in X for later use.

13FNV loops over the 13 stages [0 .. 12] and stores the current iteration index in Y.

0379730v loops over the rows of each stage,

where N is the row index and y is the current number of m's.

We start by adding floor(5/(y+1))-(y==0) spaces to each row with ð5y>;ï-y_+×.

We then determine if there should be a bat or 3 spaces before the m's.

If (-N-Y)%12 == 0 is true we add a bat, else 3 spaces.

This expression (N(Y-12%_Xè) will place bats in stages 0,6-12.

Then we place y m's with 'my×.

Now we determine if there should be a bat or 3 spaces after the m's.

The code NY-12%_y&Xè will place a bat if ((N-Y)%12 == 0) and y!=0 is true, else 3 spaces.

This will place the bats on stages 1-5.

Finally we join the whole row into a string and print with a newline: J,.


问:
Letter-replacement challenge
The idea is simple. You've to create a "visualised" letter-replacement, by providing 3 strings (input can be comma separated, separate inputs, or as an array). The first segment is the word you want to correct, and the second segment is the letters you want to replace, and the third segment is the replacement for the letters in segment 2.

For example:

```<code>|    | Input                       | Starting Word | Output      |
|----|-----------------------------|---------------|-------------|
| #1 | Hello world -wo -ld +Ea +th | Hello world   | Hello Earth |
| #2 | Hello World -wo -ld +Ea +th | Hello World   | Hello Worth |
| #3 | Hello -llo +y               | Hello         | Hey         |
| #4 | Red -R -d +Gr +en           | Red           | Green       |
| #5 | mississippi -is -i +lz +p   | mississippi   | mlzslzspppp |
| #6 | Football -o -a +a +i        | Football      | Fiitbill    |
| #7 | mississippi -is -i +iz +p   | mississippi   | mpzspzspppp |
</code>```

Explanation

The replacements are to be done step-by-step with their respective pair. Here's an illustration with an input of mississippi -is -i +iz +p to give the output mpzspzsppp (see example #7 above)

```<code>| Step  | Input                         | Output        |
|------ |---------------------------    |-------------  |
| #1    | mississippi -is -i +iz +p     |               |
| #2    | mississippi -is +iz           | mizsizsippi   |
| #3    | mizsizsippi -i +p             | mpzspzspppp   |
</code>```

Rules

Inputs are always in this order <starting_string> <list_of_letters_to_replace> <replacement_letters>.

Letters to replace and replacement groups will never be mixed (ie: there will never be -a +i -e +o).

Letters to replace are always prefixed with - and replacement letters are always prefixed with +. (The prefix is mandatory)

There may be more than one set of letters to replace, so you'd need to look at the prefix.

Assume the amount of letter groups to replace and the amount of replacement letter groups are always equal (ie: there will never be -a -e +i)

Replacements are case-sensitive (see example #1 and #2).

Replacements are done in the order they were given in the input.

Letter replacements can be replaced with other replacements. See example #6.

The first segment (starting word) will never include - or + characters.

This is code-golf so shortest bytes win.

Leaderboards

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Convex, 19 bytes

```<code>¶:äz{S*"-+"-ä~@\ò}/
</code>```

Try it online!

Title: Letter-replacement challenge

Body:
Convex, 19 bytes

¶:äz{S*"-+"-ä~@\ò}/

Try it online!


问:
Tips for golfing in C
What general tips do you have for golfing in C? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C (e.g. "remove comments" is not an answer). Please post one tip per answer. Also, please include if your tip applies to C89 and/or C99 and if it only works on certain compilers.</p>

答:
Missing includes and return values

As noted in the very first answer, some compilers (notably, GCC anc clang) let you get away with omitting #includes for standard library functions.

While that usually goes well, it might cause problems in some cases, since the implicit declarations of standard library functions inside the source code will cause the compiler to treat return values as ints. For example, the code

```<code>char*p=getenv("PATH");
</code>```

wont work as expected on a 64-bit platform since getenv returns a 64-bit memory address which doesn't fit into an int.

In this case, there are at least three ways to use getenv without errors.

Include the header file as follows.

```<code>#include<stdlib.h>
char*p=getenv("PATH");
</code>```

This is the right way™, but not very golfy; it costs 19 bytes.

Declare getenv with the pointer as follows.

```<code>char*getenv(),*p=getenv("PATH");
</code>```

This costs 10 bytes.

Finally, unless your code wouldn't work on 32-bit platforms, compile your code on one of those or with the -m32 flag (gcc). This costs 0 bytes.

Title: Tips for golfing in C

Body:
Missing includes and return values

As noted in the very first answer, some compilers (notably, GCC anc clang) let you get away with omitting #includes for standard library functions.

While that usually goes well, it might cause problems in some cases, since the implicit declarations of standard library functions inside the source code will cause the compiler to treat return values as ints. For example, the code

char*p=getenv("PATH");

wont work as expected on a 64-bit platform since getenv returns a 64-bit memory address which doesn't fit into an int.

In this case, there are at least three ways to use getenv without errors.

Include the header file as follows.

#include<stdlib.h>
char*p=getenv("PATH");

This is the right way™, but not very golfy; it costs 19 bytes.

Declare getenv with the pointer as follows.

char*getenv(),*p=getenv("PATH");

This costs 10 bytes.

Finally, unless your code wouldn't work on 32-bit platforms, compile your code on one of those or with the -m32 flag (gcc). This costs 0 bytes.


答:
PHP, 106 bytes

```<code>for($s=($v=$argv)[$i=1];$i++<$n=$argc/2;)$s=str_replace(substr($v[$i],1),substr($v[$n+$i-1],1),$s);echo$s;
</code>```

straight forward approach. Run with php -r ' <arguments>.

Title: Letter-replacement challenge

Body:
The idea is simple. You've to create a "visualised" letter-replacement, by providing 3 strings (input can be comma separated, separate inputs, or as an array). The first segment is the word you want to correct, and the second segment is the letters you want to replace, and the third segment is the replacement for the letters in segment 2.

For example:

```<code>|    | Input                       | Starting Word | Output      |
|----|-----------------------------|---------------|-------------|
| #1 | Hello world -wo -ld +Ea +th | Hello world   | Hello Earth |
| #2 | Hello World -wo -ld +Ea +th | Hello World   | Hello Worth |
| #3 | Hello -llo +y               | Hello         | Hey         |
| #4 | Red -R -d +Gr +en           | Red           | Green       |
| #5 | mississippi -is -i +lz +p   | mississippi   | mlzslzspppp |
| #6 | Football -o -a +a +i        | Football      | Fiitbill    |
| #7 | mississippi -is -i +iz +p   | mississippi   | mpzspzspppp |
</code>```

Explanation

The replacements are to be done step-by-step with their respective pair. Here's an illustration with an input of mississippi -is -i +iz +p to give the output mpzspzsppp (see example #7 above)

```<code>| Step  | Input                         | Output        |
|------ |---------------------------    |-------------  |
| #1    | mississippi -is -i +iz +p     |               |
| #2    | mississippi -is +iz           | mizsizsippi   |
| #3    | mizsizsippi -i +p             | mpzspzspppp   |
</code>```

Rules

Inputs are always in this order <starting_string> <list_of_letters_to_replace> <replacement_letters>.

Letters to replace and replacement groups will never be mixed (ie: there will never be -a +i -e +o).

Letters to replace are always prefixed with - and replacement letters are always prefixed with +. (The prefix is mandatory)

There may be more than one set of letters to replace, so you'd need to look at the prefix.

Assume the amount of letter groups to replace and the amount of replacement letter groups are always equal (ie: there will never be -a -e +i)

Replacements are case-sensitive (see example #1 and #2).

Replacements are done in the order they were given in the input.

Letter replacements can be replaced with other replacements. See example #6.

The first segment (starting word) will never include - or + characters.

This is code-golf so shortest bytes win.

Leaderboards

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
PHP, 106 bytes

for($s=($v=$argv)[$i=1];$i++<$n=$argc/2;)$s=str_replace(substr($v[$i],1),substr($v[$n+$i-1],1),$s);echo$s;

straight forward approach. Run with php -r '<code> <arguments>.


问:
Vertically collapse text
Say I have text like this (each word on one line, with no spaces)

```<code>Programming
Puzzles
&
Code
Golf
</code>```

That makes no sense! It totally defies the laws of physics.

Your challenge is to remedy this impossible situation and collapse the text like so:

```<code>P
Prog
&uzz
Coderam
Golflesming
</code>```

So that there is no empty space underneath any character but the characters retain their vertical order.

The goal is to satisfy the requirements but use the fewest bytes of source code possible.

答:
Jelly, 6 bytes (non-competing)

```<code>ỴṚZZṚY
</code>```

Try it online!

How it works

The idea in the same as in my Pyth answer.

```<code>ỴṚZZṚY  Main link. Argument: s (string)

Ỵ       Split at linefeeds.
 Ṛ      Reverse the order of the lines.
  ZZ    Zip/transpose twice.
    Ṛ   Reverse the order of the lines.
     Y  Join, separating by linefeeds.
</code>```

Title: Vertically collapse text

Body:
Jelly, 6 bytes (non-competing)

ỴṚZZṚY

Try it online!

How it works

The idea in the same as in my Pyth answer.

ỴṚZZṚY  Main link. Argument: s (string)

Ỵ       Split at linefeeds.
 Ṛ      Reverse the order of the lines.
  ZZ    Zip/transpose twice.
    Ṛ   Reverse the order of the lines.
     Y  Join, separating by linefeeds.


问:
Play a game of Yahtzee
In the game Yahtzee, players take turns rolling 5 6-sided dice up to three times per turn, possibly saving dice between rolls, and then selecting a category they wish to use for their roll. This continues until there are no more categories (which happens after 13 turns). Then, players' scores are tallied, and the player with the highest score wins.

The categories are as follows ("sum of dice" means adding up the number of pips on the specified dice):

Upper Section

Aces: sum of the dice showing 1 pip

Twos: sum of the dice showing 2 pips

Threes: sum of the dice showing 3 pips

Fours: sum of the dice showing 4 pips

Fives: sum of the dice showing 5 pips

Sixes: sum of the dice showing 6 pips

Lower Section

Three of a Kind: 3 dice with same value, score is sum of all dice

Four of a Kind: 4 dice with same value, score is sum of all dice

Full House: 3 dice with one value and 2 with another, score is 25

Small Straight: 4 sequential dice, score is 30

Large Straight: 5 sequential dice, score is 40

Yahtzee: all 5 dice with same value, score is 50

Chance: any combination of dice, score is sum of all dice

There are a few rules about the category choices:

If a player chooses a category that does not match their roll, they receive a score of 0 for that category.

If a player earns a score of at least 63 in the upper section, they receive 35 bonus points.

If a player has rolled a Yahtzee but the Yahtzee category is already taken (by another Yahtzee - filling in 0 for a miss doesn't count), they receive a bonus of 100 points. This bonus is awarded for every Yahtzee after the first.

Additionally, the player must still choose to fill in a category. They must choose the upper section category corresponding to their roll (e.g. a roll of 5 6's must be placed in the Sixes category). If the corresponding upper section category has already been used, the Yahtzee may be used for a lower section category (in this case, choosing Full House, Small Straight, or Large Straight awards the normal amount of points rather than 0). If all of the lower section categories are taken, then the Yahtzee may be applied to an unused upper section category, with a score of 0.

The Challenge

In this challenge, the competitors will play 1000 games of Yahtzee. At the end of each game, the submission(s) that scored the highest will receive 1 point. After all of the games are finished, the submission with the most points will win. If there is a tie, additional games will be played with only the tied submissions until the tie is broken.

Controller

The complete controller code can be found on this GitHub repository. Here are the public interfaces with which players will be interacting:

public interface ScorecardInterface {

    // returns an array of unused categories
    Category[] getFreeCategories();

    // returns the current total score
    int getScore();

    // returns the current Yahtzee bonus
    int getYahtzeeBonus();

    // returns the current Upper Section bonus
    int getUpperBonus();

    // returns the current Upper Section total
    int getUpperScore();

}
```

<pre class="lang-java prettyprint-override"><code>public interface ControllerInterface {

    // returns the player's scorecard (cloned copy, so don't try any funny business)
    ScorecardInterface getScoreCard(Player p);

    // returns the current scores for all players, in no particular order
    // this allows players to compare themselves with the competition,
    //  without allowing them to know exactly who has what score (besides their own score),
    //  which (hopefully) eliminates any avenues for collusion or sabotage
    int[] getScores();

}
</code>```

public enum Category {
    ACES,
    TWOS,
    THREES,
    FOURS,
    FIVES,
    SIXES,
    THREE_OF_A_KIND,
    FOUR_OF_A_KIND,
    FULL_HOUSE,
    SMALL_STRAIGHT,
    LARGE_STRAIGHT,
    YAHTZEE,
    CHANCE;

    // determines if the category is part of the upper section
    public boolean isUpper() {
        // implementation
    }

    // determines if the category is part of the lower section
    public boolean isLower() {
        // implementation
    }

    // determines if a given set of dice fits for the category
    public boolean matches(int[] dice) {
        // implementation
    }

    // calculates the score of a set of dice for the category
    public int getScore(int[] dice) {
        // implementation
    }

    // returns all categories that fit the given dice
    public static Category[] getMatchingCategories(int[] dice) {
        // implementation
    }
}
```

<pre class="lang-java prettyprint-override"><code>public class TurnChoice {

    // save the dice with the specified indexes (0-4 inclusive)
    public TurnChoice(int[] diceIndexes) {
        // implementation
    }

    // use the current dice for specified category
    public TurnChoice(Category categoryChosen) {
        // implementation
    }

}

public abstract class Player {

    protected ControllerInterface game;

    public Player(ControllerInterface game) {
        this.game = game;
    }

    public String getName() {
        return this.getClass().getSimpleName();
    }

    // to be implemented by players
    // dice is the current roll (an array of 5 integers in 1-6 inclusive)
    // stage is the current roll stage in the turn (0-2 inclusive)
    public abstract TurnChoice turn(int[] dice, int stage);

}
</code>```

Additionally, there are some utility methods in Util.java. They are mainly there to simplify the controller code, but they can be used by players if they desire.

Rules

Players are not allowed to interact in any way except using the Scorecard.getScores method to see the current scores of all players. This includes colluding with other players or sabotaging other players via manipulating parts of the system that are not part of the public interface.

If a player makes an illegal move, they will not be allowed to compete in the tournament. Any issues that cause illegal moves must be resolved prior to the running of the tournament.

If additional submissions are made after the tournament is run, a new tournament will be run with the new submission(s), and the winning submission will be updated accordingly. I make no guarantee of promptness in running the new tournament, however.

Submissions may not exploit any bugs in the controller code that cause it to deviate from the actual game rules. Point out bugs to me (in a comment and/or in a GitHub issue), and I'll fix them.

Use of Java's reflection tools is forbidden.

Any language which runs on the JVM, or can be compiled to Java or JVM bytecode (such as Scala or Jython) can be used, so long as you supply any additional code needed to interface it with Java.

Final Comments

If there is any utility method you would like me to add to the controller, simply ask in the comments and/or make an issue on GitHub, and I'll add it, assuming it doesn't allow for rule breaking or expose information to which players are not privy. If you want to write it yourself and create a pull request on GitHub, even better!

答:
DummyPlayer

package mego.yahtzee;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class DummyPlayer extends Player {

    public DummyPlayer(ControllerInterface game) {
        super(game);
    }

    @Override
    public TurnChoice turn(int[] dice, int stage) {
        Category[] choices = game.getScoreCard(this).getFreeCategories();
        Category choice = choices[new Random().nextInt(choices.length)];
        if(IntStream.of(dice).allMatch(die -> die == dice[0])) {
            if(Stream.of(choices).filter(c -> c == Category.YAHTZEE).count() > 0) {
                choice = Category.YAHTZEE;
            } else if(Stream.of(choices).filter(c -> c == Util.intToUpperCategory(dice[0])).count() > 0) {
                choice = Util.intToUpperCategory(dice[0]);
            } else {
                choices = Stream.of(game.getScoreCard(this).getFreeCategories()).filter(c -> c.isLower()).toArray(Category[]::new);
                if(choices.length > 0) {
                    choice = choices[new Random().nextInt(choices.length)];
                } else {
                    choices = game.getScoreCard(this).getFreeCategories();
                    choice = choices[new Random().nextInt(choices.length)];
                }
            }
        }
        return new TurnChoice(choice);
    }

}
```

This player is here to serve as a basic outline for how to use the tools present in the Yahtzee controller. It chooses Yahtzee whenever possible, and makes random choices otherwise, while complying with the strict joker rules.

Title: Play a game of Yahtzee

Body:
DummyPlayer

package mego.yahtzee;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class DummyPlayer extends Player {

    public DummyPlayer(ControllerInterface game) {
        super(game);
    }

    @Override
    public TurnChoice turn(int[] dice, int stage) {
        Category[] choices = game.getScoreCard(this).getFreeCategories();
        Category choice = choices[new Random().nextInt(choices.length)];
        if(IntStream.of(dice).allMatch(die -> die == dice[0])) {
            if(Stream.of(choices).filter(c -> c == Category.YAHTZEE).count() > 0) {
                choice = Category.YAHTZEE;
            } else if(Stream.of(choices).filter(c -> c == Util.intToUpperCategory(dice[0])).count() > 0) {
                choice = Util.intToUpperCategory(dice[0]);
            } else {
                choices = Stream.of(game.getScoreCard(this).getFreeCategories()).filter(c -> c.isLower()).toArray(Category[]::new);
                if(choices.length > 0) {
                    choice = choices[new Random().nextInt(choices.length)];
                } else {
                    choices = game.getScoreCard(this).getFreeCategories();
                    choice = choices[new Random().nextInt(choices.length)];
                }
            }
        }
        return new TurnChoice(choice);
    }

}

This player is here to serve as a basic outline for how to use the tools present in the Yahtzee controller. It chooses Yahtzee whenever possible, and makes random choices otherwise, while complying with the strict joker rules.


答:
Ruby, <s>164</s> 156 bytes

```<code>puts Zlib.inflate Base64.decode64 "eNqlkrUVAAEMQvtMcZP9DfLYvzo3qhNSxQ2GVRC1ad29ar1JXaoHbul16Yig+p6BCKqtFBFU+1IE1famoHrX/jZBvN8e8f5tiE94Ib4SBREwNKH5BNJy2QM="
</code>```

Very simple program. Can be worked on more. Please leave tips in the comments.

Body:
Ruby, <s>164</s> 156 bytes

puts Zlib.inflate Base64.decode64 "eNqlkrUVAAEMQvtMcZP9DfLYvzo3qhNSxQ2GVRC1ad29ar1JXaoHbul16Yig+p6BCKqtFBFU+1IE1famoHrX/jZBvN8e8f5tiE94Ib4SBREwNKH5BNJy2QM="

Very simple program. Can be worked on more. Please leave tips in the comments.


答:
Jelly, <s>76 69</s> 58 bytes

```<code>⁾ mṁ11ż“æ¤¿¬®µ‘ŒḄ¤Œṙs⁴Y
_4¢ḣ;“^o^”;¢ṫ⁸¤
“½œ0CSbp\I7'ð½‘Ç€Y
</code>```

TryItOnline

How?

```<code>⁾ mṁ11ż“æ¤¿¬®µ‘ŒḄ¤Œṙs⁴Y - Link 1, make a moon (niladic)
⁾ m                     - literal " m"
   ṁ                    - reshape like
    11                  - 11 (interpreted as range(11)) -> " m m m m m "
                 ¤      - nilad followed by links as a nilad
       “æ¤¿¬®µ‘         - code page indexes [22,3,11,7,8,9]
               ŒḄ       - bounce -> [22,3,11,7,8,9,8,7,11,3,22]
      ż                 - zip -> [[22,' '],[3,'m'],[11,' '],...]
                  Œṙ    - run length decode -> "                      mmm           mmmmmmm        mmmmmmmmm        mmmmmmm           mmm                      "
                    s   - split into chunks of length
                     ⁴  - l6
                      Y - join with line feeds

_4¢ḣ;“^o^”;¢ṫ⁸¤ - Link 2, a moon with a bat placed: endIndex
_4              - subtract 4 (startIndex)
  ¢              - call last link (1) as a nilad
   ḣ            - ḣead to startIndex
    ;           - concatenate
     “^o^”      - literal "^o^"
          ;     - concatenate
              ¤ - nilad followed by links as a nilad
           ¢    - call last link (1) as a nilad
            ṫ⁸  - tail from endIndex

“½œ0CSbp\I7'ð½‘Ç€Y - Main link (niladic)
“½œ0CSbp\I7'ð½‘    - code page indexes [10,30,48,67,83,98,112,92,73,55,39,24,10]
                   -    indices to the right of each bat in a constructed moon
               Ç€  - call last link (2) as a monad for each
                 Y - join on line feeds
</code>```

Body:
Jelly, <s>76 69</s> 58 bytes

⁾ mṁ11ż“æ¤¿¬®µ‘ŒḄ¤Œṙs⁴Y
_4¢ḣ;“^o^”;¢ṫ⁸¤
“½œ0CSbp\I7'ð½‘Ç€Y

TryItOnline

How?

⁾ mṁ11ż“æ¤¿¬®µ‘ŒḄ¤Œṙs⁴Y - Link 1, make a moon (niladic)
⁾ m                     - literal " m"
   ṁ                    - reshape like
    11                  - 11 (interpreted as range(11)) -> " m m m m m "
                 ¤      - nilad followed by links as a nilad
       “æ¤¿¬®µ‘         - code page indexes [22,3,11,7,8,9]
               ŒḄ       - bounce -> [22,3,11,7,8,9,8,7,11,3,22]
      ż                 - zip -> [[22,' '],[3,'m'],[11,' '],...]
                  Œṙ    - run length decode -> "                      mmm           mmmmmmm        mmmmmmmmm        mmmmmmm           mmm                      "
                    s   - split into chunks of length
                     ⁴  - l6
                      Y - join with line feeds

_4¢ḣ;“^o^”;¢ṫ⁸¤ - Link 2, a moon with a bat placed: endIndex
_4              - subtract 4 (startIndex)
  ¢              - call last link (1) as a nilad
   ḣ            - ḣead to startIndex
    ;           - concatenate
     “^o^”      - literal "^o^"
          ;     - concatenate
              ¤ - nilad followed by links as a nilad
           ¢    - call last link (1) as a nilad
            ṫ⁸  - tail from endIndex

“½œ0CSbp\I7'ð½‘Ç€Y - Main link (niladic)
“½œ0CSbp\I7'ð½‘    - code page indexes [10,30,48,67,83,98,112,92,73,55,39,24,10]
                   -    indices to the right of each bat in a constructed moon
               Ç€  - call last link (2) as a monad for each
                 Y - join on line feeds


问:
Golf you a quine for great good!
Using your language of choice, golf a quine.

A quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output.

No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either.

No error quines -- there is already a separate challenge for error quines.

Points for:

Smallest code (in bytes)

Most obfuscated/obscure solution

Using esoteric/obscure languages

Successfully using languages that are difficult to golf in

The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat:

var QUESTION_ID=69;
var OVERRIDE_USER=98;

var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}
function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&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(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.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(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}
getAnswers();var SCORE_REG=(function(){var headerTag=String.raw `h\d`
var score=String.raw `\-?\d+\.?\d*`
var normalText=String.raw `[^\n<>]*`
var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
var noDigitText=String.raw `[^\n\d<>]*`
var htmlTag=String.raw `<[^\n<>]+>`
return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}
function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))
body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)
valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,})});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)
lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+a.language+'').text().toLowerCase();languages[lang]=languages[lang]||{lang:a.language,user:a.user,size:a.size,link:a.link,uniq:lang}});var langs=[];for(var lang in languages)
if(languages.hasOwnProperty(lang))
langs.push(languages[lang]);langs.sort(function(a,b){if(a.uniq>b.uniq)return 1;if(a.uniq<b.uniq)return-1;return 0});for(var i=0;i<langs.length;++i)
{var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

  <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654">

Winners by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

 ```

答:
Bash, <s>35</s> <s>28</s> 20 bytes

```<code>trap -- 'trap' EXIT
</code>```

@Dennis pointed out that even the -p flag is not necessary, and trap will print the trap strings unqualified, which helped save another 8 bytes, and brought about another quine:

Zsh, 18 bytes

```<code>trap -- trap EXIT
</code>```

Zsh trap does not print the single quotes, which makes it incompatible with the bash version, but also allows you to save another 2 bytes for the zsh-only version. Again, though, bash does not show this behavior and trap does not print anything.

Bash, 19 bytes

Another, just barely shorter, and much less interesting bash quine:

```<code>echo $BASH_COMMAND
</code>```

Thankfully the lack of single quotes mean that in zsh, trap is still shorter, which is important because the $BASH_COMMAND variable does not exist. Additionally, I'd be tempted to count this as 'reading the source' but that might be because I like the trap one so much.

Bash 28 byte submission

```<code>trap -- 'trap -p EXIT' EXIT
</code>```

Just realized that the echo statement could be cut out entirely, trap -p simply prints the trap statement in this format (saved another 7 bytes).

Compatibility: This must be in a script file, trap does not work as expected on the command line, and its bash-only: bourne shell/ash/dash does not support the -p flag to trap (obviously instrumental to the quine).

Original 35 byte submission:

```<code>trap -- 'echo `trap -p EXIT`' EXIT
</code>```

A much farther golf of @ormaaj's trap-based solution. Shaves off 1 byte by switching to backticks, 2 more because the quotes around the echo body are not necessary, and 9 bytes by switching to echo. The real magic though, is switching from a DEBUG trap to EXIT. This saves 2 bytes just because EXIT is shorter, and 3 more because you do not need to call : or print it (and it drastically simplified the escaping needed for echo).

I'm not 100% sure whether this counts as 34 or 35 bytes, as echo prints a trailing newline and I'm not sure whether its a true quine if I don't include a trailing newline in the source. I called it 35 bytes to be more safe/truthful, but I'd love to know what a real ruling on this is.

Link to @ormaaj's original solution. (If I had enough reputation to post these golfs as a comment on the original post, I would have. My apologies if any of this breaks convention.)

ContentLicense: CC BY-SA 4.0

Title: Golf you a quine for great good!

Body:
Bash, <s>35</s> <s>28</s> 20 bytes

trap -- 'trap' EXIT

@Dennis pointed out that even the -p flag is not necessary, and trap will print the trap strings unqualified, which helped save another 8 bytes, and brought about another quine:

Zsh, 18 bytes

trap -- trap EXIT

Zsh trap does not print the single quotes, which makes it incompatible with the bash version, but also allows you to save another 2 bytes for the zsh-only version. Again, though, bash does not show this behavior and trap does not print anything.

Bash, 19 bytes

Another, just barely shorter, and much less interesting bash quine:

echo $BASH_COMMAND

Thankfully the lack of single quotes mean that in zsh, trap is still shorter, which is important because the $BASH_COMMAND variable does not exist. Additionally, I'd be tempted to count this as 'reading the source' but that might be because I like the trap one so much.

Bash 28 byte submission

trap -- 'trap -p EXIT' EXIT

Just realized that the echo statement could be cut out entirely, trap -p simply prints the trap statement in this format (saved another 7 bytes).

Compatibility: This must be in a script file, trap does not work as expected on the command line, and its bash-only: bourne shell/ash/dash does not support the -p flag to trap (obviously instrumental to the quine).

Original 35 byte submission:

trap -- 'echo `trap -p EXIT`' EXIT

A much farther golf of @ormaaj's trap-based solution. Shaves off 1 byte by switching to backticks, 2 more because the quotes around the echo body are not necessary, and 9 bytes by switching to echo. The real magic though, is switching from a DEBUG trap to EXIT. This saves 2 bytes just because EXIT is shorter, and 3 more because you do not need to call : or print it (and it drastically simplified the escaping needed for echo).

I'm not 100% sure whether this counts as 34 or 35 bytes, as echo prints a trailing newline and I'm not sure whether its a true quine if I don't include a trailing newline in the source. I called it 35 bytes to be more safe/truthful, but I'd love to know what a real ruling on this is.

Link to @ormaaj's original solution. (If I had enough reputation to post these golfs as a comment on the original post, I would have. My apologies if any of this breaks convention.)


答:
PHP, 321 bytes

```<code>$i=imagecreatefromjpeg($f="96512.jpg");list($w,$h)=getimagesize($f);for($y=$h;$y--;)for($x=$w;$x--;$s=$n=0){for($a=-2;$a++<1;)for($b=-2;$b++<1;)if(false!==($d=imagecolorat($i,$x+$a,$y+$b))){$n++;$s+=imagecolorsforindex($i,$d)[red];}imagesetpixel($i,$x,$y,imagecolorallocate($i,$r=ceil($s/$n),$r,$r));}imagejpeg($i,"b$f");
</code>```

does the blurring from bottom to top, from right to left.

-2 bytes for a gif or png; could save even more with a shorter file name

and -6 if rounding down was allowed. pity that image processing functions have so long names.

but I´m fine. pretty byte count.

Title: Image Smoothie!

Body:
Input into your program a black and white image. (png, jpg, etc)

Convert the image to a 2D matrix of pixels, where each index is the grayscale value of the image.

Take each index of the matrix and average the 8 pixels around it. Then replace that index with the average.

For example if you had:

```<code>120 80  60
20  10  30
40  100 05
</code>```

If you were finding the average for 10, the result would be 56.875, which is (120,80,60,30,05,100,40,20)/8.

Round to up to the nearest integer (57) and replace the index. The result of this iteration would be

```<code>120 80  60
20  57  30
40  100 05
</code>```

If you are finding the average for a pixel on an edge then only take values that are valid. In the example above if you were finding the average for 20 You would only consider 120, 80, 57, 100, and 40 which is 79.4 rounded to 80.

You may start at any index of the graph but it must be in order. For example you could do

```<code>[0][0], [0][1], ... [0][n], then [1][0], [1][1],... [1][n]
</code>```

Once the averaging is complete, convert the matrix back into a new image.

Display the new image as the output of the program. (Or save it and add it in your solution). The result of your code should be a blurry looking image but much smoother than the original.

Example Input

Example Output

Example Input two

Example Output two

Please provide your code and start and end image results.

Q/A

1Q. If one of the 8 neighbors has already been changed, should the average be calculated based on this new value, or based on the original values? That is, does the order of calculation affect the end result?

1A Yes, You should change each index with new values from any potential indices done before. That is why you need to go left-right, top-bottom etc. In order.

2Q. Could you clarify what is meant by "must be in order"? Does this mean that only raster order/reading order is acceptable? Or does it mean that the order must be the same each time the code is run? Would a spiral be valid? Or a shuffled order that is always the same?

2A. You should go left to right, right to left, top to bottom, or bottom to top. I.E. Do all of the 0th row, do all of the 1st row,... do all of the nth row

Body:
PHP, 321 bytes

$i=imagecreatefromjpeg($f="96512.jpg");list($w,$h)=getimagesize($f);for($y=$h;$y--;)for($x=$w;$x--;$s=$n=0){for($a=-2;$a++<1;)for($b=-2;$b++<1;)if(false!==($d=imagecolorat($i,$x+$a,$y+$b))){$n++;$s+=imagecolorsforindex($i,$d)[red];}imagesetpixel($i,$x,$y,imagecolorallocate($i,$r=ceil($s/$n),$r,$r));}imagejpeg($i,"b$f");

does the blurring from bottom to top, from right to left.

-2 bytes for a gif or png; could save even more with a shorter file name

and -6 if rounding down was allowed. pity that image processing functions have so long names.

but I´m fine. pretty byte count.


答:
Python 2, <s>299</s> <s>300</s> <s>290</s> 270 bytes

Golfed down to 270 having gained a bit more golfing experience.

Reference implementation golfed down by <s>321</s> <s>320</s> 330 bytes. Not pretty or elegant. Just uses brute force string and list slicing. Was fun to get the byte count down though but I think the approach was completely wrong to start with for a serious competitor.

I don't expect this answer to be taken seriously so please no downvotes. I did say in the question that I would try to golf the reference implementation and this is exactly that. Just posted for fun.

c,e,n=' ','m','\n';f,g=c*9+e*3+c*9,c*7+e*7+c*7;h=9,12;i=12,15;j=6,9;k=13,17;l=4,7;m=c*21,f,g,c*6+e*9+c*6,g,f,c*21;p=h,i,k,(15,18),k,i,h,j,l,(3,6),l,j,h;w=0
for z in map(int,'0123456543210'):print n.join(m[:z])+n+m[z][:p[w][0]]+'^o^'+m[z][p[w][1]:]+n+n.join(m[z+1:]);w+=1
```

Try it online!

Body:
Python 2, <s>299</s> <s>300</s> <s>290</s> 270 bytes

Golfed down to 270 having gained a bit more golfing experience.

Reference implementation golfed down by <s>321</s> <s>320</s> 330 bytes. Not pretty or elegant. Just uses brute force string and list slicing. Was fun to get the byte count down though but I think the approach was completely wrong to start with for a serious competitor.

I don't expect this answer to be taken seriously so please no downvotes. I did say in the question that I would try to golf the reference implementation and this is exactly that. Just posted for fun.

c,e,n=' ','m','\n';f,g=c*9+e*3+c*9,c*7+e*7+c*7;h=9,12;i=12,15;j=6,9;k=13,17;l=4,7;m=c*21,f,g,c*6+e*9+c*6,g,f,c*21;p=h,i,k,(15,18),k,i,h,j,l,(3,6),l,j,h;w=0
for z in map(int,'0123456543210'):print n.join(m[:z])+n+m[z][:p[w][0]]+'^o^'+m[z][p[w][1]:]+n+n.join(m[z+1:]);w+=1

Try it online!


问:
How many answers does this question have?
Write a program or a function that outputs the integer number of answers this question has. Your solution should still work as more answers are added.

Languages that run in a browser may be run from the js console while on this page. Otherwise, you'd probably have to download this page. Multi-language solutions, e.g. wgeting the page and parsing it using grep is ok. Just sum up the command line and all source used.

This is code golf; shortest answer in bytes wins.

EDIT:

Let's allow at most one occourance of the url of this page to not count, either as input or in the source. No url shorteners, no data stored as get parameters etc. Quotes around url, if needed, still count. Taking the url as input is also fine. If you want to remove some part of the url, e.g. /how-many-answers..., you can, but it probably doesn't help you.

答:
CJam, 15 bytes

```<code>lg"2>"/1=A>S/0=
</code>```

Expects this page's URL as input.

How it works

```<code>l                e# Read a line (the URL) from STDIN.
 g               e# Fetch the resource the URL points to.
  "2>"/          e# Split the source at occurrences of "2>".
       1=        e# Select the second chunk, i.e., everything between the first
                 e# <h2> and the first </h2>.
         A>      e# Discard the first 10 characters (a linefeed and 9 tabs).
           S/0=  e# Split at spaces and select the first chunk.
</code>```

Body:
CJam, 15 bytes

lg"2>"/1=A>S/0=

Expects this page's URL as input.

How it works

l                e# Read a line (the URL) from STDIN.
 g               e# Fetch the resource the URL points to.
  "2>"/          e# Split the source at occurrences of "2>".
       1=        e# Select the second chunk, i.e., everything between the first
                 e# <h2> and the first </h2>.
         A>      e# Discard the first 10 characters (a linefeed and 9 tabs).
           S/0=  e# Split at spaces and select the first chunk.


答:
HTML+JS, <s>153</s> 149 bytes

n=setInterval(_=>o.innerText=`zzd
zc3e
 b7f
a9g
 l7h
zk3i
zzj`.replace(/\S/g,c=>parseInt(c,36)-n%12-10?`m`.repeat(c)||`   `:`^o^`,n++),1e3)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id=o></code>```

Edit: Saved a bunch of bytes thanks to @RickHitchcock. The boring version that just returns the 13 multiline strings in an array is <s>132</s> 131 bytes:

```<code>_=>[...Array(13)].map((_,n)=>`zza
zl3b
 k7c
j9d
 i7e
zh3f
zzg`.replace(/\S/g,c=>parseInt(c,36)-n%12-10?`m`.repeat(c)||`   `:`^o^`))
</code>```

Body:
HTML+JS, <s>153</s> 149 bytes

n=setInterval(_=>o.innerText=`zzd
zc3e
 b7f
a9g
 l7h
zk3i
zzj`.replace(/\S/g,c=>parseInt(c,36)-n%12-10?`m`.repeat(c)||`   `:`^o^`,n++),1e3)

<pre id=o>

Edit: Saved a bunch of bytes thanks to @RickHitchcock. The boring version that just returns the 13 multiline strings in an array is <s>132</s> 131 bytes:

_=>[...Array(13)].map((_,n)=>`zza
zl3b
 k7c
j9d
 i7e
zh3f
zzg`.replace(/\S/g,c=>parseInt(c,36)-n%12-10?`m`.repeat(c)||`   `:`^o^`))


答:
JavaScript (ES6), 78 bytes

```<code>([a,b,c,d,e,f])=>a==e&&!(f||/(.)\1/.test(a+b+c+d+e)||(a>b)-(b>c)+(c>d)-(d>e))
</code>```

Based on @Arnauld's incorrect code, but golfed and corrected. Works by first checking that the first character is the same as the fifth (thus guaranteeing 5 characters) and that the length of the string is no more than 5. After checking for consecutive duplicate characters, it remains to check the waviness of the string, which should have one peak and one trough two letters apart.

If the peak and the trough are the middle and first/last letters, then the first two comparisons and the last two comparisons cancel out

If the peak and the trough are the second and fourth letters, then the middle two comparisons and the outer two comparisons cancel out

Otherwise, something fails to cancel and the overall expression returns false

Edit: Alternative 78-byte solution based on @KarlNapf's answer:

```<code>([a,b,c,d,e,f],g=(a,b)=>(a<b)-(a>b))=>a==e&&!f&&g(a,b)*g(c,d)+g(b,c)*g(d,e)<-1
</code>```

Title: Find the Infinity Words!

Body:
(Note: This is a spin-off of my previous challenge Find the Swirling Words!)

Definition of Infinity Word:

If you connect with curves all the characters of an Infinity Word on the alphabet (A-Z) you obtain the infinity symbol ∞ like in the diagrams below.

All the even connection must be down, all the odd connections must be up.

You can ignore upper/lowercase or consider/convert all to upper case or all to lower case.

The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, or symbols.

Each word must be exactly 5 characters. Words > 5 or < 5 are not valid.

If a word has double consecutive characters, the word is not valid, like "FLOOD" or "QUEEN".

All the Infinity Words start and end with the same character.

Here there are some examples:

Task:

Write a full program or function that will take a word from standard input and will output if is an Infinity Word or not. The output can be true/false, 1/0, 1/Null, etc.

Test cases:

```<code>Infinity Words:
ALPHA, EAGLE, HARSH, NINON, PINUP, RULER, THEFT, WIDOW

NOT Infinity Words:
CUBIC, ERASE, FLUFF, LABEL, MODEM, RADAR, RIVER, SWISS, TRUST,
KNEES, QUEEN, GROOVE, ONLY, CHARACTER, OFF, IT, ORTHO
</code>```

Rules:

Shortest code wins.

Optional Task:

Find, as a list, as many Infinity Words as you can in an English dictionary. You can take for example as reference the complete list of English words here.

Body:
JavaScript (ES6), 78 bytes

([a,b,c,d,e,f])=>a==e&&!(f||/(.)\1/.test(a+b+c+d+e)||(a>b)-(b>c)+(c>d)-(d>e))

Based on @Arnauld's incorrect code, but golfed and corrected. Works by first checking that the first character is the same as the fifth (thus guaranteeing 5 characters) and that the length of the string is no more than 5. After checking for consecutive duplicate characters, it remains to check the waviness of the string, which should have one peak and one trough two letters apart.

If the peak and the trough are the middle and first/last letters, then the first two comparisons and the last two comparisons cancel out

If the peak and the trough are the second and fourth letters, then the middle two comparisons and the outer two comparisons cancel out

Otherwise, something fails to cancel and the overall expression returns false

Edit: Alternative 78-byte solution based on @KarlNapf's answer:

([a,b,c,d,e,f],g=(a,b)=>(a<b)-(a>b))=>a==e&&!f&&g(a,b)*g(c,d)+g(b,c)*g(d,e)<-1


答:
Python 2, <s>110</s> <s>87</s> 60 bytes

Saving 1 byte thanks to Neil

Requires input enclosed in quotes, e.g. 'KNEES'

True if it is an infinity word, False if not and it has length of 5 and prints error message if wrong length

s=input()
a,b,c,d,e=map(cmp,s,s[1:]+s[0])
print a*c+b*d|e<-1
```
<p>Inspired by xnor's answer using <code>map(cmp...</code></p>
<pre class="lang-python prettyprint-override"><code>s=input()
e=map(cmp,s,s[1:]+s[0])
print e[4]==0and e[0]*e[2]+e[1]*e[3]==-2and 5==len(s)
</code>```

previous solution:

s=input()
d=[ord(x)-ord(y)for x,y in zip(s,s[1:])]
print s[0]==s[4]and d[0]*d[2]<0and d[1]*d[3]<0and 4==len(d)
```

Using the optimized logic of Kevin Cruijssen

Title: Find the Infinity Words!

Body:
Python 2, <s>110</s> <s>87</s> 60 bytes

Saving 1 byte thanks to Neil

Requires input enclosed in quotes, e.g. 'KNEES'

True if it is an infinity word, False if not and it has length of 5 and prints error message if wrong length

s=input()
a,b,c,d,e=map(cmp,s,s[1:]+s[0])
print a*c+b*d|e<-1

Inspired by xnor's answer using map(cmp...

s=input()
e=map(cmp,s,s[1:]+s[0])
print e[4]==0and e[0]*e[2]+e[1]*e[3]==-2and 5==len(s)

previous solution:

s=input()
d=[ord(x)-ord(y)for x,y in zip(s,s[1:])]
print s[0]==s[4]and d[0]*d[2]<0and d[1]*d[3]<0and 4==len(d)

Using the optimized logic of Kevin Cruijssen


问:
Display a Connect Four game
Connect Four is a game where two players take turns to drop disks into columns of a vertically mounted grid, and attempt to connect four disks orthogonally or diagonally. When a column is chosen, the disk falls to the lowest empty position in that column, so any game may be completely specified by the size of the grid and the sequence of columns chosen. The task is to generate the configuration of the grid given this information.

Input

Width w and Height h of the grid, both positive integers.

Sequence of columns c1, c2, ..., cn chosen by the players, in any reasonable format (list, array etc.); either 0-based (0 to w-1) or 1-based (1 to w) indexing can be used.

It may be assumed that all of the column numbers lie within the grid (so the sequence won't contain -3 or w+50) and that any column number appears at most h times in the sequence (so a column can't be chosen once it is full).

Note that the sequence of columns may not constitute a complete game, nor a legal game. For instance, the players could opt to continue playing even after a player has connected four disks.

Output

Any reasonable representation of the resulting state of each position in the grid, either "occupied by Player 1", "occupied by Player 2", or "empty". Player 1 always moves first.

For example, a string, array, tuple etc. with each position containing one of three symbols (ASCII character, number etc.) representing the state of that position in the grid. The grid may be transposed.

For list/tuple/array outputs, the separator cannot be one of the three representative symbols. For string outputs, trailing spaces at the end of each line are permitted, provided a space is not one of the three representative symbols. Trailing newlines at the very end are permitted.

Test cases

Here, string output is used, with X, O, . denoting "occupied by Player 1", "occupied by Player 2", "empty".

```<code>IN: Width 1 Height 1 Sequence (empty sequence)
OUT:
.

IN: Width 7 Height 6 Sequence 4 4 5 5 6 7 3 [1-based]
                              3 3 4 4 5 6 2 [0-based]
OUT:
.......
.......
.......
.......
...OO..
..XXXXO

IN: Width 5 Height 5 Sequence 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 [1-based]
                              0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 [0-based]
OUT:
XOXOX
OXOXO
XOXOX
OXOXO
xOXOX

IN: Width 4 Height 4 Sequence 3 3 2 4 3 2 4 2 2 3 4 4 1 1 1 1 [1-based]
                              2 2 1 3 2 1 3 1 1 2 3 3 0 0 0 0 [0-based]
OUT:
OXOO
XOXX
OOOX
XXXO

IN: Width 10 Height 10 Sequence 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 10  [1-based]
                                0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0  9 0  9  [0-based]
OUT:
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X........O
XOOOOOOOOO
</code>```

Shortest code in bytes wins.

答:
Pyth, 19 bytes

```<code>m.[2vz%R2fq@QTd_UQE
</code>```

Try it online.

Takes input as c,o,l,s\nheight\nwidth, 0-indexed. Outputs a list of columns (transposed), using 012 for player 1, player 2, empty respectively.

Title: Display a Connect Four game

Body:
Pyth, 19 bytes

m.[2vz%R2fq@QTd_UQE

Try it online.

Takes input as c,o,l,s\nheight\nwidth, 0-indexed. Outputs a list of columns (transposed), using 012 for player 1, player 2, empty respectively.


答:
Python 2, 71 bytes

lambda s:map(cmp,s,s[1:]+s[0])in[[m,n,-m,-n,0]for m in-1,1for n in-1,1]
```

<p>Takes the string <code>s</code> with characters <code>abcde</code>, rotates it to <code>bcdea</code>, and does an elementwise comparison of corresponding characters.</p>

<pre class="lang-python prettyprint-override"><code>a  b   cmp(a,b)
b  c   cmp(b,c)
c  d   cmp(c,d)
d  e   cmp(d,e)
e  a   cmp(e,a)
</code>```

The result is a list of -1, 0, 1. Then, checks if the result is one of the valid sequences of up and downs:

[-1, -1, 1, 1, 0]
[-1, 1, 1, -1, 0]
[1, -1, -1, 1, 0]
[1, 1, -1, -1, 0]
```

<p>as generated from the template <code>[m,n,-m,-n,0]</code> with <code>m,n=±1</code>. The last <code>0</code> checks that the first and last letter were equal, and the length ensures that the input string had length 5.</p>

<hr>

<p>An alternative 71. Checks the conditions on comparisons while ensuring the right length.</p>

<pre class="lang-python prettyprint-override"><code>def f(s):a,b,c,d,e=map(cmp,s,s[1:]+s*9)[:5];print a*c<0==e>b*d>len(s)-7
</code>```

Title: Find the Infinity Words!

Body:
Python 2, 71 bytes

lambda s:map(cmp,s,s[1:]+s[0])in[[m,n,-m,-n,0]for m in-1,1for n in-1,1]

Takes the string s with characters abcde, rotates it to bcdea, and does an elementwise comparison of corresponding characters.

a  b   cmp(a,b)
b  c   cmp(b,c)
c  d   cmp(c,d)
d  e   cmp(d,e)
e  a   cmp(e,a)

The result is a list of -1, 0, 1. Then, checks if the result is one of the valid sequences of up and downs:

[-1, -1, 1, 1, 0]
[-1, 1, 1, -1, 0]
[1, -1, -1, 1, 0]
[1, 1, -1, -1, 0]

as generated from the template [m,n,-m,-n,0] with m,n=±1. The last 0 checks that the first and last letter were equal, and the length ensures that the input string had length 5.

An alternative 71. Checks the conditions on comparisons while ensuring the right length.

def f(s):a,b,c,d,e=map(cmp,s,s[1:]+s*9)[:5];print a*c<0==e>b*d>len(s)-7


问:
Program that creates larger versions of itself (quine-variant)
You are to write a program that will output source code that is

Larger than the original program (character wise)

Will print another program larger than itself when run (i.e. the new program is also a valid answer to this challenge) indefinitely

This is code-golf, so shortest answer wins.

答:
GS2 (8636bd8e), 0 bytes

``````

This prints a single newline, which prints two newlines, which prints three newlines, et cetera.

Try it online!

Body:
GS2 (8636bd8e), 0 bytes

This prints a single newline, which prints two newlines, which prints three newlines, et cetera.

Try it online!


答:
C, <s>44 bytes</s>, 41 bytes

```<code>int*n(int*s,int a){return a?n(&s,a-1):s;}
</code>```

You can test it by doing the following:

```<code>int main(void) {
    char* s = "stackoverflow";

    /* Test Case 0 */
    int* a = n(s,0);
    printf("'%s'\n", a);

    /* Test Case 1 */
    int* b = n(s,1);
    printf("['%s']\n", *b);

    /* Test Case 2 */
    int** c = n(s,2);
    printf("[['%s']]\n", **c);

    /* Test Case 3 */
    int*** d = n(s,3);
    printf("[[['%s']]]\n", ***d);

    /* Test Case 4 */
    int********** e = n(s,10);
    printf("[[[[[[[[[['%s']]]]]]]]]]\n", **********e);

    return 0;
}
</code>```

The output:

```<code>'stackoverflow'
['stackoverflow']
[['stackoverflow']]
[[['stackoverflow']]]
[[[[[[[[[['stackoverflow']]]]]]]]]]
</code>```

Of course, you'll get warnings. This works on gcc on bash on my Windows machine (gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3), as well as on a true Linux machine (gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)).

Title: Nest a string inside an array n times

Body:
You must produce a function which nests a string s inside an array, n times

```<code>>>> N("stackoverflow",2)
[['stackoverflow']]
</code>```

Parameters:

s - An ascii string

n - An integer >= 0

Rules

Shortest code wins.

The output will be a nested array, list or tuple (or similar type based off an array)

Test Cases

```<code>>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]
</code>```

Inspired by: Nesting a string inside a list n times ie list of a list of a list

Body:
C, <s>44 bytes</s>, 41 bytes

int*n(int*s,int a){return a?n(&s,a-1):s;}

You can test it by doing the following:

int main(void) {
    char* s = "stackoverflow";

    /* Test Case 0 */
    int* a = n(s,0);
    printf("'%s'\n", a);

    /* Test Case 1 */
    int* b = n(s,1);
    printf("['%s']\n", *b);

    /* Test Case 2 */
    int** c = n(s,2);
    printf("[['%s']]\n", **c);

    /* Test Case 3 */
    int*** d = n(s,3);
    printf("[[['%s']]]\n", ***d);

    /* Test Case 4 */
    int********** e = n(s,10);
    printf("[[[[[[[[[['%s']]]]]]]]]]\n", **********e);

    return 0;
}

The output:

'stackoverflow'
['stackoverflow']
[['stackoverflow']]
[[['stackoverflow']]]
[[[[[[[[[['stackoverflow']]]]]]]]]]

Of course, you'll get warnings. This works on gcc on bash on my Windows machine (gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.3), as well as on a true Linux machine (gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)).


答:
RProgN, 22 Bytes

```<code>►xX=x=1\_1:[s]xPX=}x
</code>```

Explination

```<code>►xX=x=1\_1:[s]xPX=}x
►                   # Spaceless segment.
 xX=                # Assign 'x' to X
    x=              # Assign the string input to 'x'
      1\_1:       } # Push 1, flip it under the number input Then floor it, converting it from a string(?) to an integer, push another one, execute it as a for loop (i=1; i<=INPUT; i+=1)
           [            # Pop the incrementer of the for loop. We don't need it here.
            s]      # Push a new stack, then clone it.
              xP        # Push x, (Either the current bottom stack or the string), Push it to the new stack
                X=  # Assign it back to 'x' (This is why we set X to x)
                   x    # Push x to the reg stack. Implicitly return.
</code>```

Easy enough, fun to finally get to use multi-dimensional stacks.

Try it Online!

Title: Nest a string inside an array n times

Body:
RProgN, 22 Bytes

►xX=x=1\_1:[s]xPX=}x

Explination

►xX=x=1\_1:[s]xPX=}x
►                   # Spaceless segment.
 xX=                # Assign 'x' to X
    x=              # Assign the string input to 'x'
      1\_1:       } # Push 1, flip it under the number input Then floor it, converting it from a string(?) to an integer, push another one, execute it as a for loop (i=1; i<=INPUT; i+=1)
           [            # Pop the incrementer of the for loop. We don't need it here.
            s]      # Push a new stack, then clone it.
              xP        # Push x, (Either the current bottom stack or the string), Push it to the new stack
                X=  # Assign it back to 'x' (This is why we set X to x)
                   x    # Push x to the reg stack. Implicitly return.

Easy enough, fun to finally get to use multi-dimensional stacks.

Try it Online!