问:
Palindromizing the strings

Introduction

For the ones who don't know, a palindrome is when a string is equal to the string backwards (with exception to interpunction, spaces, etc.). An example of a palindrome is:

```<code>abcdcba
</code>```

If you reverse this, you will end up with:

```<code>abcdcba
</code>```

Which is the same. Therefore, we call this a palindrome. To palindromize things, let's take a look at an example of a string:

```<code>adbcb
</code>```

This is not a palindrome. To palindromize this, we need to merge the reversed string into the initial string at the right of the initial string, leaving both versions intact. The shorter, the better.

The first thing we can try is the following:

```<code>adbcb
bcbda
^^ ^^
</code>```

Not all characters match, so this is not the right position for the reversed string. We go one step to the right:

```<code>adbcb
 bcbda
 ^^^^
</code>```

This also doesn't match all characters. We go another step to the right:

```<code>adbcb
  bcbda
</code>```

This time, all characters match. We can merge both string leaving the intact. The final result is:

```<code>adbcbda
</code>```

This is the palindromized string.

The Task

Given a string (with at least one character) containing only lowercase letters (or uppercase, if that fits better), output the palindromized string.

Test cases

```<code>Input     Output

abcb      abcba
hello     hellolleh
bonobo    bonobonob
radar     radar
hex       hexeh
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

答:
Perl, 37 bytes

Based on xnor's answer.

Includes +2 for -lp

Run with input on STDIN, e.g.

```<code>palindromize.pl <<< bonobo
</code>```

palindromize.pl:

```<code>#!/usr/bin/perl -lp
s/.//,do$0,$_=$&.$_.$&if$_!~reverse
</code>```

Title: Palindromizing the strings

Body:
Perl, 37 bytes

Based on xnor's answer.

Includes +2 for -lp

Run with input on STDIN, e.g.

palindromize.pl <<< bonobo

palindromize.pl:

#!/usr/bin/perl -lp
s/.//,do$0,$_=$&.$_.$&if$_!~reverse


问:
Are the brackets fully matched?
You must write a program or function that takes a string of brackets and outputs whether or not that string is fully matched. Your program should print a truthy or falsy value, and IO can be in any reasonable format.

Rules and definitions:

For the purpose of this challenge, a "bracket" is any of these characters: ()[]{}<>.

A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as

```<code>()
[]{}
</code>```

Or if every subelement inside of it is also matched.

```<code>[()()()()]
{<[]>}
(()())
</code>```

Subelements can also be nested several layers deep.

```<code>[(){<><>[()]}<>()]
<[{((()))}]>
</code>```

A string is considered "Fully matched" if and only if:

Every single character is a bracket,

Each pair of brackets has the correct opening and closing bracket and in the right order, and

Each bracket is matched.

You may assume the input will only contain printable ASCII.

Test IO

Here are some inputs that should return a truthy value:

```<code>()
[](){}<>
(((())))
({[<>]})
[{()<>()}[]]
[([]{})<{[()<()>]}()>{}]
</code>```

And here are some outputs that should return a falsy value:

```<code>(               Has no closing ')'
}{              Wrong order
(<)>            Each pair contains only half of a matched element
(()()foobar)    Contains invalid characters
[({}<>)>        The last bracket should be ']' instead of '>'
(((()))         Has 4 opening brackets, but only 3 closing brackets.
</code>```

As usual, this is code-golf, so standard loopholes apply, and shortest answer in bytes wins.

答:
Pyth, 20 bytes

```<code>!uuscNTc"[](){}<>"2G
</code>```

Try it online: Test Suite

Repeatedly removes occurrences of [], (), <> and {} by splitting and re-merging. Checks if the resulting string is empty or not.

ContentLicense: CC BY-SA 3.0

Title: Are the brackets fully matched?

Body:
Pyth, 20 bytes

!uuscNTc"[](){}<>"2G

Try it online: <a href="http://pyth.herokuapp.com/?code=!uuscNTc%22[]%28%29%7B%7D%3C%3E%222G&input=%22%28[%29]%22&test_suite=1&test_suite_input=%22%28%29%22%0A%22[]%28%29%7B%7D%3C%3E%22%0A%22%28%28%28%28%29%29%29%29%22%0A%22%28%7B[%3C%3E]%7D%29%22%0A%22[%7B%28%29%3C%3E%28%29%7D[]]%22%0A%22[%28[]%7B%7D%29%3C%7B[%28%29%3C%28%29%3E]%7D%28%29%3E%7B%7D]%22%0A%22%28%22%0A%22%7D%7B%22%0A%22%28%3C%29%3E%22%0A%22%28%28%29%28%29foobar%29%22%0A%22[%28%7B%7D%3C%3E%29%3E%22%0A%22%28%28%28%28%29%29%29%22&debug=0" rel="nofollow">Test Suite

Repeatedly removes occurrences of [], (), <> and {} by splitting and re-merging. Checks if the resulting string is empty or not.


问:
Shortest code for infinite disk I/O
(Just open 50 tabs in Google Chrome :D (just kidding, no you can't))

Shortest code for infinite disk I/O any language, C# example:

using System.IO;

namespace FileApp {
    static class Program {
        public static void Main() {
            do {
                File.WriteAllText("a", "a");
                File.Delete("a");
            } while (true);
        }
    }
}
```

You can't just fill the entire disk though, as then it would halt in the end and would be finite.

And you can't do reading only, infinite writing has to happen. (It has to kill my SSD after enough runtime.)

Get cracking! :)

答:
vim text editor, 10 bytes

```<code>qa:w<enter>@aq@a
</code>```

8 bytes if you do not could the execution command @a

Title: Shortest code for infinite disk I/O

Body:
vim text editor, 10 bytes

qa:w<enter>@aq@a

8 bytes if you do not could the execution command @a


问:
Rectangle Detection
Write a program or function that takes in a multiline string of 0's and 1's. No other characters will be in the string and the string will always be rectangular (all lines will have same number of characters), with dimensions as small as 1×1, but otherwise the 0's and 1's may be arranged arbitrarily.

You may assume the string has an optional trailing newline, and if desired you may use any two distinct printable ASCII characters in place of 0 and 1.

Print or return a truthy value if all of the path connected regions of both 0's and 1's in the string are solid rectangles, else output a falsy value.

A path connected region of 0's means that from any one 0 in the region, all the other 0's can be reached by only moving up, down, left and right to other 0's (and not moving diagonally, not moving to any 1, and not moving outside the string bounds). The same idea applies to 1 path connected regions.

A solid rectangle of 0's means the entire area of the rectangle is filled with 0's and no 1's. The same idea applies to 1 solid rectangles.

The shortest code in bytes wins. Tiebreaker is earlier answer.

(Note that the string does not wrap around with toroidal boundary conditions.)

Examples

1) This input string has 3 path connected regions (2 for 0 and 1 for 1). Only the bottom right 00 region is a solid rectangle though, so the output would be falsy.

```<code>0011
0111
0100
</code>```

2) This input string has 4 path connected regions (2 for both 0 and 1). All of them are solid rectangles so the output would be truthy.

```<code>0011
0011
1100
</code>```

3) This input has 2 path connected regions, but only one of them is a solid rectangle, so the output would be falsy.

```<code>00000000
01111110
00000000
</code>```

4) This input has only 1 path connected region and is trivially a solid rectangle, so the output is truthy.

```<code>11111111
11111111
11111111
</code>```

Test Cases

A T just below the input string means truthy, F means falsy.

```<code>0
T

1
T

00
T

01
T

10
T

11
T

0000000
T

1111111
T

011100100100101100110100100100101010100011100101
T

00
11
T

01
10
T

01
11
F

00
01
F

11
11
T

110
100
F

111
000
T

111
101
111
F

101
010
101
T

1101
0010
1101
0010
T

1101
0010
1111
0010
F

0011
0111
0100
F

0011
0011
1100
T

00000000
01111110
00000000
F

11111111
11111111
11111111
T

0000001111
0000001111
T

0000001111
0000011111
F

0000001111
1000001111
F

1000001111
1000001111
T

1110100110101010110100010111011101000101111
1010100100101010100100010101010101100101000
1110100110010010110101010111010101010101011
1010100100101010010101010110010101001101001
1010110110101010110111110101011101000101111
F</code>```

答:
Snails, 20 bytes

```<code>!{to{\0w`3\1|\1w`3\0
</code>```

Prints the area of the grid if there isn't a 2x2 square with 3 zeroes and a one or 3 ones and a zero, or 0 if such a 2x2 square exists.

Title: Rectangle Detection

Body:
Snails, 20 bytes

!{to{\0w`3\1|\1w`3\0

Prints the area of the grid if there isn't a 2x2 square with 3 zeroes and a one or 3 ones and a zero, or 0 if such a 2x2 square exists.


答:
Brachylog, <s>16</s> <s>6</s> 5 bytes (Non-competing)

```<code>:Ac.r
</code>```

Try it online!

When I posted my initial answer, it was still on the old implementation in Java. Since I have reprogrammed everything in Prolog, it now works as it should have in the first place.

Explanation

```<code>(?):Ac.        Output is the concatenation of Input with another unknown string A
      .r(.)    The reverse of the Output is the Output
</code>```

Backpropagation makes it so that the first valid value for A it will find will be the shortest that you can concatenate to Input to make it a palindrome.

Alternate solution, 5 bytes

```<code>~@[.r
</code>```

This is roughly the same as the above answer, except that instead of stating "Output is the concatenation of the Input with a string A", we state that "Output is a string for which the Input is a prefix of the Output".

Title: Palindromizing the strings

Body:
Introduction

For the ones who don't know, a palindrome is when a string is equal to the string backwards (with exception to interpunction, spaces, etc.). An example of a palindrome is:

```<code>abcdcba
</code>```

If you reverse this, you will end up with:

```<code>abcdcba
</code>```

Which is the same. Therefore, we call this a palindrome. To palindromize things, let's take a look at an example of a string:

```<code>adbcb
</code>```

This is not a palindrome. To palindromize this, we need to merge the reversed string into the initial string at the right of the initial string, leaving both versions intact. The shorter, the better.

The first thing we can try is the following:

```<code>adbcb
bcbda
^^ ^^
</code>```

Not all characters match, so this is not the right position for the reversed string. We go one step to the right:

```<code>adbcb
 bcbda
 ^^^^
</code>```

This also doesn't match all characters. We go another step to the right:

```<code>adbcb
  bcbda
</code>```

This time, all characters match. We can merge both string leaving the intact. The final result is:

```<code>adbcbda
</code>```

This is the palindromized string.

The Task

Given a string (with at least one character) containing only lowercase letters (or uppercase, if that fits better), output the palindromized string.

Test cases

```<code>Input     Output

abcb      abcba
hello     hellolleh
bonobo    bonobonob
radar     radar
hex       hexeh
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

Body:
Brachylog, <s>16</s> <s>6</s> 5 bytes (Non-competing)

:Ac.r

Try it online!

When I posted my initial answer, it was still on the old implementation in Java. Since I have reprogrammed everything in Prolog, it now works as it should have in the first place.

Explanation

(?):Ac.        Output is the concatenation of Input with another unknown string A
      .r(.)    The reverse of the Output is the Output

Backpropagation makes it so that the first valid value for A it will find will be the shortest that you can concatenate to Input to make it a palindrome.

Alternate solution, 5 bytes

~@[.r

This is roughly the same as the above answer, except that instead of stating "Output is the concatenation of the Input with a string A", we state that "Output is a string for which the Input is a prefix of the Output".


答:
Yacc, 119 bytes

Does not use regex/replace.

```<code>%%input:r;r:%empty|'['r']'r|'{'r'}'r|'('r')'r|'<'r'>'r;%%yylex(){return getchar();}main(){return yyparse();}yyerror(){}
</code>```

Ungolfed

```<code>%%                              # Grammar in BNF
input:
  r;
r:
  %empty
| '['r']'r
| '{'r'}'r
| '('r')'r
| '<'r'>'r;
%%                              # Minimal parser invocation and lexer
yylex(){return getchar();}
main(){return yyparse();}
yyerror(){}
</code>```

Compilation

```<code>yacc -o bracket.c bracket.y
cc -o bracket bracket.c
</code>```

Usage

```<code>~/ % echo -n "<()[]>" | ./bracket
~/ %
~/ % echo -n "{" | ./bracket
~/ 1 %                                                                         :(
</code>```

Title: Are the brackets fully matched?

Body:
You must write a program or function that takes a string of brackets and outputs whether or not that string is fully matched. Your program should print a truthy or falsy value, and IO can be in any reasonable format.

Rules and definitions:

For the purpose of this challenge, a "bracket" is any of these characters: ()[]{}<>.

A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as

```<code>()
[]{}
</code>```

Or if every subelement inside of it is also matched.

```<code>[()()()()]
{<[]>}
(()())
</code>```

Subelements can also be nested several layers deep.

```<code>[(){<><>[()]}<>()]
<[{((()))}]>
</code>```

A string is considered "Fully matched" if and only if:

Every single character is a bracket,

Each pair of brackets has the correct opening and closing bracket and in the right order, and

Each bracket is matched.

You may assume the input will only contain printable ASCII.

Test IO

Here are some inputs that should return a truthy value:

```<code>()
[](){}<>
(((())))
({[<>]})
[{()<>()}[]]
[([]{})<{[()<()>]}()>{}]
</code>```

And here are some outputs that should return a falsy value:

```<code>(               Has no closing ')'
}{              Wrong order
(<)>            Each pair contains only half of a matched element
(()()foobar)    Contains invalid characters
[({}<>)>        The last bracket should be ']' instead of '>'
(((()))         Has 4 opening brackets, but only 3 closing brackets.
</code>```

As usual, this is code-golf, so standard loopholes apply, and shortest answer in bytes wins.

Body:
Yacc, 119 bytes

Does not use regex/replace.

%%input:r;r:%empty|'['r']'r|'{'r'}'r|'('r')'r|'<'r'>'r;%%yylex(){return getchar();}main(){return yyparse();}yyerror(){}

Ungolfed

%%                              # Grammar in BNF
input:
  r;
r:
  %empty
| '['r']'r
| '{'r'}'r
| '('r')'r
| '<'r'>'r;
%%                              # Minimal parser invocation and lexer
yylex(){return getchar();}
main(){return yyparse();}
yyerror(){}

Compilation

yacc -o bracket.c bracket.y
cc -o bracket bracket.c

Usage

~/ % echo -n "<()[]>" | ./bracket
~/ %
~/ % echo -n "{" | ./bracket
~/ 1 %                                                                         :(


问:
Simulate Cookie Clicker

Intro

Cookie Clicker is a popular browser game in which the player has to click a cookie to gain... Cookies!

The player can buy upgrades which will automatically farm cookies for you. Sometimes a golden cookie will enter the screen, which will provide a bonus upon clicking it.

Challenge

This challenge will not be about clicking a cookie. It will be about automating the cookie.

The player starts off with 0 cookies, and will gain cookies on every game tick. The goal of the challenge is to calculate the amount of ticks it takes to reach a certain amount of cookies.

Input

Your program or function will have 2 input parameters.

The first parameter is the goal, which is simply the amount of cookies you need to finish.

The second parameter is a list of upgrades the player can buy. The format of the list will be explained in further detail in the paragraph Upgrades - List format.

For sake of convenience, you may assume that the input is always in the correct format. You don't have to deal with bad input.

Output

Your program or function should print or return the amount of ticks it takes before the player has reached the goal amount of cookies.

Upgrades

Every game-tick will earn the player some cookies. These are based on the upgrades of the player. If a player has no upgrades, the cookie production will be 1 cookie per tick. Once the player reaches enough cookies to buy an upgrade, he will automatically purchase it (before the next tick happens).

When the player has enough cookies after a tick to buy multiple upgrades, he will attempt to buy all possible upgrades, starting with the cheapest.

List format

[[100, '+', 1],[1000, '*', 2],[10000, '*', 10]

This is an unordered list which contains 3 upgrades. The first parameter of an upgrade is the price of the upgrade. The second parameter is the effect of the upgrade and the third parameter is the effect amount.

The input list will contain no upgrades with the same price.

The only possible effects are + (addition) and * (multiplication).

[100, '+', 1] means that the cookie production will increase by 1 at a cost of 100 cookies.

Golden cookies

Every 1000 ticks, the player will find a golden cookie. When this happens, the player will receive a bonus of 10% (rounded down) of his cookie amount. If the player has 1000 cookies at tick 1000, he will have 1100 cookies before tick 1001 happens.

Order of events

After every tick a couple of actions can occur.

If the player has enough cookies, end the game

If the player has enough cookies, purchase upgrades

If the amount of ticks is a multiple of 1000; Golden cookie

Example input + output

```<code>(0    , [])                              -> 0
(100  , [])                              -> 100
(1    , [[10, '+', 1]])                  -> 1
(10   , [[10, '+', 1]])                  -> 10
(1000 , [[100, '*', 2], [10, '+', 1]])   -> 310
(10000, [[10, '+', 1], [100, '*', 2]])   -> 2263
</code>```

Detailed example

```<code>(1000 , [[100, '*', 2], [10, '+', 1]])   -> 310

ticks: 8, cookies: 8, production: 1
ticks: 9, cookies: 9, production: 1
ticks: 10, cookies: 0, production: 2
ticks: 11, cookies: 2, production: 2
ticks: 58, cookies: 96, production: 2
ticks: 59, cookies: 98, production: 2
ticks: 60, cookies: 0, production: 4
ticks: 61, cookies: 4, production: 4
ticks: 70, cookies: 40, production: 4
ticks: 80, cookies: 80, production: 4
ticks: 260, cookies: 800, production: 4
ticks: 280, cookies: 880, production: 4
ticks: 300, cookies: 960, production: 4
ticks: 309, cookies: 996, production: 4
ticks: 310, cookies: 1000, production: 4 -- done
</code>```

Disclaimer

I will not be held responsible for any addictions caused by this challenge.

Happy golfing!

答:
Lua, 220 Bytes

Can't think of a way to golf it down for the moment, it's still pretty long mostly because lua doesn't let you use loops carelessly regarding the bit count ^^'

function f(g,u)c=0t=0r=1while(c<g)do c=c+r t=t+1if(c>=g)then break end
for i=1,#u do x=u[i]if(c>=x[1])then c=c-x[1]r=x[2]=="+"and r+x[3]or r*x[3]table.remove(u,i)break
end end c=t%1000<1 and c+c/10or c end return t end
```

<h3>Ungolfed</h3>

<pre class="lang-lua prettyprint-override"><code>function f(g,u)
  c=0                       -- cookie counter
  t=0                       -- tick counter
  r=1                       -- cookie gain rate

  while(c<g)                -- iterate while cookie < goal
  do                        -- prevent returning 1 tick when the goal is 0
    c=c+r                   -- gain cookies
    t=t+1                   -- increment the tick counter
    if(c>=g)then break end  -- if we have enough cookies, exit
    for i=1,#u              -- iterate over the upgrades
    do
      x=u[i]                -- alias the current upgrade
      if(c>=x[1])           -- if we can, afford it
      then
        c=c-x[1]            -- deduce its price from our cookies
        r=x[2]=="+"         -- if it was an additive bonus
          and r+x[3]        -- add its value to the rate
          or r*x[3]         -- else multiply the rate by it
        table.remove(u,i)   --remove it from the list of upgrades
        break               -- exit the shop :D
      end
    end
    c=t%1000<1              -- every thousand ticks
      and c+c/10            -- get a golden cookie
      or c                  -- every other ticks does nothing
  end
  return t                  -- return the number of ticks it took
end
</code>```

Test Suite

You can copy paste the following code into this online compiler to run all the test cases.

function f(g,u)c=0t=0r=1while(c<g)do c=c+r t=t+1if(c>=g)then break end
for i=1,#u do x=u[i]if(c>=x[1])then c=c-x[1]r=x[2]=="+"and r+x[3]or r*x[3]table.remove(u,i)break
end end c=t%1000<1 and c+c/10or c end return t end
print(f(0,{}))
print(f(100,{}))
print(f(1,{{10,'+',1}}))
print(f(10,{{10,'+',1}}))
print(f(1000,{{10,'+',1},{100,'*',2}}))
print(f(10000,{{10,'+',1},{100,'*',2}}))
```

Title: Simulate Cookie Clicker

Body:
Lua, 220 Bytes

Can't think of a way to golf it down for the moment, it's still pretty long mostly because lua doesn't let you use loops carelessly regarding the bit count ^^'

function f(g,u)c=0t=0r=1while(c<g)do c=c+r t=t+1if(c>=g)then break end
for i=1,#u do x=u[i]if(c>=x[1])then c=c-x[1]r=x[2]=="+"and r+x[3]or r*x[3]table.remove(u,i)break
end end c=t%1000<1 and c+c/10or c end return t end

Ungolfed

function f(g,u)
  c=0                       -- cookie counter
  t=0                       -- tick counter
  r=1                       -- cookie gain rate

  while(c<g)                -- iterate while cookie < goal
  do                        -- prevent returning 1 tick when the goal is 0
    c=c+r                   -- gain cookies
    t=t+1                   -- increment the tick counter
    if(c>=g)then break end  -- if we have enough cookies, exit
    for i=1,#u              -- iterate over the upgrades
    do
      x=u[i]                -- alias the current upgrade
      if(c>=x[1])           -- if we can, afford it
      then
        c=c-x[1]            -- deduce its price from our cookies
        r=x[2]=="+"         -- if it was an additive bonus
          and r+x[3]        -- add its value to the rate
          or r*x[3]         -- else multiply the rate by it
        table.remove(u,i)   --remove it from the list of upgrades
        break               -- exit the shop :D
      end
    end
    c=t%1000<1              -- every thousand ticks
      and c+c/10            -- get a golden cookie
      or c                  -- every other ticks does nothing
  end
  return t                  -- return the number of ticks it took
end

Test Suite

You can copy paste the following code into this online compiler to run all the test cases.

function f(g,u)c=0t=0r=1while(c<g)do c=c+r t=t+1if(c>=g)then break end
for i=1,#u do x=u[i]if(c>=x[1])then c=c-x[1]r=x[2]=="+"and r+x[3]or r*x[3]table.remove(u,i)break
end end c=t%1000<1 and c+c/10or c end return t end
print(f(0,{}))
print(f(100,{}))
print(f(1,{{10,'+',1}}))
print(f(10,{{10,'+',1}}))
print(f(1000,{{10,'+',1},{100,'*',2}}))
print(f(10000,{{10,'+',1},{100,'*',2}}))


Title: Are the brackets fully matched?

Body:
Python 2, 80 bytes

def m(s,i=0):exec's=s.replace("[({<])}>"[i%4::4],"");i+=1;'*4*len(s);return"">=s


答:
Pyth, <s>31</s> <s>25</s> 24 bytes

Golfed down to 25 bytes thanks to FryAmTheEggMan
Removed 1 byte

```<code>VQ=:Q"<>|\[]|{}|\(\)"k;!
</code>```

Try it here: Test suite !

I'm still a Pyth newbie, any help is appreciated.

Explanation

```<code>VQ                         For N in range(0, len(z)), with Q being the evaluated input.
                           Optimal solution would be to use range(0, len(z)/2) instead, but it add two bytes.
  =:Q"<>|\[]|{}|\(\)"k     assign Q without {}, [], <> nor () (regex replacement) to Q
                      ;    End of For loop
                       !   Logical NOT of Q's length (Q is the input, but has gone several times through y, and Q is implicit).
                           This last operation returns True if len(Q) is 0 (which means all brackets were matched), False otherwise
</code>```

BTW, congrats to the other Pyth answer (which is currently 20 bytes)

Title: Are the brackets fully matched?

Body:
Pyth, <s>31</s> <s>25</s> 24 bytes

Golfed down to 25 bytes thanks to FryAmTheEggMan
Removed 1 byte

VQ=:Q"<>|\[]|{}|\(\)"k;!

Try it here: Test suite !

I'm still a Pyth newbie, any help is appreciated.

Explanation

VQ                         For N in range(0, len(z)), with Q being the evaluated input.
                           Optimal solution would be to use range(0, len(z)/2) instead, but it add two bytes.
  =:Q"<>|\[]|{}|\(\)"k     assign Q without {}, [], <> nor () (regex replacement) to Q
                      ;    End of For loop
                       !   Logical NOT of Q's length (Q is the input, but has gone several times through y, and Q is implicit).
                           This last operation returns True if len(Q) is 0 (which means all brackets were matched), False otherwise

BTW, congrats to the other Pyth answer (which is currently 20 bytes)


答:
MATL, 12 bytes

```<code>Ybc2thYCs2\~
</code>```

Same algorithm as @sp3000's great answer.

To allow multiline input, MATL needs the row char array (string) to be explicitly built using character 10 for newline. So the input of the four examples are (note that [] is concatenation, so each of these is a row array of chars):

```<code>['0011' 10 '0111' 10 '0100']
['0011' 10 '0011' 10 '1100']
['00000000' 10 '01111110' 10 '00000000']
['11111111' 10 '11111111' 10 '11111111']
</code>```

and the last three test cases are

```<code>['0000001111' 10 '1000001111']
['1000001111' 10 '1000001111']
['1110100110101010110100010111011101000101111' 10 '1010100100101010100100010101010101100101000' 10 '1110100110010010110101010111010101010101011' 10 '1010100100101010010101010110010101001101001' 10 '1010110110101010110111110101011101000101111']
</code>```

Truthy output is an array containing only ones.

Try it online!

Explanation

This uses the fact that the parity of chars '0' and '1' is the same as that of numbers 0 and 1, so there's not need to convert from char to the digit it represents,

```<code>Yb     % split implicit input by whitespace. Gives a cell array
c      % concatenate cell contents into 2D char array
2th    % push array [2 2]
YC     % get 2×2 sliding blocks and arrange as columns
s      % sum of each column
2\     % modulo 2 of each sum
~      % negate. Implicit display
</code>```

Title: Rectangle Detection

Body:
Write a program or function that takes in a multiline string of 0's and 1's. No other characters will be in the string and the string will always be rectangular (all lines will have same number of characters), with dimensions as small as 1×1, but otherwise the 0's and 1's may be arranged arbitrarily.

You may assume the string has an optional trailing newline, and if desired you may use any two distinct printable ASCII characters in place of 0 and 1.

Print or return a truthy value if all of the path connected regions of both 0's and 1's in the string are solid rectangles, else output a falsy value.

A path connected region of 0's means that from any one 0 in the region, all the other 0's can be reached by only moving up, down, left and right to other 0's (and not moving diagonally, not moving to any 1, and not moving outside the string bounds). The same idea applies to 1 path connected regions.

A solid rectangle of 0's means the entire area of the rectangle is filled with 0's and no 1's. The same idea applies to 1 solid rectangles.

The shortest code in bytes wins. Tiebreaker is earlier answer.

(Note that the string does not wrap around with toroidal boundary conditions.)

Examples

1) This input string has 3 path connected regions (2 for 0 and 1 for 1). Only the bottom right 00 region is a solid rectangle though, so the output would be falsy.

```<code>0011
0111
0100
</code>```

2) This input string has 4 path connected regions (2 for both 0 and 1). All of them are solid rectangles so the output would be truthy.

```<code>0011
0011
1100
</code>```

3) This input has 2 path connected regions, but only one of them is a solid rectangle, so the output would be falsy.

```<code>00000000
01111110
00000000
</code>```

4) This input has only 1 path connected region and is trivially a solid rectangle, so the output is truthy.

```<code>11111111
11111111
11111111
</code>```

Test Cases

A T just below the input string means truthy, F means falsy.

```<code>0
T

1
T

00
T

01
T

10
T

11
T

0000000
T

1111111
T

011100100100101100110100100100101010100011100101
T

00
11
T

01
10
T

01
11
F

00
01
F

11
11
T

110
100
F

111
000
T

111
101
111
F

101
010
101
T

1101
0010
1101
0010
T

1101
0010
1111
0010
F

0011
0111
0100
F

0011
0011
1100
T

00000000
01111110
00000000
F

11111111
11111111
11111111
T

0000001111
0000001111
T

0000001111
0000011111
F

0000001111
1000001111
F

1000001111
1000001111
T

1110100110101010110100010111011101000101111
1010100100101010100100010101010101100101000
1110100110010010110101010111010101010101011
1010100100101010010101010110010101001101001
1010110110101010110111110101011101000101111
F</code>```

Body:
MATL, 12 bytes

Ybc2thYCs2\~

Same algorithm as @sp3000's great answer.

To allow multiline input, MATL needs the row char array (string) to be explicitly built using character 10 for newline. So the input of the four examples are (note that [] is concatenation, so each of these is a row array of chars):

['0011' 10 '0111' 10 '0100']
['0011' 10 '0011' 10 '1100']
['00000000' 10 '01111110' 10 '00000000']
['11111111' 10 '11111111' 10 '11111111']

and the last three test cases are

['0000001111' 10 '1000001111']
['1000001111' 10 '1000001111']
['1110100110101010110100010111011101000101111' 10 '1010100100101010100100010101010101100101000' 10 '1110100110010010110101010111010101010101011' 10 '1010100100101010010101010110010101001101001' 10 '1010110110101010110111110101011101000101111']

Truthy output is an array containing only ones.

Try it online!

Explanation

This uses the fact that the parity of chars '0' and '1' is the same as that of numbers 0 and 1, so there's not need to convert from char to the digit it represents,

Yb     % split implicit input by whitespace. Gives a cell array
c      % concatenate cell contents into 2D char array
2th    % push array [2 2]
YC     % get 2×2 sliding blocks and arrange as columns
s      % sum of each column
2\     % modulo 2 of each sum
~      % negate. Implicit display


Title: Are the brackets fully matched?

Body:
C, <s>121</s> <s>122</s> 114 bytes

Shaved of 8 bytes thanks to @xsot!

a[99],i,k;main(c){for(;read(0,&c,!k);c%7&2?k|=a[i--]^c/9:(a[++i]=c/9))k|=!strchr("()[]{}<>",c);putchar(48+!k*!i);}

Uses a stack.


问:
The plus-minus sequence

The plus-minus sequence

The plus-minus sequence is one that starts with two seeds, a(0) and b(0). Each iteration of this sequence is the addition and subtraction of the previous two members of the sequence. That is, a(N) = a(N-1) + b(N-1) and b(N) = a(N-1) - b(N-1).

Objective Produce the plus-minus sequence, in infinitude or the first K steps given K. You may do this using an infinite output program, a generator, or a function/program that gives the first K steps. The output order does not matter, so long as it is consistent. (I.e., b(K) a(K) or a(K) b(K), with some non-numeric, non-newline separator in between.) The output must start with the input.

Test cases

For inputs 10 2 (of a(0) b(0), this is a possible output for the first K approach (or a subsection of the infinite approach):

```<code>10     2
12     8
20     4
24     16
40     8
48     32
80     16
96     64
160    32
192    128
320    64
384    256
640    128
768    512
1280   256
1536   1024
2560   512
3072   2048
5120   1024
6144   4096
10240  2048
12288  8192
20480  4096
24576  16384
40960  8192
49152  32768
81920  16384
98304  65536
</code>```

For inputs 2 20 10 (a(0) b(0) k):

```<code>2     20
22   -18
4     40
44   -36
8     80
88   -72
16    160
176  -144
32    320
352  -288
</code>```

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Mathcad, 52 bytes

Two versions: one uses Mathcad's range variables (a form of iterator) and the second uses a for-loop inside a function.

The Mathcad user interface is a 2D "whiteboard", wherein expressions (which may be equations, text, plots or results) are evaluated in left-to-right, top-to-bottom order.  Identifier names are usually typed letter-by-letter, but there are also many combinations that allow the user to enter Mathcad specific operators.  For example, typing "=" will enter the definition operator (:=) and ";" will enter the range operator (..).  Typing ctl-m brings up the matrix dialog, and typing the number of row and columns will create a matrix of that size.  For golfing purposes, a Mathcad "byte" is taken to be the number of keyboard characters necessary to enter a letter/number/operator.

{the augment function is just there to make the display more table like but doesn't count to the byte total}

ContentLicense: CC BY-SA 4.0

Title: The plus-minus sequence


Title: The plus-minus sequence

Body:
The plus-minus sequence

The plus-minus sequence is one that starts with two seeds, a(0) and b(0). Each iteration of this sequence is the addition and subtraction of the previous two members of the sequence. That is, a(N) = a(N-1) + b(N-1) and b(N) = a(N-1) - b(N-1).

Objective Produce the plus-minus sequence, in infinitude or the first K steps given K. You may do this using an infinite output program, a generator, or a function/program that gives the first K steps. The output order does not matter, so long as it is consistent. (I.e., b(K) a(K) or a(K) b(K), with some non-numeric, non-newline separator in between.) The output must start with the input.

Test cases

For inputs 10 2 (of a(0) b(0), this is a possible output for the first K approach (or a subsection of the infinite approach):

```<code>10     2
12     8
20     4
24     16
40     8
48     32
80     16
96     64
160    32
192    128
320    64
384    256
640    128
768    512
1280   256
1536   1024
2560   512
3072   2048
5120   1024
6144   4096
10240  2048
12288  8192
20480  4096
24576  16384
40960  8192
49152  32768
81920  16384
98304  65536
</code>```

For inputs 2 20 10 (a(0) b(0) k):

```<code>2     20
22   -18
4     40
44   -36
8     80
88   -72
16    160
176  -144
32    320
352  -288
</code>```

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
><>, 26 bytes

:?!;1-r:n48*o:@@:nao:@+}-$

Call with a, b, n on the stack, where n is the number of turns or a negative value for infinite output. Outputs a and b separated by a space.

As an explanation, here is how the stack evolves during runtime :

abn
nba
nbaa
naab
naabb
nabab
nab+
+nab
+n-
+-n

You can try it on the online interpreter with a positive amount of turns but you will need to use the official python interpreter to test the infinite mode.

$ python fish.py -c ':?!;1-r:n48*o:@@:nao:@+}-$' -t 0.01 -v 10 2 -1
10 2
12 8
20 4
24 16
40 8
48 32
80 16
96 64
160 32
192 128
320 64
384 256
640 128
768 512
1280 256
1536 1024
2560 512
3072 2048
5120 1024
6144 4096
10240 2048
12288 8192
20480 4096
24576 16384
40960 8192
49152 32768
81920 16384
98304 65536
163840 32768
196608 131072
327680 65536
393216 262144
655360 131072
786432 524288
1310720 262144
[...]


问:
Stretch the word
The input is a word of lowercase letters not separated by whitespace. A newline at the end is optional.

The same word must be output in a modified version: For each character, double it the second time it appears in the original word, triple it the third time etc.

Example input:

```<code>bonobo
</code>```

Example output:

```<code>bonoobbooo
</code>```

Standard I/O rules apply. The shortest code in bytes wins.

Tests provided by @Neil :

```<code>tutu -> tuttuu
queue -> queuuee
bookkeeper -> boookkkeeepeeer
repetitive -> repeetittiiveee
uncopyrightables -> uncopyrightables
abracadabra -> abraacaaadaaaabbrraaaaa
mississippi -> misssiisssssssiiipppiiii
</code>```

答:
Mathcad, 66 bytes

Unfortunately, Mathcad doesn't have particularly good string handling, so I've converted the input string to a vector and then used a (character code indexed) vector to keep track of the number of times a character is encountered, adding the character that number of times to a result vector.  Finally, the result vector is converted back to a string.  Quite lenghty unfortunately.

Note that Mathcad uses a 2D "whiteboard" interface, with a mix of normal text and operators; operators are normally entered via a toolbar or keyboard shortcut; for example, ctl-# enters the for loop operator, which comprises the keyword for, the element-of symbol and 3 empty "placeholders" for the iteration variable, range and body expressions respectively.   Typing [ after a variable name enters array index mode, Typing ' enters a matched pair of parentheses (mostly ... there are exceptions depending upon what else is in the surrounding expression)

Title: Stretch the word


答:
Grime v0.1, 34 bytes

```<code>M=\(M\)|\[M\]|\{M\}|\<M\>|MM|_
e`M
</code>```

Prints 1 for a match and 0 for no match.
Try it online!

Explanation

Grime is my 2D pattern-matching language designed for this challenge; it can also be used to match 1D strings.
This is my first answer with it.
I did modify Grime today, but only to change the character of one syntax element (` instead of ,), so it doesn't affect my score.

```<code>M=                         Define pattern called M that matches:
\(M\)|\[M\]|\{M\}|\<M\>      a smaller M inside matched brackets,
|MM                          or two smaller Ms concatenated,
|_                           or the empty pattern.
e`M                        Match the entire input against M.
</code>```

Title: Are the brackets fully matched?

Body:
Grime v0.1, 34 bytes

M=\(M\)|\[M\]|\{M\}|\<M\>|MM|_
e`M

Prints 1 for a match and 0 for no match.
Try it online!

Explanation

Grime is my 2D pattern-matching language designed for this challenge; it can also be used to match 1D strings.
This is my first answer with it.
I did modify Grime today, but only to change the character of one syntax element (` instead of ,), so it doesn't affect my score.

M=                         Define pattern called M that matches:
\(M\)|\[M\]|\{M\}|\<M\>      a smaller M inside matched brackets,
|MM                          or two smaller Ms concatenated,
|_                           or the empty pattern.
e`M                        Match the entire input against M.


问:
Tips for King of the Hill bots
What general tips do you have for creating a bot to participate in a King of the Hill challenge? What strategies do you use to go from considering the challenge to creating your bot? What data structures do you find most useful?

Please post one tip per answer.

答:
If team based, work together with your team

While you can usually write a bot that works solo to complete tasks to help your team, there's a much greater advantage when you coordinate both in and out of the game. A prime example of this can be seen in Red vs. Blue - Pixel Team Battlebots.

During development, teams were able to chat and discuss how to coordinate their bots to function better than alone. While technically the same bot, SphiNotPi3000 was written to work in tandem with another of itself, and was able to move in ways that accounted for the weaknesses it would have faced if it were on its own. The end result was that they were able to almost completely dominate the battlefield, even when it was just the two of them against the entire other team.

So outside the game, plan and coordinate with your teammates on what strategies to cover. Maybe someone has a bot that scans the map diagonally? Have yours scan horizontally (just an example). Inside the game, if the challenge allows for team communication, take advantage of it. In the battlebots game for example, you could send a message to your teammates on the position of bots outside their field of vision, and then encourage them to write their bots in a compatible way to make use of those signals.

Title: Tips for King of the Hill bots


问:
Snakify a String
A snakified string looks like this:

```<code>T AnE eOf ifi ing
h s x l A k e r
isI amp Sna dSt
</code>```

Your Task

Take a string s and a size n, then output the snakified string. The inputs ThisIsAnExampleOfaSnakifiedString and 3 would produce the example above.

Specifications

s will only contain ASCII characters between code points 33 and 126 inclusive (no spaces or newlines).

s will be between 1 and 100 characters long.

n is an integer representing the size of each output string segment. Each line of characters (up/down or left/right) that make up the curves in the "snake" is n characters long. See the test cases for examples.

n will be between 3 and 10 inclusive.

The output string always starts pointing downwards.

Trailing spaces on each line are allowed.

Trailing newlines at the end of the output are also allowed.

Leading spaces are not allowed.

code-golf means shortest code in bytes wins.

Test Cases

```<code>a 3

a

----------

Hello,World! 3

H Wor
e , l
llo d!

----------

ProgrammingPuzzlesAndCodeGolf 4

P  ngPu  Code
r  i  z  d  G
o  m  z  n  o
gram  lesA  lf

----------

IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot. 5

I   gramW   tStri   100Ch   gBeca   CaseW   DoesN
H   o   o   u   n   e   a   n   u   t   i   t   o
o   r   r   p   g   r   r   o   s   s   l   I   t
p   P   k   n   s   A   a   L   e   e   l   f   .
eYour   sForI   Which   cters   ThisT   FailI

----------

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 10

!        <=>?@ABCDE        `abcdefghi
"        ;        F        _        j
#        :        G        ^        k
$        9        H        ]        l
%        8        I        \        m
&        7        J        [        n
'        6        K        Z        o        ~
(        5        L        Y        p        }
)        4        M        X        q        |
*+,-./0123        NOPQRSTUVW        rstuvwxyz{
</code>```

答:
JavaScript (ES6), 143 bytes

```<code>(s,n)=>[...s].map((c,i)=>(a[x][y]=c,i/=n)&1?y++:i&2?x--:x++,a=[...Array(n--)].map(_=>[]),x=y=0)&&a.map(b=>[...b].map(c=>c||' ').join``).join`\n`
</code>```

Where \n represents a literal newline. Ungolfed:

```<code>function snakify(string, width) {
    var i;
    var result = new Array(width);
    for (i = 0; i < width; i++) result[i] = [];
    var x = 0;
    var y = 0;
    for (i = 0; i < string.length; i++) {
       result[x][y] = string[i];
       switch (i / (width - 1) & 3) {
       case 0: x++; break;
       case 1: y++; break;
       case 2: x--; break;
       case 3: y++; break;
    }
    for (i = 0; i < width; i++) {
        for (j = 0; j < r[i].length; j++) {
            if (!r[i][j]) r[i][j] = " ";
        }
        r[i] = r[i].join("");
    }
    return r.join("\n");
}
</code>```

Title: Snakify a String

Body:
JavaScript (ES6), 143 bytes

(s,n)=>[...s].map((c,i)=>(a[x][y]=c,i/=n)&1?y++:i&2?x--:x++,a=[...Array(n--)].map(_=>[]),x=y=0)&&a.map(b=>[...b].map(c=>c||' ').join``).join`\n`

Where \n represents a literal newline. Ungolfed:

function snakify(string, width) {
    var i;
    var result = new Array(width);
    for (i = 0; i < width; i++) result[i] = [];
    var x = 0;
    var y = 0;
    for (i = 0; i < string.length; i++) {
       result[x][y] = string[i];
       switch (i / (width - 1) & 3) {
       case 0: x++; break;
       case 1: y++; break;
       case 2: x--; break;
       case 3: y++; break;
    }
    for (i = 0; i < width; i++) {
        for (j = 0; j < r[i].length; j++) {
            if (!r[i][j]) r[i][j] = " ";
        }
        r[i] = r[i].join("");
    }
    return r.join("\n");
}


问:
Golf the xᵗʰ root of x
While bored in high-school (when I was half my current age...), I found that \$f(x) = x^{x^{-1}}\$ had some interesting properties, including e.g. that the maximum \$f\$ for \$0 ≤ x\$ is \$f(e)\$, and that the binding energy per nucleon of an isotope can be approximated as \$6 × f(x ÷ 21)\$...

Anyway, write the shortest function or program that calculates the xth root of x for any number in your language's domain.

Examples cases

For all languages

```<code>     -1   >       -1
   ¯0.2   >    -3125
   ¯0.5   >        4
    0.5   >     0.25
      1   >        1
      2   >    1.414
      e   >    1.444
      3   >    1.442
    100   >    1.047
  10000   >    1.001
</code>```

For languages that handle complex numbers

```<code>   -2   >        -0.7071i
    i   >            4.81
   2i   >    2.063-0.745i
 1+2i   >   1.820-0.1834i
 2+2i   >   1.575-0.1003i
</code>```

For languages that handle infinities

```<code>-1/∞   >   0    (or ∞ or ̃∞)
   0   >   0    (or 1 or ∞)
 1/∞   >   0
   ∞   >   1
  -∞   >   1
</code>```

For languages that handle both infinities and complex numbers

```<code> -∞-2i   >   1      (or ̃∞)
</code>```

 ̃∞ denotes directed infinity.

答:
Quetzalcoatl, 4 bytes

```<code>c.I?
</code>```

Explanation:

```<code>c    # Input
 .   # Duplicate
  I  # Inverse
   ? # Power
</code>```

Title: Golf the xᵗʰ root of x

Body:
Quetzalcoatl, 4 bytes

c.I?

Explanation:

c    # Input
 .   # Duplicate
  I  # Inverse
   ? # Power


答:
Fuzzy Octo Guacamole, <s>17</s> 16 bytes

```<code>^^(:C.Zs.aZ.s.-)
</code>```

This was hard to make, due to client-side errors. But I got it!

Walkthrough:

```<code>^^                # Get input twice, pushes it to the stack.
  (               # Start a infinite loop.
   :              # Prints the stack, and since it has [a,b] is just the output.
    C             # Copy the active stack to the inactive stack.
     .            # Shift the active stack.
      Z           # Reverse the stack.
       s          # Move the top item on the active stack to the top of the inactive.
        .         # Switch stacks again.
         a        # Add the top 2 items, giving the first new item.
          Z       # Reverse the stack, so we keep the 'a' safe and prepare for the 'b'.
           .      # Switch stacks.
            s     # Move the top item on the active stack to the top of the inactive stack.
             .    # Switch stacks.
              -   # Minus the top 2 items, giving 'b'.
               )  # End infinite loop.
</code>```

Title: The plus-minus sequence

Body:
Fuzzy Octo Guacamole, <s>17</s> 16 bytes

^^(:C.Zs.aZ.s.-)

This was hard to make, due to client-side errors. But I got it!

Walkthrough:

^^                # Get input twice, pushes it to the stack.
  (               # Start a infinite loop.
   :              # Prints the stack, and since it has [a,b] is just the output.
    C             # Copy the active stack to the inactive stack.
     .            # Shift the active stack.
      Z           # Reverse the stack.
       s          # Move the top item on the active stack to the top of the inactive.
        .         # Switch stacks again.
         a        # Add the top 2 items, giving the first new item.
          Z       # Reverse the stack, so we keep the 'a' safe and prepare for the 'b'.
           .      # Switch stacks.
            s     # Move the top item on the active stack to the top of the inactive stack.
             .    # Switch stacks.
              -   # Minus the top 2 items, giving 'b'.
               )  # End infinite loop.


答:
Ruby, 87 bytes

```<code>->s,n{p=0
a=(' '*(w=s.size)+$/)*n
w.times{|i|a[p]=s[i];p+=[w+1,1,-w-1,1][i/(n-1)%4]}
a}
</code>```

Some minor abuse of the rule Trailing spaces on each line are allowed. Each line of output is w characters long, plus a newline, where w is the length of the original string, i.e. long enough to hold the whole input. Hence there is quite a lot of unnecessary whitespace to the right for large n.

Ungolfed in test program

```<code>f=->s,n{
  p=0                            #pointer to where the next character must be plotted to
  a=(' '*(w=s.size)+$/)*n        #w=length of input. make a string of n lines of w spaces, newline terminated
  w.times{|i|                    #for each character in the input (index i)
    a[p]=s[i]                    #copy the character to the position of the pointer
    p+=[w+1,1,-w-1,1][i/(n-1)%4] #move down,right,up,right and repeat. change direction every n-1 characters
  }
a}                               #return a

puts $/,f['a',3]

puts $/,f['Hello,World!',3]

puts $/,f['ProgrammingPuzzlesAndCodeGolf',4]

puts $/,f['IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.',5]

puts $/,f['!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',10]
</code>```

Title: Snakify a String

Body:
A snakified string looks like this:

```<code>T AnE eOf ifi ing
h s x l A k e r
isI amp Sna dSt
</code>```

Your Task

Take a string s and a size n, then output the snakified string. The inputs ThisIsAnExampleOfaSnakifiedString and 3 would produce the example above.

Specifications

s will only contain ASCII characters between code points 33 and 126 inclusive (no spaces or newlines).

s will be between 1 and 100 characters long.

n is an integer representing the size of each output string segment. Each line of characters (up/down or left/right) that make up the curves in the "snake" is n characters long. See the test cases for examples.

n will be between 3 and 10 inclusive.

The output string always starts pointing downwards.

Trailing spaces on each line are allowed.

Trailing newlines at the end of the output are also allowed.

Leading spaces are not allowed.

code-golf means shortest code in bytes wins.

Test Cases

```<code>a 3

a

----------

Hello,World! 3

H Wor
e , l
llo d!

----------

ProgrammingPuzzlesAndCodeGolf 4

P  ngPu  Code
r  i  z  d  G
o  m  z  n  o
gram  lesA  lf

----------

IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot. 5

I   gramW   tStri   100Ch   gBeca   CaseW   DoesN
H   o   o   u   n   e   a   n   u   t   i   t   o
o   r   r   p   g   r   r   o   s   s   l   I   t
p   P   k   n   s   A   a   L   e   e   l   f   .
eYour   sForI   Which   cters   ThisT   FailI

----------

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ 10

!        <=>?@ABCDE        `abcdefghi
"        ;        F        _        j
#        :        G        ^        k
$        9        H        ]        l
%        8        I        \        m
&        7        J        [        n
'        6        K        Z        o        ~
(        5        L        Y        p        }
)        4        M        X        q        |
*+,-./0123        NOPQRSTUVW        rstuvwxyz{
</code>```

Body:
Ruby, 87 bytes

->s,n{p=0
a=(' '*(w=s.size)+$/)*n
w.times{|i|a[p]=s[i];p+=[w+1,1,-w-1,1][i/(n-1)%4]}
a}

Some minor abuse of the rule Trailing spaces on each line are allowed. Each line of output is w characters long, plus a newline, where w is the length of the original string, i.e. long enough to hold the whole input. Hence there is quite a lot of unnecessary whitespace to the right for large n.

Ungolfed in test program

f=->s,n{
  p=0                            #pointer to where the next character must be plotted to
  a=(' '*(w=s.size)+$/)*n        #w=length of input. make a string of n lines of w spaces, newline terminated
  w.times{|i|                    #for each character in the input (index i)
    a[p]=s[i]                    #copy the character to the position of the pointer
    p+=[w+1,1,-w-1,1][i/(n-1)%4] #move down,right,up,right and repeat. change direction every n-1 characters
  }
a}                               #return a

puts $/,f['a',3]

puts $/,f['Hello,World!',3]

puts $/,f['ProgrammingPuzzlesAndCodeGolf',4]

puts $/,f['IHopeYourProgramWorksForInputStringsWhichAre100CharactersLongBecauseThisTestCaseWillFailIfItDoesNot.',5]

puts $/,f['!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~',10]


答:
PowerShell v2+, <s>63</s> 62 bytes

```<code>param($a)for(;$a-ne$b){$a=($b=$a)-replace"\[\]|\(\)|<>|{}"}!$a
</code>```

Can't quite catch JavaScript, but is currently edging out the other non-esolangs.

Similar approach as other answers: a simple loop that continues so long as we can remove one of [], (), or <> (with several extraneous characters because we need to escape the regex specials). We use $b as a helper along the way to remember what our previous loop's $a was set as. An uninitialized variable is $null, so the first time the loop is encountered, $a is obviously not equal to $null.

At the end of the loop, $a is either empty or not, and the Boolean-not of that string is either True or False.

Example

```<code>PS C:\Tools\Scripts\golfing> .\are-the-brackets-fully-matched.ps1 "[({})]"
True

PS C:\Tools\Scripts\golfing> .\are-the-brackets-fully-matched.ps1 "[({])}"
False
</code>```

Title: Are the brackets fully matched?

Body:
PowerShell v2+, <s>63</s> 62 bytes

param($a)for(;$a-ne$b){$a=($b=$a)-replace"\[\]|\(\)|<>|{}"}!$a

Can't quite catch JavaScript, but is currently edging out the other non-esolangs.

Similar approach as other answers: a simple loop that continues so long as we can remove one of [], (), or <> (with several extraneous characters because we need to escape the regex specials). We use $b as a helper along the way to remember what our previous loop's $a was set as. An uninitialized variable is $null, so the first time the loop is encountered, $a is obviously not equal to $null.

At the end of the loop, $a is either empty or not, and the Boolean-not of that string is either True or False.

Example

PS C:\Tools\Scripts\golfing> .\are-the-brackets-fully-matched.ps1 "[({})]"
True

PS C:\Tools\Scripts\golfing> .\are-the-brackets-fully-matched.ps1 "[({])}"
False


答:
Be specific about the requirements to run your bot

Bots can be written in a variety of languages (and versions of those languages), so it helps everyone out when you:

Test it in the environment the OP specifies (or as close to it as you can).

Test it in a variety of other environments if possible (to help others who want to run it).

Be specific about the language and version you use, and explain how to run your bot.

As a bonus: if you are using a lesser known language, make a link to where people can download the binary/source to run it.

Title: Tips for King of the Hill bots

Body:
What general tips do you have for creating a bot to participate in a King of the Hill challenge? What strategies do you use to go from considering the challenge to creating your bot? What data structures do you find most useful?

Please post one tip per answer.


答:
Python, 67 bytes

lambda s:eval("s"+".replace('%s','')"*4%([],(),{},'<>')*len(s))==''
```
<p>Generates and evals an expression that looks like</p>
<pre class="lang-python prettyprint-override"><code>s.replace('[]','').replace('()','').replace('{}','').replace('<>','').replace('[]','').replace('()','').replace('{}','').replace('<>','')
</code>```

and checks if the result is empty.

Sp3000 saved 8 bytes by pointing out that [],(),{} can be subbed in without quotes because they're Python objects, and that two parens were unneeded.

Title: Are the brackets fully matched?

Body:
You must write a program or function that takes a string of brackets and outputs whether or not that string is fully matched. Your program should print a truthy or falsy value, and IO can be in any reasonable format.

Rules and definitions:

For the purpose of this challenge, a "bracket" is any of these characters: ()[]{}<>.

A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as

```<code>()
[]{}
</code>```

Or if every subelement inside of it is also matched.

```<code>[()()()()]
{<[]>}
(()())
</code>```

Subelements can also be nested several layers deep.

```<code>[(){<><>[()]}<>()]
<[{((()))}]>
</code>```

A string is considered "Fully matched" if and only if:

Every single character is a bracket,

Each pair of brackets has the correct opening and closing bracket and in the right order, and

Each bracket is matched.

You may assume the input will only contain printable ASCII.

Test IO

Here are some inputs that should return a truthy value:

```<code>()
[](){}<>
(((())))
({[<>]})
[{()<>()}[]]
[([]{})<{[()<()>]}()>{}]
</code>```

And here are some outputs that should return a falsy value:

```<code>(               Has no closing ')'
}{              Wrong order
(<)>            Each pair contains only half of a matched element
(()()foobar)    Contains invalid characters
[({}<>)>        The last bracket should be ']' instead of '>'
(((()))         Has 4 opening brackets, but only 3 closing brackets.
</code>```

As usual, this is code-golf, so standard loopholes apply, and shortest answer in bytes wins.

Body:
Python, 67 bytes

lambda s:eval("s"+".replace('%s','')"*4%([],(),{},'<>')*len(s))==''

Generates and evals an expression that looks like

s.replace('[]','').replace('()','').replace('{}','').replace('<>','').replace('[]','').replace('()','').replace('{}','').replace('<>','')

and checks if the result is empty.

Sp3000 saved 8 bytes by pointing out that [],(),{} can be subbed in without quotes because they're Python objects, and that two parens were unneeded.


答:
Finding Nash Equilibria

This is a very important concept when the KOTH involves a relatively simple set of decisions, involves only a few players (typically 2), and is deterministic.  A Nash equilibrium describes a "gridlock" position: if the two players have decided upon their two strategies, then the two players are effectively locked in those positions: either player changing their strategy simply creates additional vulnerabilities.

Examples of games where Nash equilibria are important are:

Rock-Paper-Scissors(-Lizard-Spock), in which an "unbeatable" strategy is random play

Morra, which has a "spectrum" of equilibria. Peter Taylor wrote a good example in his answer here.

Prisoner's Dilemma, a cooperative game notable for having an "everybody loses" gridlock

How to find an equilibrium

Finding an equilibrium actually is actually pretty simple for most simple games, and is often pretty intuitive.  A ton of detail about the various methods can be found on the internet.  The basic concept, which is normally applicable, is to create a list of possible strategies that the two players can use (the options provided by the game).  If one strategy is "dominated" by another, then that strategy can be removed from the list, and the process is repeated. By "domination," I mean that if strategy A always gives an equal-or-better result than strategy B, against all of the remaining opponent strategies, then strategy B can be removed from the list.

Example: Rock-Paper-Scissors

RPS has something called a "mixed" equilibrium, meaning that a distribution is involved.  Rather than playing the same move repeatedly (which will lead to quick defeat), the equilibrium is to play 1/3 rock, 1/3 paper, and 1/3 scissors in a random distribution.  If I play randomly, there is nothing my opponent can do to get an edge on me, period.  If my opponent chooses not to play randomly, then that only creates a vulnerability on his part.

Games with mixed equilibrium are probably the most common on PPCG, since they can take many forms (the only interesting game I can think of with a pure equilibrium is prisoner's dilemma).  I should note that the mixed equilibrium doesn't have to be uniformly random, simply something other than playing the same move every time.

Using this information

The Nash equilibrium of a game often represents the "baseline" from which you should try to operate.  In RPS, playing randomly guarantees a finishing spot around the middle of the pack.  In order to move to the top, you have to start identifying other player's weaknesses.

To do this, you should stick to the equilibrium when unsure of the opponent's weaknesses.  Once those weaknesses have been identified (you have detected that your opponent is not in equilibrium), then you need to gently shift out of equilibrium to take advantage of your opponent.  This action, in turn, creates weaknesses on your own part.  You must then detect when your opponent is changing his strategy, so that you can then stop the attack and resume random play.

Detecting variation from equilibrium

This is pretty difficult, and I am not an expert.  Variations can come in many forms:

Favoring some options above/below others for no reason, like an RPS player that plays rock twice as often as scissors, or one that avoids playing paper.  Some relatively simple statistics can detect this.

Basing a current move off past moves, in some predictable pattern.  This includes copy-cats, "beats what beats your last move" bots, or "cycling" bots.  This takes additional logic to detect, since the overall move distribution can be evenly-distributed, even though the moves aren't random.  You should attempt to take the record of moves and find correlations like "the move I made 2 turns ago and the move my opponent made now" and "the move he made 1 turn ago, and the move he made now", etc.

Bots whose move distribution is based off of yours.  The vulnerability in these bots is often not created (in a measurable quantity) until after you have yourself varied from a random distribution.  Generally, your own bot falls into this category.

Title: Tips for King of the Hill bots


答:
Jelly, 7 bytes

```<code>ṣ⁷µ=ḢZE
</code>```

This uses the same algorithm as @LevelRiverSt's Ruby answer. The actual algorithm fits in the last 4 bytes; the first 3 bytes are required to parse the input format.

Try it online!

How it works

```<code>ṣ⁷µ=ḢZE  Main link. Argument: t (string)

ṣ⁷       Split t at linefeeds..
  µ      Begin a new, monadic link. Argument: A (list of strings)
    Ḣ    Pop the first string of A.
   =     Compare all other strings in A with the first.
         = compares characters, so this yields a list of Booleans for each string.
         For a truthy input, all pairs of lines now have been transformed in lists
         of only 1's or only 0's. That means all columns must be equal.
     Z   Zip; transpose rows with columns.
      E  Check if all rows (former columns) are equal to each other.
</code>```

Title: Rectangle Detection

Body:
Jelly, 7 bytes

ṣ⁷µ=ḢZE

This uses the same algorithm as @LevelRiverSt's Ruby answer. The actual algorithm fits in the last 4 bytes; the first 3 bytes are required to parse the input format.

Try it online!

How it works

ṣ⁷µ=ḢZE  Main link. Argument: t (string)

ṣ⁷       Split t at linefeeds..
  µ      Begin a new, monadic link. Argument: A (list of strings)
    Ḣ    Pop the first string of A.
   =     Compare all other strings in A with the first.
         = compares characters, so this yields a list of Booleans for each string.
         For a truthy input, all pairs of lines now have been transformed in lists
         of only 1's or only 0's. That means all columns must be equal.
     Z   Zip; transpose rows with columns.
      E  Check if all rows (former columns) are equal to each other.


答:
Grime v0.1, 31 bytes

```<code>E=\0+|\1+
N=.+&E!
e`(E/N|N/E)#!
</code>```

Prints 1 for match and 0 for no match. Try it online!

Explanation

Grime is my 2D pattern matching language.
I did modify it today, but only to change the character of a syntax element (` instead of ,), so it doesn't affect my score.

I'm using a similar approach to that of Sp3000: an input is falsy if it contains a 2×N rectangle whose one row contains both 0 and 1, and the other row does not.

```<code>E=             Define a nonterminal E, which matches
  \0+|           a horizontal run of one or more 0s, OR
      \1+        a horizontal run of one or more 1s.
N=             Define a nonterminal N, which matches
  .+             a horizontal run of one or more characters,
    &E!          which is NOT matched by E (so contains both 0 and 1).
e`             Match entire input to this pattern:
            !    not
           #     contains
  (E/N|N/E)      E on top of N, or N on top of E
</code>```

Title: Rectangle Detection

Body:
Grime v0.1, 31 bytes

E=\0+|\1+
N=.+&E!
e`(E/N|N/E)#!

Prints 1 for match and 0 for no match. Try it online!

Explanation

Grime is my 2D pattern matching language.
I did modify it today, but only to change the character of a syntax element (` instead of ,), so it doesn't affect my score.

I'm using a similar approach to that of Sp3000: an input is falsy if it contains a 2×N rectangle whose one row contains both 0 and 1, and the other row does not.

E=             Define a nonterminal E, which matches
  \0+|           a horizontal run of one or more 0s, OR
      \1+        a horizontal run of one or more 1s.
N=             Define a nonterminal N, which matches
  .+             a horizontal run of one or more characters,
    &E!          which is NOT matched by E (so contains both 0 and 1).
e`             Match entire input to this pattern:
            !    not
           #     contains
  (E/N|N/E)      E on top of N, or N on top of E


答:
Pyth, <s>85</s> <s>74</s> 59 bytes

<s>Kl@Q0J0=Y*]d-+*@Q1K@Q1 1FNr1@Q1=XY-+*KNN1b;VK=XYJ@@Q0N=+J@[+K1 1-_K1 1).&3/N-@Q1 1;sY</s>

<s>=G@Q1=H@Q0KlHJ0=Y*]dt+*GKGFNr1G=XYt+*KNNb;VK=XYJ@HN=+J@[hK1t_K1).&3/NtG;sY</s>

```<code>Klz=Ym;+*QKQVQ=XYt+*KhNhNb;VK=XYZ@zN=+Z@[hK1_hK1).&3/NtQ;sY
</code>```

Thanks to @FryAmTheEggman for greatly helping me !

Golfed as much as I could. Try it here !
For some reason, line wrapping make the output weird. You may want to have a look at the output on full page

Explanation

Breathe a second, and focus.
This can be broken down in three sections, like almost any "classic" algorithm.

The first section

It's where variables are initialized. It can be splitted into two parts :

```<code>Klz=Ym;+*QKQ
Klz                Assign len(input[0]) to K. (length of input String)
   =Ym;+*QKQ       Assign an empty list to Y of length K*input[1]-input[1]-1, where input[1] is the size of the snake
                   (thus the height of the final string)
</code>```

the second part :

```<code>VQ=XYt+*KhNhNb;
VQ                       For N in range(0, input[1]), where input[1] is the size of the snake
  =                        Assign to Y. Y is implicit, it is the last variable we used.
   XYt+*KhNhNb               Y[K*N+N-1]="\n". Can be broken down in four parts :
   X                           Replace function. X <A: list> <B: int> <C: any> is A[B]=C
    Y                          A: The array we initialized in the first section.
     t+*KhNhN                  B: K*(N+1)+N+1 (N is the for loop variable)
             b                 C: Newline character ("\n")
              ;          End the loop.
</code>```

The second section

It contains the actual logic.

```<code>VK=XYZ@zN=+Z@[hK1_hK1).&3/NtQ;
VK                                         For N in range(0, K), where K is the length of the input string (see first section)
  =                                          Assign to Y. Y is implicit, it is the last variable we used.
   XYZ@zN                                    Same as in section 2. This is a replacement function. Y[Z] = input[0][N]. Z is initially 0.
         =+Z@[hK1_hK1).&3/NtQ                Again this can be broken down :
         =+Z                                   Add to Z
             [hK1_hK1)                         Array containing directions. Respectively [K+1, 1, -K-1, 1]
            @         .&3/NtQ                  Lookup in the array, on index .&3/N-@Q1 1:
                      .&3                        Bitwise AND. .& <int> <int>
                         /NtQ                    (input[1]-1)/N, where input[1] is the size of the snake
                             ;             End the loop
</code>```

The third section

This is the output part. Not really interesting...

```<code>sY    Join the array Y. Implicitly print.
</code>```

BONUS

I wrote the pyth program from this python script.

```<code>input=["ThisIsAnExampleOfASnakifiedString", 4];
width=len(input[0]);
height=input[1];
pointer=0;
directions = [width+1,1,-width-1,1] #Respectively Down, right, up, right (left is replaced by right because of snake's nature. Doesn't go left).
output=[' ' for i in range(0, width*height+height-1)];
for N in range(1, height):
    output[width*N+N-1]="\n";
for N in range(0, len(input[0])):
    output[pointer]=input[0][N];
    pointer+=directions[3&(N/(height-1))];
print "".join(output);
</code>```

Title: Snakify a String

Body:
Pyth, <s>85</s> <s>74</s> 59 bytes

<s>Kl@Q0J0=Y*]d-+*@Q1K@Q1 1FNr1@Q1=XY-+*KNN1b;VK=XYJ@@Q0N=+J@[+K1 1-_K1 1).&3/N-@Q1 1;sY</s>

<s>=G@Q1=H@Q0KlHJ0=Y*]dt+*GKGFNr1G=XYt+*KNNb;VK=XYJ@HN=+J@[hK1t_K1).&3/NtG;sY</s>

Klz=Ym;+*QKQVQ=XYt+*KhNhNb;VK=XYZ@zN=+Z@[hK1_hK1).&3/NtQ;sY

Thanks to @FryAmTheEggman for greatly helping me !

Golfed as much as I could. Try it here !
For some reason, line wrapping make the output weird. You may want to have a look at the output on full page

Explanation

Breathe a second, and focus.
This can be broken down in three sections, like almost any "classic" algorithm.

The first section

It's where variables are initialized. It can be splitted into two parts :

Klz=Ym;+*QKQ
Klz                Assign len(input[0]) to K. (length of input String)
   =Ym;+*QKQ       Assign an empty list to Y of length K*input[1]-input[1]-1, where input[1] is the size of the snake
                   (thus the height of the final string)

the second part :

VQ=XYt+*KhNhNb;
VQ                       For N in range(0, input[1]), where input[1] is the size of the snake
  =                        Assign to Y. Y is implicit, it is the last variable we used.
   XYt+*KhNhNb               Y[K*N+N-1]="\n". Can be broken down in four parts :
   X                           Replace function. X <A: list> <B: int> <C: any> is A[B]=C
    Y                          A: The array we initialized in the first section.
     t+*KhNhN                  B: K*(N+1)+N+1 (N is the for loop variable)
             b                 C: Newline character ("\n")
              ;          End the loop.

The second section

It contains the actual logic.

VK=XYZ@zN=+Z@[hK1_hK1).&3/NtQ;
VK                                         For N in range(0, K), where K is the length of the input string (see first section)
  =                                          Assign to Y. Y is implicit, it is the last variable we used.
   XYZ@zN                                    Same as in section 2. This is a replacement function. Y[Z] = input[0][N]. Z is initially 0.
         =+Z@[hK1_hK1).&3/NtQ                Again this can be broken down :
         =+Z                                   Add to Z
             [hK1_hK1)                         Array containing directions. Respectively [K+1, 1, -K-1, 1]
            @         .&3/NtQ                  Lookup in the array, on index .&3/N-@Q1 1:
                      .&3                        Bitwise AND. .& <int> <int>
                         /NtQ                    (input[1]-1)/N, where input[1] is the size of the snake
                             ;             End the loop

The third section

This is the output part. Not really interesting...

sY    Join the array Y. Implicitly print.

BONUS

I wrote the pyth program from this python script.

input=["ThisIsAnExampleOfASnakifiedString", 4];
width=len(input[0]);
height=input[1];
pointer=0;
directions = [width+1,1,-width-1,1] #Respectively Down, right, up, right (left is replaced by right because of snake's nature. Doesn't go left).
output=[' ' for i in range(0, width*height+height-1)];
for N in range(1, height):
    output[width*N+N-1]="\n";
for N in range(0, len(input[0])):
    output[pointer]=input[0][N];
    pointer+=directions[3&(N/(height-1))];
print "".join(output);


问:
Magic number of a given length
Your program must take an input (n for the purpose of description) and output all permutations of a number that is n digits long with no repeating digits, where each of the digits preceding and including its index are divisible by the place in the number that it falls.

You can read about magic numbers here.

Rules:

1 <= n <= 10

No digits may be repeated

The leading 0 must be present (if applicable)

The 1st through xth digit of the number (starting with the first character as 1) must be divisible by x, i.e. in 30685, 3 is divisible by 1, 30 is divisible by 2, 306 is divisible by 3, 3068 is divisible by 4, and 30685 is divislbe by 5.

The program must take an integer as input (through the command line, as a function argument, etc.) and print all permutations that satisfy the rules.

Output must be separated by 1 or more white space character

Permutations may start and with zero (so they're not technically magic numbers).

The order of output does not matter

You do not need to handle unexpected input

Least characters in bytes wins

Examples

Given 1:

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

Given 2:

```<code>02
04
06
08
10
12
14
16
18
20
24
26
28
30
32
34
36
38
40
42
46
48
50
52
54
56
58
60
62
64
68
70
72
74
76
78
80
82
84
86
90
92
94
96
98
</code>```

Given 10:

```<code>3816547290
</code>```

Credit to Pizza Hut & John H. Conway for the original puzzle (Option A).
Thanks to @Mego and @sp3000 for their links.

答:
JavaScript (Firefox 30-57), 77 bytes

```<code>f=n=>n?[for(s of f(n-1))for(c of"0123456789")if(s.search(c)+(s+c)%n<0)s+c]:[""]
</code>```

Edit: Saved 1 byte thanks to @edc65.

Title: Magic number of a given length

Body:
JavaScript (Firefox 30-57), 77 bytes

f=n=>n?[for(s of f(n-1))for(c of"0123456789")if(s.search(c)+(s+c)%n<0)s+c]:[""]

Edit: Saved 1 byte thanks to @edc65.