问:
"KNOT" or "NOT"?
Write a program that processes an ASCII art representation of a tangled string and decides whether or not it can be untangled into a simple loop. The tangle is represented using the characters - and | to represent horizontal and vertical segments, and + to represent corners. Places where the string passes over itself are represented as follows:

```<code>            |                           |
         -------                     ---|---
            |                           |
(Horizontal segment on top)   (Vertical segment on top)
</code>```

The ends of the string are connected together; there are no loose ends.

If your program decides that the string cannot be untangled into a simple loop, it should output the word KNOT. Otherwise, it should output the word NOT.

This is a code-golf challenge, so the shortest valid answer (measured in bytes of source code) will win.

Limits

The ASCII input will consist of up to 25 lines of 80 characters. You may assume that all the lines are padded with spaces to the same length.

Examples

Input:

```<code>+-------+    +-------+
|       |    |       |
|   +---|----+   +-------+
|   |   |        |   |   |
+-------|------------|---+
    |   |        |   |
    +---+        +---+
</code>```

Output:

```<code>KNOT
</code>```

Input:

```<code>+----------+
|          |
|    +--------------+
|    |     |        |
|    |   +-|----+   |
|    |   | |    |   |
|    +-----+    |   |
|        |      |   |
|        +------|---+
|               |
+---------------+
</code>```

Output:

```<code>NOT
</code>```

References

http://en.wikipedia.org/wiki/Knot_theory

http://en.wikipedia.org/wiki/Reidemeister_move

http://en.wikipedia.org/wiki/Unknotting_problem

答:
Python 3, <s>457</s> <s>316</s> 306 bytes

E=enumerate
V={'+'}
Q=[[(-j,i,k)for i,u in E(open(0))for j,v in E(u)for k in[{v}&V,'join'][u[j:j+2]=='|-']]]
while Q:
 a,b,c,d,*e=A=tuple(x//2for y,x in sorted((y,x)for x,y in E(Q.pop())));e or exit('NOT')
 if{A}-V:V|={A};Q+=[[c,d,a,b]+e,A,A[2:]+A[:2]][a<c<b<d:][c<a<d<b:]
 if b==d:Q=[[a,c]+e]
exit('KNOT')
```

<h2>Huh?</h2>

<p>The program first converts the knot to a rectangular diagram, which has the following restrictions:</p>

<ol>
<li>No two vertical or horizontal segments lie on the same line.</li>
<li>No vertical segment crosses over a horizontal segment.</li>
</ol>

<p>For example, the first test case is converted to the following rectangular diagram:</p>

```+-----------+
|           |
|           | +-------+
|           | |       |
| +-------+ | |       |
| |       | | |       |
| |     +---+ |       |
| |     | |   |       |
| |     | +---+       |
| |     |             |
| |     |       +-------+
| |     |       |     | |
+-----+ |       |     | |
  |   | |       |     | |
  | +---+       |     | |
  | | |         |     | |
  | | +-------------+ | |
  | |           |   | | |
  | |           | +---+ |
  | |           | | |   |
  | |           | | +---+
  | |           | |
  +-+           | |
                | |
                +-+
```

<p>which we uniquely represent by the sequence of y coordinates of the vertical segments, from right to left:</p>

```(5,10, 1,9, 8,10, 9,12, 5,12, 1,4, 0,3, 2,4, 3,7, 6,8, 7,11, 2,11, 0,6)
```

<p>It then searches for simplifications of the rectangular diagram as described in Ivan Dynnikov, “Arc-presentations of links. Monotonic simplification”, 2004.  Dynnikov proved that from any rectangular diagram of the unknot, there is a sequence of simplifying moves that ends at the trivial diagram.  Briefly, the allowed moves include:</p>

<ol>
<li>Cyclically permuting the vertical (or horizontal) segments;</li>
<li>Swapping consecutive vertical (or horizontal) segments under certain configuration constraints.</li>
<li>Replacing three adjacent vertices that lie in the very corner of the diagram with one vertex.</li>
</ol>

<p>See the paper for pictures.  This is not an obvious theorem; it does not hold if, say, Reidemeister moves that do not increase the number of crossings are used instead.  But for the particular kinds of simplifications above, it turns out to be true.</p>

<p>(We simplify the implementation by only permuting vertical segments, but also allowing the entire knot to be transposed to interchange horizontal with vertical.)</p>

<h2>Demo</h2>

```$ python3 knot.py <<EOF
+-------+    +-------+
|       |    |       |
|   +---|----+   +-------+
|   |   |        |   |   |
+-------|------------|---+
    |   |        |   |
    +---+        +---+
EOF
KNOT
$ python3 knot.py <<EOF
+----------+
|          |
|    +--------------+
|    |     |        |
|    |   +-|----+   |
|    |   | |    |   |
|    +-----+    |   |
|        |      |   |
|        +------|---+
|               |
+---------------+
EOF
NOT
$ python3 knot.py <<EOF  # the Culprit
        +-----+
        |     |
+-----------+ |
|       |   | |
|   +-+ | +---|-+
|   | | | | | | |
| +-|-------+ | |
| | | | | |   | |
+-|-+ | | +---+ |
  |   | |       |
  +---|---------+
      | |
      +-+
EOF
NOT
$ python3 knot.py <<EOF  # Ochiai unknot
    +-----+
    |     |
  +-|---------+
  | |     |   |
  | | +-+ |   |
  | | | | |   |
+-|-|---|-|-+ |
| | | | | | | |
| | | +---|---+
| | |   | | |
+-------+ | |
  | |     | |
  | +-------+
  |       |
  +-------+
EOF
NOT
$ python3 knot.py <<EOF  # Ochiai unknot plus trefoil
    +-----+ +-----+
    |     | |     |
  +-|---------+   |
  | |     | | |   |
  | | +-+ | +---+ |
  | | | | |   | | |
+-|-|---|-|-+ +---+
| | | | | | |   |
| | | +---|-----+
| | |   | | |
+-------+ | |
  | |     | |
  | +-------+
  |       |
  +-------+
EOF
KNOT
$ python3 knot.py <<EOF  # Thistlethwaite unknot
      +---------+
      |         |
    +---+ +---------+
    | | | |     |   |
    | +-------+ |   |
    |   | |   | |   |
    |   | | +---+   |
    |   | | | |     |
    |   | +-------+ |
    |   |   | |   | |
    |   +-------+ | |
    |       | | | | |
+-----------+ | | | |
|   |         | | | |
| +-----------+ | | |
| | |           | | |
| | +-------------+ |
| |             |   |
| |             +-----+
| |                 | |
| |                 +---+
| |                   | |
+---------------------+ |
  |                     |
  +---------------------+
EOF
NOT
$ python3 knot.py <<EOF  # (−3,5,7)-pretzel knot
      +-------------+
      |             |
    +-|-----+       |
    | |     |       |
  +-|-+   +-------+ |
  | |     | |     | |
+-|-+   +---+   +---+
| |     | |     | |
| |   +---+   +---+
| |   | |     | |
| | +---+   +---+
| | | |     | |
| +---+   +---+
|   |     | |
|   |   +---+
|   |   | |
|   | +---+
|   | | |
|   +---+
|     |
+-----+
EOF
KNOT
$ python3 knot.py <<EOF  # Gordian unknot
+-------------+                 +-------------+
|             |                 |             |
| +---------+ |                 | +---------+ |
| |         | |                 | |         | |
| | +-------------+         +-------------+ | |
| | |       | |   |         |   | |       | | |
| | | +---------+ |         | +---------+ | | |
| | | |     | | | |         | | | |     | | | |
| +-------+ | +-------+ +-------+ | +-------+ |
|   | |   | |   | |   | |   | |   | |   | |   |
+-------+ | +-------+ | | +-------+ | +-------+
    | | | |     | | | | | | | |     | | | |
    | +-------+ | | | | | | | | +-------+ |
    |   | |   | | | | | | | | | |   | |   |
    +-------+ | | | | | | | | | | +-------+
        | | | | | | | | | | | | | | | |
        | +-----+ | | | | | | +-----+ |
        |   | |   | | | | | |   | |   |
        +---------+ | | | | +---------+
            | |     | | | |     | |
          +---------+ | | +---------+
          | | |       | |       | | |
          | | +-----------------+ | |
          | |         | |         | |
          | +---------------------+ |
          |           | |           |
          +-----------+ +-----------+
EOF
NOT
```

Title: "KNOT" or "NOT"?

Body:
Python 3, <s>457</s> <s>316</s> 306 bytes

E=enumerate
V={'+'}
Q=[[(-j,i,k)for i,u in E(open(0))for j,v in E(u)for k in[{v}&V,'join'][u[j:j+2]=='|-']]]
while Q:
 a,b,c,d,*e=A=tuple(x//2for y,x in sorted((y,x)for x,y in E(Q.pop())));e or exit('NOT')
 if{A}-V:V|={A};Q+=[[c,d,a,b]+e,A,A[2:]+A[:2]][a<c<b<d:][c<a<d<b:]
 if b==d:Q=[[a,c]+e]
exit('KNOT')

Huh?

The program first converts the knot to a rectangular diagram, which has the following restrictions:

No two vertical or horizontal segments lie on the same line.

No vertical segment crosses over a horizontal segment.

For example, the first test case is converted to the following rectangular diagram:

+-----------+
|           |
|           | +-------+
|           | |       |
| +-------+ | |       |
| |       | | |       |
| |     +---+ |       |
| |     | |   |       |
| |     | +---+       |
| |     |             |
| |     |       +-------+
| |     |       |     | |
+-----+ |       |     | |
  |   | |       |     | |
  | +---+       |     | |
  | | |         |     | |
  | | +-------------+ | |
  | |           |   | | |
  | |           | +---+ |
  | |           | | |   |
  | |           | | +---+
  | |           | |
  +-+           | |
                | |
                +-+

which we uniquely represent by the sequence of y coordinates of the vertical segments, from right to left:

(5,10, 1,9, 8,10, 9,12, 5,12, 1,4, 0,3, 2,4, 3,7, 6,8, 7,11, 2,11, 0,6)

It then searches for simplifications of the rectangular diagram as described in Ivan Dynnikov, “Arc-presentations of links. Monotonic simplification”, 2004.  Dynnikov proved that from any rectangular diagram of the unknot, there is a sequence of simplifying moves that ends at the trivial diagram.  Briefly, the allowed moves include:

Cyclically permuting the vertical (or horizontal) segments;

Swapping consecutive vertical (or horizontal) segments under certain configuration constraints.

Replacing three adjacent vertices that lie in the very corner of the diagram with one vertex.

See the paper for pictures.  This is not an obvious theorem; it does not hold if, say, Reidemeister moves that do not increase the number of crossings are used instead.  But for the particular kinds of simplifications above, it turns out to be true.

(We simplify the implementation by only permuting vertical segments, but also allowing the entire knot to be transposed to interchange horizontal with vertical.)

Demo

$ python3 knot.py <<EOF
+-------+    +-------+
|       |    |       |
|   +---|----+   +-------+
|   |   |        |   |   |
+-------|------------|---+
    |   |        |   |
    +---+        +---+
EOF
KNOT
$ python3 knot.py <<EOF
+----------+
|          |
|    +--------------+
|    |     |        |
|    |   +-|----+   |
|    |   | |    |   |
|    +-----+    |   |
|        |      |   |
|        +------|---+
|               |
+---------------+
EOF
NOT
$ python3 knot.py <<EOF  # the Culprit
        +-----+
        |     |
+-----------+ |
|       |   | |
|   +-+ | +---|-+
|   | | | | | | |
| +-|-------+ | |
| | | | | |   | |
+-|-+ | | +---+ |
  |   | |       |
  +---|---------+
      | |
      +-+
EOF
NOT
$ python3 knot.py <<EOF  # Ochiai unknot
    +-----+
    |     |
  +-|---------+
  | |     |   |
  | | +-+ |   |
  | | | | |   |
+-|-|---|-|-+ |
| | | | | | | |
| | | +---|---+
| | |   | | |
+-------+ | |
  | |     | |
  | +-------+
  |       |
  +-------+
EOF
NOT
$ python3 knot.py <<EOF  # Ochiai unknot plus trefoil
    +-----+ +-----+
    |     | |     |
  +-|---------+   |
  | |     | | |   |
  | | +-+ | +---+ |
  | | | | |   | | |
+-|-|---|-|-+ +---+
| | | | | | |   |
| | | +---|-----+
| | |   | | |
+-------+ | |
  | |     | |
  | +-------+
  |       |
  +-------+
EOF
KNOT
$ python3 knot.py <<EOF  # Thistlethwaite unknot
      +---------+
      |         |
    +---+ +---------+
    | | | |     |   |
    | +-------+ |   |
    |   | |   | |   |
    |   | | +---+   |
    |   | | | |     |
    |   | +-------+ |
    |   |   | |   | |
    |   +-------+ | |
    |       | | | | |
+-----------+ | | | |
|   |         | | | |
| +-----------+ | | |
| | |           | | |
| | +-------------+ |
| |             |   |
| |             +-----+
| |                 | |
| |                 +---+
| |                   | |
+---------------------+ |
  |                     |
  +---------------------+
EOF
NOT
$ python3 knot.py <<EOF  # (−3,5,7)-pretzel knot
      +-------------+
      |             |
    +-|-----+       |
    | |     |       |
  +-|-+   +-------+ |
  | |     | |     | |
+-|-+   +---+   +---+
| |     | |     | |
| |   +---+   +---+
| |   | |     | |
| | +---+   +---+
| | | |     | |
| +---+   +---+
|   |     | |
|   |   +---+
|   |   | |
|   | +---+
|   | | |
|   +---+
|     |
+-----+
EOF
KNOT
$ python3 knot.py <<EOF  # Gordian unknot
+-------------+                 +-------------+
|             |                 |             |
| +---------+ |                 | +---------+ |
| |         | |                 | |         | |
| | +-------------+         +-------------+ | |
| | |       | |   |         |   | |       | | |
| | | +---------+ |         | +---------+ | | |
| | | |     | | | |         | | | |     | | | |
| +-------+ | +-------+ +-------+ | +-------+ |
|   | |   | |   | |   | |   | |   | |   | |   |
+-------+ | +-------+ | | +-------+ | +-------+
    | | | |     | | | | | | | |     | | | |
    | +-------+ | | | | | | | | +-------+ |
    |   | |   | | | | | | | | | |   | |   |
    +-------+ | | | | | | | | | | +-------+
        | | | | | | | | | | | | | | | |
        | +-----+ | | | | | | +-----+ |
        |   | |   | | | | | |   | |   |
        +---------+ | | | | +---------+
            | |     | | | |     | |
          +---------+ | | +---------+
          | | |       | |       | | |
          | | +-----------------+ | |
          | |         | |         | |
          | +---------------------+ |
          |           | |           |
          +-----------+ +-----------+
EOF
NOT


问:
Smallest groups in an array

Introduction

Let's observe the following array:

```<code>[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]
</code>```

A group consists of the same digits next to each other. In the above array, there are 5 different groups:

```<code>[1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1]

 1, 1, 1
          2, 2
                1, 1, 1, 1
                            2, 2, 2
                                     1, 1, 1
</code>```

The smallest group of these is [2, 2], so we output [2, 2].

Let's take another example:

```<code>[3, 3, 3, 4, 4, 4, 4, 5, 5, 4, 4, 3, 3, 4, 4]

 3, 3, 3
          4, 4, 4, 4
                      5, 5
                            4, 4
                                  3, 3
                                        4, 4
</code>```

You can see that there are multiple groups with the same length. The smallest groups are:

```<code>[3, 3], [4, 4], [4, 4] and [5, 5].
</code>```

So we just output [3, 3], [4, 4], [4, 4], [5, 5] in any reasonable format. You may output these in any order.

The Task

Given an array consisting of only positive integers, output the smallest group(s) from the array. You can assume that the array will contain at least 1 integer.

Test cases

```<code>Input: [1, 1, 2, 2, 3, 3, 4]
Output: [4]

Input: [1]
Output: [1]

Input: [1, 1, 10, 10, 10, 100, 100]
Output: [1, 1], [100, 100]
</code>```

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

ContentLicense: CC BY-SA 3.0

Title: Smallest groups in an array

Body:
JavaScript (ES6), 113 bytes

a=>a.map(n=>n==c[0]?c.push(n):b.push(c=[n]),c=b=[])&&b.sort((a,b)=>a[l]-b[l],l='length').filter(e=>e[l]==b[0][l])


问:
Automatic house-builder
Automatic house building nanobots have been fabricated, and it's your job to code them.

Here is the house created by input 7 4 2

```<code>  /-----/|
 /     / |
|-----|  |
|     |  |
|     | /
|_____|/
</code>```

The input is a string containing the house's dimensions.

7 is the width.

```<code>|_____|

---7---
</code>```

4 is the height.

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

2 is the depth

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

Given this input, can you create the house?

Your code must be as small as possible so that it can fit in the robots.

Notes

The smallest dimensions you will be given as input are 3 2 2. Your program can do anything with dimensions that are smaller than 3 2 2.

Testcases

```<code>3 2 10

          /-/|
         / / |
        / / /
       / / /
      / / /
     / / /
    / / /
   / / /
  / / /
 / / /
|-| /
|_|/
</code>```

答:
JavaScript (ES6), 169 bytes

```<code>(w,h,d)=>[...Array(d+h--)].map((_,i)=>` `[r=`repeat`](i<d&&d-i)+(c=`|/`[+(i<d)])+` _-`[i&&i-d?h+d-i?0:1:2][r](w-2)+c+` `[r]((i<d?i:d)-(i>h&&i-h))+`|/`[+(i>h)]).join`\n`
</code>```

Where \n represents a literal newline character. Explanation:

```<code>(w,h,d,)=>                          Parameters
[...Array(d+h--)].map((_,i)=>       Loop over total height = d + h
 ` `[r=`repeat`](i<d&&d-i)+         Space before roof (if applicable)
 (c=`|/`[+(i<d)])+                  Left wall/roof edge
 ` _-`[i&&i-d?h+d-i?0:1:2][r](w-2)+ Space, floor or eaves between walls
 c+                                 Right wall/roof edge (same as left)
 ` `[r]((i<d?i:d)-(i>h&&i-h))+      Right wall
 `|/`[+(i>h)]                       Back wall/floor edge
).join`                             Join everything together
`
</code>```

Edit: Saved 2 bytes thanks to @jrich.

Title: Automatic house-builder

Body:
JavaScript (ES6), 169 bytes

(w,h,d)=>[...Array(d+h--)].map((_,i)=>` `[r=`repeat`](i<d&&d-i)+(c=`|/`[+(i<d)])+` _-`[i&&i-d?h+d-i?0:1:2][r](w-2)+c+` `[r]((i<d?i:d)-(i>h&&i-h))+`|/`[+(i>h)]).join`\n`

Where \n represents a literal newline character. Explanation:

(w,h,d,)=>                          Parameters
[...Array(d+h--)].map((_,i)=>       Loop over total height = d + h
 ` `[r=`repeat`](i<d&&d-i)+         Space before roof (if applicable)
 (c=`|/`[+(i<d)])+                  Left wall/roof edge
 ` _-`[i&&i-d?h+d-i?0:1:2][r](w-2)+ Space, floor or eaves between walls
 c+                                 Right wall/roof edge (same as left)
 ` `[r]((i<d?i:d)-(i>h&&i-h))+      Right wall
 `|/`[+(i>h)]                       Back wall/floor edge
).join`                             Join everything together
`

Edit: Saved 2 bytes thanks to @jrich.


问:
Polygonal numbers
A polygonal number is the number of dots in a k-gon of size n.

You will be given n and k, and your task is to write a program/function that outputs/prints the corresponding number.

Scoring

This is code-golf. Shortest solution in bytes wins.

Example

The 3rd hexagon number (k=6, n=3) is 28 because there are 28 dots above.

Testcases

Can be generated from this Pyth test suite.

Usage: two lines per testcase, n above, k below.

```<code>n    k  output
10   3  55
10   5  145
100  3  5050
1000 24 10990000
</code>```

Further information

In Wikipedia: https://en.wikipedia.org/wiki/Polygonal_number

In Wolfram Mathworld: http://mathworld.wolfram.com/PolygonalNumber.html

In OEIS Wiki: http://oeis.org/wiki/Polygonal_numbers

OEIS sequences for n-gonal numbers for various n: 3 (A000217), 4 (A000290), 5 (A000326), 6 (A000384), 7 (A000566), 8 (A000567), 9 (A001106), 10 (A001107), 11 (A051682), 12 (A051624), 13 (A051865), 14 (A051866), 15 (A051867), 16 (A051868), 17 (A051869), 18 (A051870), 19 (A051871), 20 (A051872), 21 (A051873), 22 (A051874), 23 (A051875), 24 (A051876)

答:
Hexagony, 25 bytes

```<code>?(({"+!@/"*'+{/?('*})/2':
</code>```

Unfolded:

```<code>   ? ( ( {
  " + ! @ /
 " * ' + { /
? ( ' * } ) /
 2 ' : . . .
  . . . . .
   . . . .
</code>```

Reads k first and n second (using any separator).

Try it online!

Explanation

The program is completely linear, but as usual in Hexagony, the order of execution is all over the place:

The paths are executed in the order grey, dark blue, red, light blue, dark green, pink. As you can see, the three / only act to redirect the flow. Also, the . are no-ops. Stripping all hexagonal fanciness, the resulting linear program is:

```<code>?(({?('*})"*'+{2':"+!@
</code>```

This computes the standard formula

like most of the other answers. It does so using the following five memory edges, with the memory pointer (MP) starting as shown in red:

Here's how this is done:

```<code>?    Read integer input s into edge A.
((   Decrement twice to get (s-2).
{    Move the MP forwards onto edge B.
?    Read integer input n into edge B.
(    Decrement to get (n-1).
'    Move the MP backwards onto edge C.
*    Multiply edges A and B to store the result (s-2)(n-1) in edge C.
}    Move the MP forwards onto edge B.
)    Increment to restore the value n.
"    Move the MP backwards onto edge A.
*    Multiply edge B and C to store the result (s-2)(n-1)n in edge A.
'    Move the MP backwards onto edge D.
+    Add edges E (initially 0) and A to copy (s-2)(n-1)n into edge D.
{    Move the MP forwards onto edge E.
2    Set the memory edge to value 2.
'    Move the MP backwards onto edge A.
:    Divide edge D by edge E to store (s-2)(n-1)n/2 in edge A.
"    Move the MP backwards onto edge C.
+    Add edges A and B to store (s-2)(n-1)n/2+n in edge C.
!    Print as integer.
@    Terminate the program.
</code>```

Title: Polygonal numbers

Body:
Hexagony, 25 bytes

?(({"+!@/"*'+{/?('*})/2':

Unfolded:

   ? ( ( {
  " + ! @ /
 " * ' + { /
? ( ' * } ) /
 2 ' : . . .
  . . . . .
   . . . .

Reads k first and n second (using any separator).

Try it online!

Explanation

The program is completely linear, but as usual in Hexagony, the order of execution is all over the place:

The paths are executed in the order grey, dark blue, red, light blue, dark green, pink. As you can see, the three / only act to redirect the flow. Also, the . are no-ops. Stripping all hexagonal fanciness, the resulting linear program is:

?(({?('*})"*'+{2':"+!@

This computes the standard formula

like most of the other answers. It does so using the following five memory edges, with the memory pointer (MP) starting as shown in red:

Here's how this is done:

?    Read integer input s into edge A.
((   Decrement twice to get (s-2).
{    Move the MP forwards onto edge B.
?    Read integer input n into edge B.
(    Decrement to get (n-1).
'    Move the MP backwards onto edge C.
*    Multiply edges A and B to store the result (s-2)(n-1) in edge C.
}    Move the MP forwards onto edge B.
)    Increment to restore the value n.
"    Move the MP backwards onto edge A.
*    Multiply edge B and C to store the result (s-2)(n-1)n in edge A.
'    Move the MP backwards onto edge D.
+    Add edges E (initially 0) and A to copy (s-2)(n-1)n into edge D.
{    Move the MP forwards onto edge E.
2    Set the memory edge to value 2.
'    Move the MP backwards onto edge A.
:    Divide edge D by edge E to store (s-2)(n-1)n/2 in edge A.
"    Move the MP backwards onto edge C.
+    Add edges A and B to store (s-2)(n-1)n/2+n in edge C.
!    Print as integer.
@    Terminate the program.


问:
KOTH: Every coin has two sides
Final results available

Introduction

After my previous KOTH with heavy themes (fantasy war, worldwide pandemic...), I'm back with a new lighthearted game. This time, you are facing off in a "board game-like" situation. A pile of upside down coins is placed at the center of a really big table, and you are determined to get your share of the loot!

Glossary

Coins: Tokens that can either be flipped or unflipped.

  Unflipped: Coins placed on the table with their value pointing down. This is the default state of the coins.

  Flipped: Coins placed on the table with their value pointing up.

  Local: Refers to your pile of coins.

  Global: Refers to the pile of coins at the center.

Principle

At the start of the game, each player starts with 0 points and 0 coins (flipped or unflipped). The game is turn-based. During their turn, players can take up to 3 actions interacting either with the pile of coins at the center of the table, their own pile of coins or with other players.

Play order is defined randomly at the start of the game. The order of the players in the argument list represents the turn order, and it goes from left to right in that list. "Next" and "Previous" refer respectively to "on the right in that list" and "on the left in that list" with a loop if you're the last of either side.

The game lasts for 50 rounds or until there are 0 coins at the center at the end of a player turn (meaning that you will finish your 3 actions even if the pile is empty after your first action, and you can put back coins to let the game continue). The starting number of global coins is defined randomly with this formula:

```<code>(2 ^ nb_players) + (nb_players * 10) - random(1 + (nb_players ^ 2))`
</code>```

Each action will get you points (or make you lose some) and at the end of the game, each coin you have will be added to your points (-1 for unflipped, +2 for flipped). The player with the highest score wins.

The controller provides you with input via command arguments, and your program has to output via stdout.

Syntax

Input

Each time your program is called, it will receive arguments in this format:

Round;YourPlayerId;Coins;PlayerId_Points_Flipped_Unflipped;PlayerId_Points_Flipped_Unflipped;...

Rounds are 1-indexed.

Example input

6;2;52;1_20_3_12;0_-2_0_1;2_12_1_0

Here, you see it is the 6th round and you are player 2. There are 52 coins in the central pile. You have 12 points, 1 flipped coin and 0 unflipped coin. Points can be negative.

Output

You have to output three characters (no space, no separator), which each correspond to one action you'll take this turn. The order of the characters determine the order of the actions. You can output the same actions multiple times. In case there is not enough coins to complete your action, it will use the maximum of available coins and count points only for the coins used.

N: Do Nothing

1: Take 1 coin from the central pile [Effects: +1 local unflipped / -1 point / -1 global unflipped]

2: Take 2 coins from the central pile [Effects: +2 local unflipped / -2 points / -2 global unflipped]

3: Take 3 coins from the central pile [Effects: +3 local unflipped / -3 points / -3 global unflipped]

A: Put back 1 coin from your pile [Effects: -1 local unflipped / +1 point / +1 global unflipped]

B: Put back 2 coins from your pile [Effects: -2 local unflipped / +2 points / +2 global unflipped]

C: Put back 3 coins from your pile [Effects: -3 local unflipped / +3 points / +3 global unflipped]

X: Remove 1 coin from your pile [Effects: -1 local unflipped / 0 point]

Y: Remove 2 coins from your pile [Effects: -2 local unflipped / 0 point]

Z: Remove 3 coins from your pile [Effects: -3 local unflipped / 0 point]

R: Rotate coins to previous player [Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]

T: Rotate coins to next player [Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]

F: Flip 1 coin [Effects: -1 local unflipped / +1 local flipped / +2 point]

U: Unflip 1 coin [Effects: +1 local unflipped / -1 local flipped / -2 point]

Example output

2FF : Takes two coins and flips two coin, scoring -2 + 2 + 2 = 2 points

If your output is incorrect, controller will assume NNN.

Controller

You can find the controller on GitHub. It also contains two samplebots, written in Java.
To make it run, check out the project and open it in your Java IDE. The entry point in the main method of the class Game. Java 8 required.

To add bots, first you need either the compiled version for Java (.class files) or the sources for interpreted languages. Place them in the root folder of the project. Then, create a new Java class in the players package (you can take example on the already existing bots). This class must implement Player to override the method String getCmd(). The String returned is the shell command to run your bots. You can for example make a Ruby bot work with this command : return "C:\Ruby\bin\ruby.exe MyBot.rb";. Finally, add the bot in the players array at the top of the Game class.

Rules

Bots should not be written to beat or support specific other bots.

Writing to files is allowed. Please write to"yoursubmissionname.txt", the folder will be emptied before a game starts. Other external resources are disallowed.

Your submission has 1 second to respond.

Provide commands to compile and run your submissions.

Supported Languages

I'll try and support every language, but it needs to be available online for free. Please provide instructions for installation if you're not using a "mainstream" language.

As of right now, I can run : Java 6-7-8, PHP, Ruby, Perl, Python 2-3, Lua, R, node.js, Haskell, Kotlin, C++ 11.

Final results

These are the results of 100 games (points are added up) :

```<code>1. BirdInTheHand: 1017790
2. Balance: 851428
3. SecondBest: 802316
4. Crook: 739080
5. Jim: 723440
6. Flipper: 613290
7. Wheeler: 585516
8. Oracle: 574916
9. SimpleBot: 543665
10. TraderBot: 538160
11. EgoisticalBot: 529567
12. RememberMe: 497513
13. PassiveBot: 494441
14. TheJanitor: 474069
15. GreedyRotation: 447057
16. Devil: 79212
17. Saboteur: 62240
</code>```

Individual results of the games are available here : http://pasted.co/63f1e924 (with starting coins and number of rounds per game).

A bounty of 50 reputations is awarded to the winner : Bird In The Hand by Martin Büttner.

Thank you all for your participation, see you next KOTH~

答:
SimpleBot, Python 3

SimpleBot is, well, simple. He's worked out one strategy and he's going to stick with it.

To run:

```<code>python3 main.py
</code>```

where the contents of the main.py file is:

```<code>def main():
    print("3RF")

if __name__ == "__main__":
    main()
</code>```

Title: KOTH: Every coin has two sides

Body:
SimpleBot, Python 3

SimpleBot is, well, simple. He's worked out one strategy and he's going to stick with it.

To run:

python3 main.py

where the contents of the main.py file is:

def main():
    print("3RF")

if __name__ == "__main__":
    main()


问:
Random word-sentence-story generator
This question got me nostalgic: Build a word generator!

In the '80s I wrote a simple word generator in under 42kB (code and working memory) that would take a collection of strings and use them to create new words and phrases.

Your task is to recreate this program in as few bytes as possible, with a few minor updates.

Your program will take the input and ensure that there are two spaces after each sentence. Each sentence should end with a full-stop (.). There must not be three consecutive spaces anywhere in the text. Line breaks should be replaced by a single space. There should only be two spaces after a sentence and nowhere else.

Record the number of times each character triplet appears. If you're using regex to break up the text /\X/ is a good way to match a Unicode glyph (could be multiple codepoints, not necessarily a single codepoint). For the purposes of counting, assume that there are two spaces at the start of the text and two spaces at the end.

Hopefully, you now have some good data to work with! Randomly select a triplet where the first two characters are both spaces. For example, if the only two matching triplets are [' ', ' ', 'I'] => 3 and [' ', ' ', 'A'] => 7 there should be a 30% chance of selecting I and a 70% chance of selecting A. Shift the characters along and randomly select one of the next triplets. If A was the first character selected the next triplets might be [' ', 'A', 'n'] => 2, [' ', 'A', 't'] => 2 and [' ', 'A', 's'] => 3. Randomly select one using the correct weightings and so on. Repeat until the last two characters are both spaces, then output the string generated if it's 100 characters or longer. If the output is less than 100 characters, repeat the process again, adding to the existing string until it is at least 100 characters long.

You should end up with output something like below, which looks almost like the input language. As my test input I used the first chapter of Charles Dickens' A Tale of Two Cities but you can use any text you feel like. Please provide a link to your input text (preferably not copyrighted) and a sample of the output.

In harithe dir, in hadede Fards fouses, by we aws, mand by nouse St. Merty exce, he th at ing ithe inceir farce, a Capir bod day, one defor ond rodmane of the ce witsethe after seas a pleark parison a prion to eves hund Parglairty the beere tielaires, and wrece to ente comses itic plaw andozene hich tat andiver, a he pent wer thneople, the werseved froads se sebron theire mands inge Woodmage larestown ther Ligh, sed and was the withaved broce pers. Brity-fired of bust a din humakings th, incre pas of the amonoblis the a kne Chrooteres, to offle ound lies yeargland this thing by on the goil ituarivesdozen, moolurd instive the whe only a king was thelfe one divery. Und the intren a king thiging ors, and he tow, afty out pas musears, thot he in aces, it it Fran, tho the blets be anglaters ouseticiodmand whimeng was by the primed tord a ce a dirience.

TL;DR

Build sentences from test input by analysing the frequency of the character triplets, and using those frequencies to randomly select each character in sequence.

You can pre-format your text to make sure it matches the input requirements. It doesn't have to contribute to your byte-count.

If your language can't cope with Unicode at all, limit the input to ASCII characters. Ideally, your program should be able to cope with combining marks (accents and the like) if they are encoded separately but it doesn't have to. It shouldn't affect the output much, although it's possible you might get weird output in rare cases. e.g. if é is encoded as two codepoints, e+combining acute accent, it SHOULD (but doesn't HAVE to) treat it as a single glyph.

答:
Python 2.7, <s>156</s> <s>149</s> <s>135</s> 131 bytes

Screw efficiency, as long as it's short.

Saved 7 bytes thanks to @TuukkaX on the import statement

Saved 14 bytes thanks to @KevinLau-notKenny for negative list indice trick and if statement.

Saved 4 bytes by changing the randint

Notice that the second level uses tabs, but SE renders as 4 spaces.

```<code>from random import*
def r(i):
 o='  '
 while len(o)<100or o[-2:]!='  ':
    x=randint(2,len(i))
    if i[x-2:x]==o[-2:]:o+=i[x]
 return o
</code>```

Title: Random word-sentence-story generator

Body:
Python 2.7, <s>156</s> <s>149</s> <s>135</s> 131 bytes

Screw efficiency, as long as it's short.

Saved 7 bytes thanks to @TuukkaX on the import statement

Saved 14 bytes thanks to @KevinLau-notKenny for negative list indice trick and if statement.

Saved 4 bytes by changing the randint

Notice that the second level uses tabs, but SE renders as 4 spaces.

from random import*
def r(i):
 o='  '
 while len(o)<100or o[-2:]!='  ':
    x=randint(2,len(i))
    if i[x-2:x]==o[-2:]:o+=i[x]
 return o


问:
Encrypting and Decrypting Challenge

Encrypting Challenge

Your encrypting program must be able to do following things:

Input password

Generate random key

Encrypt random key with set key

Then, the decrypting program must be able to these things:

Input encrypted password

Input encrypted random key

Decrypt random key

Decrypt password with decrypted random key

Print password

The encryption must be setted with the key. It must be a table encryption or a encryption which makes the unencrypted values  to a part of the key.
This is code-golf. The shortest program wins!

答:
Pyth, 16+16 = 32 bytes

Encryption:

```<code>s@LG+VxLGQxLG*zl
</code>```

Try it online!

Decryption:

```<code>s@LG-VxLGQxLG*zl
</code>```

Try it online!

Uses Vigenère cipher.

Title: Encrypting and Decrypting Challenge

Body:
Pyth, 16+16 = 32 bytes

Encryption:

s@LG+VxLGQxLG*zl

Try it online!

Decryption:

s@LG-VxLGQxLG*zl

Try it online!

Uses Vigenère cipher.


答:
Flipper, Python 2

Flipper gathers coins and tries to turn unflipped to flipped. Flipper is not a smart player but tries to be a positive force in the game.

import sys, random

# process input data (not used here):
args = sys.argv[1].split(';')
rounds, myid, coins = map(int, args[:3])
players = [map(int, data.split('_')) for data in args[3:]]

# implement strategy using multiples of 'N123ABCXYZRTFU':
options = '12333FFFFFFFFFFF'
print ''.join(random.choice(options) for i in range(3))
```

Flipper just needs the python flipper.py <arg> to run.

Title: KOTH: Every coin has two sides

Body:
Final results available

Introduction

After my previous KOTH with heavy themes (fantasy war, worldwide pandemic...), I'm back with a new lighthearted game. This time, you are facing off in a "board game-like" situation. A pile of upside down coins is placed at the center of a really big table, and you are determined to get your share of the loot!

Glossary

Coins: Tokens that can either be flipped or unflipped.

  Unflipped: Coins placed on the table with their value pointing down. This is the default state of the coins.

  Flipped: Coins placed on the table with their value pointing up.

  Local: Refers to your pile of coins.

  Global: Refers to the pile of coins at the center.

Principle

At the start of the game, each player starts with 0 points and 0 coins (flipped or unflipped). The game is turn-based. During their turn, players can take up to 3 actions interacting either with the pile of coins at the center of the table, their own pile of coins or with other players.

Play order is defined randomly at the start of the game. The order of the players in the argument list represents the turn order, and it goes from left to right in that list. "Next" and "Previous" refer respectively to "on the right in that list" and "on the left in that list" with a loop if you're the last of either side.

The game lasts for 50 rounds or until there are 0 coins at the center at the end of a player turn (meaning that you will finish your 3 actions even if the pile is empty after your first action, and you can put back coins to let the game continue). The starting number of global coins is defined randomly with this formula:

```<code>(2 ^ nb_players) + (nb_players * 10) - random(1 + (nb_players ^ 2))`
</code>```

Each action will get you points (or make you lose some) and at the end of the game, each coin you have will be added to your points (-1 for unflipped, +2 for flipped). The player with the highest score wins.

The controller provides you with input via command arguments, and your program has to output via stdout.

Syntax

Input

Each time your program is called, it will receive arguments in this format:

Round;YourPlayerId;Coins;PlayerId_Points_Flipped_Unflipped;PlayerId_Points_Flipped_Unflipped;...

Rounds are 1-indexed.

Example input

6;2;52;1_20_3_12;0_-2_0_1;2_12_1_0

Here, you see it is the 6th round and you are player 2. There are 52 coins in the central pile. You have 12 points, 1 flipped coin and 0 unflipped coin. Points can be negative.

Output

You have to output three characters (no space, no separator), which each correspond to one action you'll take this turn. The order of the characters determine the order of the actions. You can output the same actions multiple times. In case there is not enough coins to complete your action, it will use the maximum of available coins and count points only for the coins used.

N: Do Nothing

1: Take 1 coin from the central pile [Effects: +1 local unflipped / -1 point / -1 global unflipped]

2: Take 2 coins from the central pile [Effects: +2 local unflipped / -2 points / -2 global unflipped]

3: Take 3 coins from the central pile [Effects: +3 local unflipped / -3 points / -3 global unflipped]

A: Put back 1 coin from your pile [Effects: -1 local unflipped / +1 point / +1 global unflipped]

B: Put back 2 coins from your pile [Effects: -2 local unflipped / +2 points / +2 global unflipped]

C: Put back 3 coins from your pile [Effects: -3 local unflipped / +3 points / +3 global unflipped]

X: Remove 1 coin from your pile [Effects: -1 local unflipped / 0 point]

Y: Remove 2 coins from your pile [Effects: -2 local unflipped / 0 point]

Z: Remove 3 coins from your pile [Effects: -3 local unflipped / 0 point]

R: Rotate coins to previous player [Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]

T: Rotate coins to next player [Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]

F: Flip 1 coin [Effects: -1 local unflipped / +1 local flipped / +2 point]

U: Unflip 1 coin [Effects: +1 local unflipped / -1 local flipped / -2 point]

Example output

2FF : Takes two coins and flips two coin, scoring -2 + 2 + 2 = 2 points

If your output is incorrect, controller will assume NNN.

Controller

You can find the controller on GitHub. It also contains two samplebots, written in Java.
To make it run, check out the project and open it in your Java IDE. The entry point in the main method of the class Game. Java 8 required.

To add bots, first you need either the compiled version for Java (.class files) or the sources for interpreted languages. Place them in the root folder of the project. Then, create a new Java class in the players package (you can take example on the already existing bots). This class must implement Player to override the method String getCmd(). The String returned is the shell command to run your bots. You can for example make a Ruby bot work with this command : return "C:\Ruby\bin\ruby.exe MyBot.rb";. Finally, add the bot in the players array at the top of the Game class.

Rules

Bots should not be written to beat or support specific other bots.

Writing to files is allowed. Please write to"yoursubmissionname.txt", the folder will be emptied before a game starts. Other external resources are disallowed.

Your submission has 1 second to respond.

Provide commands to compile and run your submissions.

Supported Languages

I'll try and support every language, but it needs to be available online for free. Please provide instructions for installation if you're not using a "mainstream" language.

As of right now, I can run : Java 6-7-8, PHP, Ruby, Perl, Python 2-3, Lua, R, node.js, Haskell, Kotlin, C++ 11.

Final results

These are the results of 100 games (points are added up) :

```<code>1. BirdInTheHand: 1017790
2. Balance: 851428
3. SecondBest: 802316
4. Crook: 739080
5. Jim: 723440
6. Flipper: 613290
7. Wheeler: 585516
8. Oracle: 574916
9. SimpleBot: 543665
10. TraderBot: 538160
11. EgoisticalBot: 529567
12. RememberMe: 497513
13. PassiveBot: 494441
14. TheJanitor: 474069
15. GreedyRotation: 447057
16. Devil: 79212
17. Saboteur: 62240
</code>```

Individual results of the games are available here : http://pasted.co/63f1e924 (with starting coins and number of rounds per game).

A bounty of 50 reputations is awarded to the winner : Bird In The Hand by Martin Büttner.

Thank you all for your participation, see you next KOTH~

Body:
Flipper, Python 2

Flipper gathers coins and tries to turn unflipped to flipped. Flipper is not a smart player but tries to be a positive force in the game.

import sys, random

# process input data (not used here):
args = sys.argv[1].split(';')
rounds, myid, coins = map(int, args[:3])
players = [map(int, data.split('_')) for data in args[3:]]

# implement strategy using multiples of 'N123ABCXYZRTFU':
options = '12333FFFFFFFFFFF'
print ''.join(random.choice(options) for i in range(3))

Flipper just needs the python flipper.py <arg> to run.


答:
Mathcad, [tbd] bytes

Uses a spigot algorithm - http://comjnl.oxfordjournals.org/content/11/2/229.full.pdf+html.

Byte count not given as Mathcad byte count equivalence is yet to be determined.  However, using a symbol equivalence it is roughly 121 bytes ... and not going to win any brevity prizes no matter how the equivalence is determined.

ContentLicense: CC BY-SA 2.5

Title: Compute the first N digits of e

Body:
Challenge

Write a program to compute the the first N (<= 10^3) digits of e.

Your program should take an integer N as input.

Input:

```<code>100
</code>```

Output:

```<code>2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427
</code>```

Input:

```<code>7
</code>```

Output:

```<code>2.718282
</code>```

Input:

```<code>1000
</code>```

Output:

```<code>2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059921817413596629043572900334295260595630738132328627943490763233829880753195251019011573834187930702154089149934884167509244761460668082264800168477411853742345442437107539077744992069551702761838606261331384583000752044933826560297606737113200709328709127443747047230696977209310141692836819025515108657463772111252389784425056953696770785449969967946864454905987931636889230098793127736178215424999229576351482208269895193668033182528869398496465105820939239829488793320362509443117301238197068416140397019837679320683282376464804295311802328782509819455815301756717361332069811250996181881593041690351598888519345807273866738589422879228499892086805825749279610484198444363463244968487560233624827041978623209002160990235304369941849146314093431738143640546253152096183690888707016768396424378140592714563549061303107208510383750510115747704171898610687396965521267154688957035035
</code>```

Shortest solution wins!


答:
Greedy Rotation, Ruby

round, id, global, *players = ARGV[0].split(';')
round = round.to_i
id = id.to_i
global = global.to_i

players.map!{ |s| s.split('_').map(&:to_i) }

nplayers = players.size

my_pos = players.find_index { |i, p, f, u| i == id }

prev_p = players[my_pos-1]
next_p = players[(my_pos+1)%nplayers]

prev_score = 2*prev_p[2] - prev_p[3]
next_score = 2*next_p[2] - next_p[3]

take_from = prev_p

$><< '3'
if prev_score > next_score || prev_score == next_score && prev_p[3] > next_p[3]
    $><< 'T'
else
    $><< 'R'
    take_from = next_p
end

if take_from[3] >= 3
    $><< 'C'
elsif take_from[3] >= 1
    $><< 'F'
else
    $><< 'N'
end
```

This is quite similar to ArtOfCode's approach, except that this checks from which neighbour we can get more points, and it chooses C instead of F if we end up with 3 or more coins after the rotation.

After writing this up, I'm pretty sure that a better approach would be just to greedily pick the best out of all moves every time, preceding rotation by taking if possible (instead of sticking to a fixed "get unflipped, rotate, get rid of unflipped" pattern).

This also doesn't take into account the implicit points represented by the coins actually owned (based on the assumption that the game is going to last enough rounds that I likely won't end up keeping my coins anyway).

Title: KOTH: Every coin has two sides

Body:
Greedy Rotation, Ruby

round, id, global, *players = ARGV[0].split(';')
round = round.to_i
id = id.to_i
global = global.to_i

players.map!{ |s| s.split('_').map(&:to_i) }

nplayers = players.size

my_pos = players.find_index { |i, p, f, u| i == id }

prev_p = players[my_pos-1]
next_p = players[(my_pos+1)%nplayers]

prev_score = 2*prev_p[2] - prev_p[3]
next_score = 2*next_p[2] - next_p[3]

take_from = prev_p

$><< '3'
if prev_score > next_score || prev_score == next_score && prev_p[3] > next_p[3]
    $><< 'T'
else
    $><< 'R'
    take_from = next_p
end

if take_from[3] >= 3
    $><< 'C'
elsif take_from[3] >= 1
    $><< 'F'
else
    $><< 'N'
end

This is quite similar to ArtOfCode's approach, except that this checks from which neighbour we can get more points, and it chooses C instead of F if we end up with 3 or more coins after the rotation.

After writing this up, I'm pretty sure that a better approach would be just to greedily pick the best out of all moves every time, preceding rotation by taking if possible (instead of sticking to a fixed "get unflipped, rotate, get rid of unflipped" pattern).

This also doesn't take into account the implicit points represented by the coins actually owned (based on the assumption that the game is going to last enough rounds that I likely won't end up keeping my coins anyway).


答:
Balance, Lua

Balance will try to keep the balance in its token, minimizing the loss in case someone uses the R and T actions against him.
He thinks this style of life is the true one and should be enforced to anyone that doesn't keep a good balance of flipped/unflipped coins, so everyone close to him will be punished as soon as it could make them lose points.

He needs the following command to run:

lua balance.lua
```
<p>Where the file balance.lua contains the following piece of code:</p>
<pre class="lang-lua prettyprint-override"><code>local datas={}
local arg=arg[1]..";"

-- parse the arguments
-- add some meta datas for debuging purpose/usefulness
arg:gsub("(.-);",function(c)
  if not datas.round
  then
    datas.round=c+0
  elseif not datas.myID
  then
    datas.myID=c+0
  elseif not datas.coins
  then
    datas.coins=c+0
  else
    datas[#datas+1]={}
    datas[#datas].repr=c
    c=c.."_"
    tmp={}
    c:gsub("(.-)_",function(d) tmp[#tmp+1]=d end)
    datas[#datas].id=tmp[1]+0
    datas[#datas].points=tmp[2]+0
    datas[#datas].flip=tmp[3]+0
    datas[#datas].unflip=tmp[4]+0
    if datas[#datas].id==datas.myID
    then
      datas.myOrder=#datas
      datas.myDatas=datas[#datas]
    end
  end
end)

local actions=""
-- construct actions
for i=1,3
do
  -- if we aren't in balance and can grab more coins
  -- we do it
  if #actions==0 and datas.myDatas.unflip<=datas.myDatas.flip/2 and datas.coins>=3
  then
    actions=actions.."3"
    datas.myDatas.unflip=datas.myDatas.unflip+3
    datas.coins=datas.coins-3
  -- if we couldn't grab coins, but aren't in balance, we flip some coins
  elseif datas.myDatas.unflip>datas.myDatas.flip/2
  then
    actions=actions.."F"
    datas.myDatas.unflip=datas.myDatas.unflip-1
    datas.myDatas.flip=datas.myDatas.flip+1

  -- if we didn't have anything to do on our pile, let's punish
  -- the fools who doesn't follow the great Balance principle
  else
    previous=datas.myOrder<2 and #datas or datas.myOrder-1
    following=datas.myOrder>=#datas and 1 or datas.myOrder+1

    lossPrev=-datas[previous].flip + 2*datas[previous].unflip
    lossFoll=-datas[following].flip+ 2*datas[following].unflip
    if lossFoll>0 and lossPrev>0
    then
      actions =actions.."N"
    elseif lossFoll>=lossPrev
    then
      actions=actions.."T"
      datas[following].unflip,datas[following].flip=datas[following].flip,datas[following].unflip
    else
      actions=actions.."R"
      datas[previous].unflip,datas[previous].flip=datas[previous].flip,datas[previous].unflip
    end
  end
end
print(actions)
</code>```

Title: KOTH: Every coin has two sides

Body:
Balance, Lua

Balance will try to keep the balance in its token, minimizing the loss in case someone uses the R and T actions against him.
He thinks this style of life is the true one and should be enforced to anyone that doesn't keep a good balance of flipped/unflipped coins, so everyone close to him will be punished as soon as it could make them lose points.

He needs the following command to run:

lua balance.lua

Where the file balance.lua contains the following piece of code:

local datas={}
local arg=arg[1]..";"

-- parse the arguments
-- add some meta datas for debuging purpose/usefulness
arg:gsub("(.-);",function(c)
  if not datas.round
  then
    datas.round=c+0
  elseif not datas.myID
  then
    datas.myID=c+0
  elseif not datas.coins
  then
    datas.coins=c+0
  else
    datas[#datas+1]={}
    datas[#datas].repr=c
    c=c.."_"
    tmp={}
    c:gsub("(.-)_",function(d) tmp[#tmp+1]=d end)
    datas[#datas].id=tmp[1]+0
    datas[#datas].points=tmp[2]+0
    datas[#datas].flip=tmp[3]+0
    datas[#datas].unflip=tmp[4]+0
    if datas[#datas].id==datas.myID
    then
      datas.myOrder=#datas
      datas.myDatas=datas[#datas]
    end
  end
end)

local actions=""
-- construct actions
for i=1,3
do
  -- if we aren't in balance and can grab more coins
  -- we do it
  if #actions==0 and datas.myDatas.unflip<=datas.myDatas.flip/2 and datas.coins>=3
  then
    actions=actions.."3"
    datas.myDatas.unflip=datas.myDatas.unflip+3
    datas.coins=datas.coins-3
  -- if we couldn't grab coins, but aren't in balance, we flip some coins
  elseif datas.myDatas.unflip>datas.myDatas.flip/2
  then
    actions=actions.."F"
    datas.myDatas.unflip=datas.myDatas.unflip-1
    datas.myDatas.flip=datas.myDatas.flip+1

  -- if we didn't have anything to do on our pile, let's punish
  -- the fools who doesn't follow the great Balance principle
  else
    previous=datas.myOrder<2 and #datas or datas.myOrder-1
    following=datas.myOrder>=#datas and 1 or datas.myOrder+1

    lossPrev=-datas[previous].flip + 2*datas[previous].unflip
    lossFoll=-datas[following].flip+ 2*datas[following].unflip
    if lossFoll>0 and lossPrev>0
    then
      actions =actions.."N"
    elseif lossFoll>=lossPrev
    then
      actions=actions.."T"
      datas[following].unflip,datas[following].flip=datas[following].flip,datas[following].unflip
    else
      actions=actions.."R"
      datas[previous].unflip,datas[previous].flip=datas[previous].flip,datas[previous].unflip
    end
  end
end
print(actions)


问:
Is it a prefix code?
In information theory, a "prefix code" is a dictionary where none of the keys are a prefix of another. In other words, this means that none of the strings starts with any of the other.

For example, {"9", "55"} is a prefix code, but {"5", "9", "55"} is not.

The biggest advantage of this, is that the encoded text can be written down with no separator between them, and it will still be uniquely decipherable. This shows up in compression algorithms such as Huffman coding, which always generates the optimal prefix code.

Your task is simple: Given a list of strings, determine whether or not it is a valid prefix code.

Your input:

Will be a list of strings in any reasonable format.

Will only contain printable ASCII strings.

Will not contain any empty strings.

Your output will be a truthy/falsey value: Truthy if it's a valid prefix code, and falsey if it isn't.

Here are some true test cases:

```<code>["Hello", "World"]
["Code", "Golf", "Is", "Cool"]
["1", "2", "3", "4", "5"]
["This", "test", "case", "is", "true"]

["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011",
 "0110", "11001", "00110", "10011", "11000", "00111", "10010"]
</code>```

Here are some false test cases:

```<code>["4", "42"]
["1", "2", "3", "34"]
["This", "test", "case", "is", "false", "t"]
["He", "said", "Hello"]
["0", "00", "00001"]
["Duplicate", "Duplicate", "Keys", "Keys"]
</code>```

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

答:
Mathematica <s>75 69</s> 68 bytes

Loquacious as usual. But Martin B was able to reduce the code by 7 bytes.

Method 1: Storing output in an Array

(68 bytes)

```<code>f@a_:=!Or@@(Join@@Array[a~Drop~{#}~StringStartsQ~a[[#]]&,Length@a])
</code>```

```<code>f@{"111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011", "0110", "11001", "00110", "10011", "11000", "00111", "10010"}
</code>```

True

```<code>f@{"He", "said", "Hello"}
</code>```

False

Method 2: Storing output in a List

(69 bytes)

```<code>f@a_:=!Or@@Flatten[a~Drop~{#}~StringStartsQ~a[[#]]&/@Range@Length@a]
</code>```

Title: Is it a prefix code?

Body:
Mathematica <s>75 69</s> 68 bytes

Loquacious as usual. But Martin B was able to reduce the code by 7 bytes.

Method 1: Storing output in an Array

(68 bytes)

f@a_:=!Or@@(Join@@Array[a~Drop~{#}~StringStartsQ~a[[#]]&,Length@a])

f@{"111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011", "0110", "11001", "00110", "10011", "11000", "00111", "10010"}

True

f@{"He", "said", "Hello"}

False

Method 2: Storing output in a List

(69 bytes)

f@a_:=!Or@@Flatten[a~Drop~{#}~StringStartsQ~a[[#]]&/@Range@Length@a]


问:
Is this uniquely concatenable?
In this challenge about prefix code, we learnt that prefix codes are uniquely concatenable.

That means, they can be joined together without separator, and without ambiguity.

For example, since [1,2,45] is a prefix code, I can join them together without separator as such: 1245245112145, and there will be no ambiguity.

However the converse is not always true.

For example, [3,34] is not a prefix code. However, I can do the same: 3333434334333, and there will be no ambiguity. You would just need a smarter parser.

However, [1,11] is not uniquely concatenable, because 1111 can be interpreted in 5 ways.

Goal

Your task is to write a program/function that takes a list of strings (ASCII) as input, and determine if they are uniquely concatenable.

Details

Duplicate counts as false.

Scoring

This is code-golf. Shortest solution in bytes wins.

Testcases

True:

```<code>[12,21,112]
[12,112,1112]
[3,4,35]
[2,3,352]
</code>```

False:

```<code>[1,1]
[1,2,112]
[1,23,4,12,34]
[1,2,35,4,123,58,8]
</code>```

答:
05AB1E, 15 bytes

On the phone, so explanation will have to follow later. Code:

```<code>gF¹N>ã})€`€JDÚQ
</code>```

Uses CP-1252 encoding. Try it online!.

Takes too much memory for the last test case, so that might not work...

Title: Is this uniquely concatenable?

Body:
05AB1E, 15 bytes

On the phone, so explanation will have to follow later. Code:

gF¹N>ã})€`€JDÚQ

Uses CP-1252 encoding. Try it online!.

Takes too much memory for the last test case, so that might not work...


答:
Java, 97 bytes

Object a(String[]a){for(String t:a)for(String e:a)if(t!=e&t.startsWith(e))return 1<0;return 1>0;}
```
<p>Uses most of the tricks found in @Marv's answer, but also makes use of the foreach loop and string reference equality.</p>
<p>Unminified:</p>
<pre class="lang-java prettyprint-override"><code>Object a(String[]a){
    for (String t : a)
        for (String e : a)
            if (t != e & t.startsWith(e))
                return 1<0;
    return 1>0;
}
</code>```

Note that, as I said, this uses string reference equality.  That does mean that the code can behave oddly due to String interning.  The code does work when using arguments passed from the command line, and also when using something read from the command line.  If you want to hardcode the values to test, though, you'd need to manually call the String constructor to force interning to not occur:

System.out.println(a(new String[] {new String("Hello"), new String("World")}));
System.out.println(a(new String[] {new String("Code"), new String("Golf"), new String("Is"), new String("Cool")}));
System.out.println(a(new String[] {new String("1"), new String("2"), new String("3"), new String("4"), new String("5")}));
System.out.println(a(new String[] {new String("This"), new String("test"), new String("case"), new String("is"), new String("true")}));
System.out.println(a(new String[] {new String("111"), new String("010"), new String("000"), new String("1101"), new String("1010"), new String("1000"), new String("0111"), new String("0010"), new String("1011"), new String("0110"), new String("11001"), new String("00110"), new String("10011"), new String("11000"), new String("00111"), new String("10010")}));
System.out.println(a(new String[] {new String("4"), new String("42")}));
System.out.println(a(new String[] {new String("1"), new String("2"), new String("3"), new String("34")}));
System.out.println(a(new String[] {new String("This"), new String("test"), new String("case"), new String("is"), new String("false"), new String("t")}));
System.out.println(a(new String[] {new String("He"), new String("said"), new String("Hello")}));
System.out.println(a(new String[] {new String("0"), new String("00"), new String("00001")}));
System.out.println(a(new String[] {new String("Duplicate"), new String("Duplicate"), new String("Keys"), new String("Keys")}));
```

Title: Is it a prefix code?

Body:
In information theory, a "prefix code" is a dictionary where none of the keys are a prefix of another. In other words, this means that none of the strings starts with any of the other.

For example, {"9", "55"} is a prefix code, but {"5", "9", "55"} is not.

The biggest advantage of this, is that the encoded text can be written down with no separator between them, and it will still be uniquely decipherable. This shows up in compression algorithms such as Huffman coding, which always generates the optimal prefix code.

Your task is simple: Given a list of strings, determine whether or not it is a valid prefix code.

Your input:

Will be a list of strings in any reasonable format.

Will only contain printable ASCII strings.

Will not contain any empty strings.

Your output will be a truthy/falsey value: Truthy if it's a valid prefix code, and falsey if it isn't.

Here are some true test cases:

```<code>["Hello", "World"]
["Code", "Golf", "Is", "Cool"]
["1", "2", "3", "4", "5"]
["This", "test", "case", "is", "true"]

["111", "010", "000", "1101", "1010", "1000", "0111", "0010", "1011",
 "0110", "11001", "00110", "10011", "11000", "00111", "10010"]
</code>```

Here are some false test cases:

```<code>["4", "42"]
["1", "2", "3", "34"]
["This", "test", "case", "is", "false", "t"]
["He", "said", "Hello"]
["0", "00", "00001"]
["Duplicate", "Duplicate", "Keys", "Keys"]
</code>```

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

Body:
Java, 97 bytes

Object a(String[]a){for(String t:a)for(String e:a)if(t!=e&t.startsWith(e))return 1<0;return 1>0;}

Uses most of the tricks found in @Marv's answer, but also makes use of the foreach loop and string reference equality.

Unminified:

Object a(String[]a){
    for (String t : a)
        for (String e : a)
            if (t != e & t.startsWith(e))
                return 1<0;
    return 1>0;
}

Note that, as I said, this uses string reference equality.  That does mean that the code can behave oddly due to String interning.  The code does work when using arguments passed from the command line, and also when using something read from the command line.  If you want to hardcode the values to test, though, you'd need to manually call the String constructor to force interning to not occur:

System.out.println(a(new String[] {new String("Hello"), new String("World")}));
System.out.println(a(new String[] {new String("Code"), new String("Golf"), new String("Is"), new String("Cool")}));
System.out.println(a(new String[] {new String("1"), new String("2"), new String("3"), new String("4"), new String("5")}));
System.out.println(a(new String[] {new String("This"), new String("test"), new String("case"), new String("is"), new String("true")}));
System.out.println(a(new String[] {new String("111"), new String("010"), new String("000"), new String("1101"), new String("1010"), new String("1000"), new String("0111"), new String("0010"), new String("1011"), new String("0110"), new String("11001"), new String("00110"), new String("10011"), new String("11000"), new String("00111"), new String("10010")}));
System.out.println(a(new String[] {new String("4"), new String("42")}));
System.out.println(a(new String[] {new String("1"), new String("2"), new String("3"), new String("34")}));
System.out.println(a(new String[] {new String("This"), new String("test"), new String("case"), new String("is"), new String("false"), new String("t")}));
System.out.println(a(new String[] {new String("He"), new String("said"), new String("Hello")}));
System.out.println(a(new String[] {new String("0"), new String("00"), new String("00001")}));
System.out.println(a(new String[] {new String("Duplicate"), new String("Duplicate"), new String("Keys"), new String("Keys")}));


问:
Decompose a number!
Your task is to decompose a number using the format below.

This is similar to base conversion, except that instead of listing the digits in the base, you list the values, such that the list adds up to the input.

If the given base is \$n\$, then each number in the list must be in the form of \$k\times n^m\$, where \$0\le k<n\$ and \$m\$ is unique throughout the list.

Specs

Any reasonable input/output format. Your program/function takes 2 inputs and outputs a list.

Output list can be in any order.

0 can be excluded or included.

Leading 0s are allowed.

Built-ins are allowed.

Testcases

```<code>number base   converted list
input1 input2 output
123456 10     [100000,20000,3000,400,50,6] or [6,50,400,3000,20000,100000]
11     2      [8,2,1] or [0,0,0,0,8,0,2,1]
727    20     [400,320,7]
101    10     [100,1] or [100,0,1]
</code>```

Scoring

This is code-golf. Shortest solution in bytes wins.

答:
TSQL, 68 bytes

```<code>DECLARE @ INT=123456,@z INT=10
DECLARE @l INT=1WHILE
@>0BEGIN PRINT @%@z*@l SELECT @/=@z,@l*=@z END
</code>```

ContentLicense: CC BY-SA 4.0

Title: Decompose a number!

Body:
TSQL, 68 bytes

DECLARE @ INT=123456,@z INT=10
DECLARE @l INT=1WHILE
@>0BEGIN PRINT @%@z*@l SELECT @/=@z,@l*=@z END


答:
Crook, R

args <- strsplit(commandArgs(TRUE),";")[[1]]
state <- as.data.frame(do.call(rbind,strsplit(args[-(1:3)],"_")), stringsAsFactors=FALSE)
colnames(state) <- c("id","pts","flipped","unflipped")
state$flipped <- as.integer(state$flipped)
state$unflipped <- as.integer(state$unflipped)
nb <- nrow(state)
score <- function(place) 2*state$flipped[place]-state$unflipped[place]
my_place <- which(state$id==args[2])
next_1 <- ifelse(my_place!=nb,my_place+1,1)
next_2 <- ifelse(next_1!=nb,next_1+1,1)
next_3 <- ifelse(next_2!=nb,next_2+1,1)
previous_1 <- ifelse(my_place!=1,my_place-1,nb)
previous_2 <- ifelse(previous_1!=1,previous_1-1,nb)
previous_3 <- ifelse(previous_2!=1,previous_2-1,nb)
n <- 3
out <- c()
while(n){
    M <- N <- score(my_place)
    R <- switch(n,"1"=score(next_1),
                "2"=cumsum(c(score(next_1),score(next_2))),
                "3"=cumsum(c(score(next_1),score(next_2),score(next_3))))
    P <- switch(n,"1"=score(previous_1),
                "2"=cumsum(c(score(previous_1),score(previous_2))),
                "3"=cumsum(c(score(previous_1),score(previous_2),score(previous_3))))
    M <- c(M,M+R[-n])
    N <- c(N,N+P[-n])
    if(any(R>M & R>0)){
        action <- c("R","RR","RRR")[which.max(R-M)]
        out <- c(out, action)
        state[,3:4] <- state[c((nchar(action)+1):nb,seq_len(nchar(action))),3:4]
        n <- n-nchar(action)
    }else if(any(P>N & P>0)){
        action <- c("T","TT","TTT")[which.max(P-N)]
        out <- c(out, action)
        state[,3:4] <- state[c((nb+1-seq_len(nchar(action))),1:(nb-seq_len(nchar(action)))),3:4]
        n <- n-nchar(action)
    }else if(n>1 & all(R[1]+M[1]>c(0,P[1]+M[1],R[1]+R[2]))){
        out <- c(out,"RT")
        n <- n-2
    }else if(n>1 & all(P[1]+M[1]>c(0,R[1]+M[1],P[1]+P[2]))){
        out <- c(out,"TR")
        n <- n-2
    }else{
        out <- c(out, switch(n,"1"="A","2"="1F","3"="2FF"))
        n <- 0
        }
    }
cat(paste(out,collapse=""))
```

To run: Rscript Crook.R

Basically it exchanges its coins with its neighbours only if the exchange is uneven in its favour. If no beneficial exchange is possible, then it exchanges coins with the global pile in a way that keeps its ratio intact but generate some points.

Edit: I added a little bit of depth to this bot by making it check the next and previous 2 and 3 player stacks instead of just the next one and check if, overall, it is beneficial to rotate that many times.

2nd Edit: Following @MartinBüttner's idea, the bot now performs a "RT", or "TR", if it would be beneficial for him more than for its neighbours (if I didn't mess up in implementing it :) ).

Title: KOTH: Every coin has two sides

Body:
Crook, R

args <- strsplit(commandArgs(TRUE),";")[[1]]
state <- as.data.frame(do.call(rbind,strsplit(args[-(1:3)],"_")), stringsAsFactors=FALSE)
colnames(state) <- c("id","pts","flipped","unflipped")
state$flipped <- as.integer(state$flipped)
state$unflipped <- as.integer(state$unflipped)
nb <- nrow(state)
score <- function(place) 2*state$flipped[place]-state$unflipped[place]
my_place <- which(state$id==args[2])
next_1 <- ifelse(my_place!=nb,my_place+1,1)
next_2 <- ifelse(next_1!=nb,next_1+1,1)
next_3 <- ifelse(next_2!=nb,next_2+1,1)
previous_1 <- ifelse(my_place!=1,my_place-1,nb)
previous_2 <- ifelse(previous_1!=1,previous_1-1,nb)
previous_3 <- ifelse(previous_2!=1,previous_2-1,nb)
n <- 3
out <- c()
while(n){
    M <- N <- score(my_place)
    R <- switch(n,"1"=score(next_1),
                "2"=cumsum(c(score(next_1),score(next_2))),
                "3"=cumsum(c(score(next_1),score(next_2),score(next_3))))
    P <- switch(n,"1"=score(previous_1),
                "2"=cumsum(c(score(previous_1),score(previous_2))),
                "3"=cumsum(c(score(previous_1),score(previous_2),score(previous_3))))
    M <- c(M,M+R[-n])
    N <- c(N,N+P[-n])
    if(any(R>M & R>0)){
        action <- c("R","RR","RRR")[which.max(R-M)]
        out <- c(out, action)
        state[,3:4] <- state[c((nchar(action)+1):nb,seq_len(nchar(action))),3:4]
        n <- n-nchar(action)
    }else if(any(P>N & P>0)){
        action <- c("T","TT","TTT")[which.max(P-N)]
        out <- c(out, action)
        state[,3:4] <- state[c((nb+1-seq_len(nchar(action))),1:(nb-seq_len(nchar(action)))),3:4]
        n <- n-nchar(action)
    }else if(n>1 & all(R[1]+M[1]>c(0,P[1]+M[1],R[1]+R[2]))){
        out <- c(out,"RT")
        n <- n-2
    }else if(n>1 & all(P[1]+M[1]>c(0,R[1]+M[1],P[1]+P[2]))){
        out <- c(out,"TR")
        n <- n-2
    }else{
        out <- c(out, switch(n,"1"="A","2"="1F","3"="2FF"))
        n <- 0
        }
    }
cat(paste(out,collapse=""))

To run: Rscript Crook.R

Basically it exchanges its coins with its neighbours only if the exchange is uneven in its favour. If no beneficial exchange is possible, then it exchanges coins with the global pile in a way that keeps its ratio intact but generate some points.

Edit: I added a little bit of depth to this bot by making it check the next and previous 2 and 3 player stacks instead of just the next one and check if, overall, it is beneficial to rotate that many times.

2nd Edit: Following @MartinBüttner's idea, the bot now performs a "RT", or "TR", if it would be beneficial for him more than for its neighbours (if I didn't mess up in implementing it :) ).


问:
Compute CRC32 Hash

Credits

This challenge originated from @miles.

Create a function that computes the CRC32 hash of an input string. The input will be an ASCII string of any length. The output will be the CRC32 hash of that input string.

Explanation

The algorithm of CRC32 and other CRC are essentially the same, so only CRC3 will be demonstrated here.

Firstly, you have the generator polynomial, which is actually a 4-bit [n+1] integer (would be 33-bit in CRC32).

In this example, the generator polynomial is 1101.

Then, you will have the string to be hashed, which in this example would be 00010010111100101011001101.

```<code>00010010111100101011001101|000 (1)    append three [n] "0"s
   1101                        (2)    align with highest bit
00001000111100101011001101|000 (3)    XOR (1) and (2)
    1101                       (4)    align with highest bit
00000101111100101011001101|000 (5)    XOR (3) and (4)
     1101                      (6)    align with highest bit
00000011011100101011001101|000 (7)    XOR (5) and (6)
      1101                     (8)    align with highest bit
00000000001100101011001101|000 (9)    XOR (7) and (8)
          1101                 (10)   align with highest bit
00000000000001101011001101|000 (11)   XOR (9) and (10)
             1101              (12)   align with highest bit
00000000000000000011001101|000 (13)   XOR (11) and (12)
                  1101         (14)   align with highest bit
00000000000000000000011101|000 (15)   XOR (13) and (14)
                     1101      (16)   align with highest bit
00000000000000000000000111|000 (17)   XOR (15) and (16)
                       110 1   (18)   align with highest bit
00000000000000000000000001|100 (19)   XOR (17) and (18)
                         1 101 (20)   align with highest bit
00000000000000000000000000|001 (21)   XOR (19) and (20)
^--------REGION 1--------^ ^2^
</code>```

The remainder obtained at (21), when region 1 is zero, which is 001, would be the result of the CRC3 hash.

Specs

The generator polynomial is 0x104C11DB7, or 0b100000100110000010001110110110111, or 4374732215.

Input can be a string or a list of integers, or any other reasonable format.

Output be a hex string or just an integer, or any other reasonable format.

Built-ins that compute the CRC32 hash are not allowed.

Goal

Standard rules for code-golf apply.

The shortest code wins.

Test cases

```<code>input         output      (hex)
"code-golf"   147743960   08CE64D8
"jelly"       1699969158  65537886
""            0           00000000
</code>```

答:
CJam, 33 bytes

```<code>q256bYb_,{(4374732215Ybf*1>.^}*Yb
</code>```

Input is in form of a string. Try it online!

How it works

```<code>q                                  Read all input from STDIN.
 256bYb                            Convert it from base 256 to base 2.
       _,{                   }*    Compute the length and repeat that many times:
          (                          Shift out the first bit.
           4374732215Yb              Convert the integer to base 2.
                       f*            Multiply each bit by the shifted out bit.
                         1>          Remove the first bit.
                           .^        Compute the element-wise XOR of both lists.
                                     If one of the lists is shorter, the elements
                                     of the other lists do not get modified, thus
                                     avoiding the necessity of right-padding B with
                                     zeroes.
                               Yb  Convert the final result from base 2 to integer.
</code>```

Title: Compute CRC32 Hash

Body:
CJam, 33 bytes

q256bYb_,{(4374732215Ybf*1>.^}*Yb

Input is in form of a string. Try it online!

How it works

q                                  Read all input from STDIN.
 256bYb                            Convert it from base 256 to base 2.
       _,{                   }*    Compute the length and repeat that many times:
          (                          Shift out the first bit.
           4374732215Yb              Convert the integer to base 2.
                       f*            Multiply each bit by the shifted out bit.
                         1>          Remove the first bit.
                           .^        Compute the element-wise XOR of both lists.
                                     If one of the lists is shorter, the elements
                                     of the other lists do not get modified, thus
                                     avoiding the necessity of right-padding B with
                                     zeroes.
                               Yb  Convert the final result from base 2 to integer.


答:
Oracle, Python 3

Update: changed the order of the various tries to favor low pile of coins over rotations.

import sys
import itertools
from copy import deepcopy

MOVES_REQUIRED = 3

FLIPPED = 0
UNFLIPPED = 1

def filter_neighbors(neighbors, me, size):
    limit = size - MOVES_REQUIRED
    for data in neighbors:
        i, _, flipped, unflipped = map(int, data.split('_'))
        if MOVES_REQUIRED < (me - i) % size < limit:
            continue  # Skip neighbors that are too far away
        yield i, [flipped, unflipped]

class Player:
    def __init__(self, raw_data):
        _, me, coins, *data = raw_data.split(';')

        self.num_players = len(data)
        self._me = int(me)
        self._coins = int(coins)
        self._state = dict(filter_neighbors(data, self._me, self.num_players))

    def reset(self):
        self.me = self._me
        self.coins = self._coins
        self.state = deepcopy(self._state)
        self.my_state = self.state[self.me]

    def invalid_move(self, move):
        if move in 'NRT':
            return False

        if move in '123'[:self.coins]:
            return False

        flipped, unflipped = self.my_state
        if flipped and move == 'U':
            return False
        if unflipped and move == 'F':
            return False

        if move in 'AXBYCZ'[:2 * unflipped]:
            return False

        return True

    def N(self):
        return 0

    def one(self):
        self.coins -= 1
        self.my_state[UNFLIPPED] += 1
        return -1

    def two(self):
        self.coins -= 2
        self.my_state[UNFLIPPED] += 2
        return -2

    def three(self):
        self.coins -= 3
        self.my_state[UNFLIPPED] += 3
        return -3

    def A(self):
        self.coins += 1
        self.my_state[UNFLIPPED] -= 1
        return 1

    def B(self):
        self.coins += 2
        self.my_state[UNFLIPPED] -= 2
        return 2

    def C(self):
        self.coins += 3
        self.my_state[UNFLIPPED] -= 3
        return 3

    def X(self):
        self.my_state[UNFLIPPED] -= 1
        return 0

    def Y(self):
        self.my_state[UNFLIPPED] -= 2
        return 0

    def Z(self):
        self.my_state[UNFLIPPED] -= 3
        return 0

    def R(self):
        self.me = (self.me + 1) % self.num_players
        flipped, unflipped = self.my_state = self.state[self.me]
        return 2 * flipped - unflipped

    def T(self):
        self.me = (self.me - 1) % self.num_players
        flipped, unflipped = self.my_state = self.state[self.me]
        return 2 * flipped - unflipped

    def F(self):
        self.my_state[FLIPPED] += 1
        self.my_state[UNFLIPPED] -= 1
        return 2

    def U(self):
        self.my_state[FLIPPED] -= 1
        self.my_state[UNFLIPPED] += 1
        return -2

setattr(Player, '1', Player.one)
setattr(Player, '2', Player.two)
setattr(Player, '3', Player.three)

def scenarii(player):
    for tries in itertools.product('FUABCXYZ123NRT', repeat=MOVES_REQUIRED):
        player.reset()
        points = 0
        for try_ in tries:
            if player.invalid_move(try_):
                break
            points += getattr(player, try_)()
        else:
            yield points, ''.join(tries)

if __name__ == '__main__':
    player = Player(sys.argv[1])
    print(max(scenarii(player))[1])
```

Tries every single possible output and keep the one that yield the maximum amount of points for this turn.

Title: KOTH: Every coin has two sides

Body:
Oracle, Python 3

Update: changed the order of the various tries to favor low pile of coins over rotations.

import sys
import itertools
from copy import deepcopy

MOVES_REQUIRED = 3

FLIPPED = 0
UNFLIPPED = 1

def filter_neighbors(neighbors, me, size):
    limit = size - MOVES_REQUIRED
    for data in neighbors:
        i, _, flipped, unflipped = map(int, data.split('_'))
        if MOVES_REQUIRED < (me - i) % size < limit:
            continue  # Skip neighbors that are too far away
        yield i, [flipped, unflipped]

class Player:
    def __init__(self, raw_data):
        _, me, coins, *data = raw_data.split(';')

        self.num_players = len(data)
        self._me = int(me)
        self._coins = int(coins)
        self._state = dict(filter_neighbors(data, self._me, self.num_players))

    def reset(self):
        self.me = self._me
        self.coins = self._coins
        self.state = deepcopy(self._state)
        self.my_state = self.state[self.me]

    def invalid_move(self, move):
        if move in 'NRT':
            return False

        if move in '123'[:self.coins]:
            return False

        flipped, unflipped = self.my_state
        if flipped and move == 'U':
            return False
        if unflipped and move == 'F':
            return False

        if move in 'AXBYCZ'[:2 * unflipped]:
            return False

        return True

    def N(self):
        return 0

    def one(self):
        self.coins -= 1
        self.my_state[UNFLIPPED] += 1
        return -1

    def two(self):
        self.coins -= 2
        self.my_state[UNFLIPPED] += 2
        return -2

    def three(self):
        self.coins -= 3
        self.my_state[UNFLIPPED] += 3
        return -3

    def A(self):
        self.coins += 1
        self.my_state[UNFLIPPED] -= 1
        return 1

    def B(self):
        self.coins += 2
        self.my_state[UNFLIPPED] -= 2
        return 2

    def C(self):
        self.coins += 3
        self.my_state[UNFLIPPED] -= 3
        return 3

    def X(self):
        self.my_state[UNFLIPPED] -= 1
        return 0

    def Y(self):
        self.my_state[UNFLIPPED] -= 2
        return 0

    def Z(self):
        self.my_state[UNFLIPPED] -= 3
        return 0

    def R(self):
        self.me = (self.me + 1) % self.num_players
        flipped, unflipped = self.my_state = self.state[self.me]
        return 2 * flipped - unflipped

    def T(self):
        self.me = (self.me - 1) % self.num_players
        flipped, unflipped = self.my_state = self.state[self.me]
        return 2 * flipped - unflipped

    def F(self):
        self.my_state[FLIPPED] += 1
        self.my_state[UNFLIPPED] -= 1
        return 2

    def U(self):
        self.my_state[FLIPPED] -= 1
        self.my_state[UNFLIPPED] += 1
        return -2

setattr(Player, '1', Player.one)
setattr(Player, '2', Player.two)
setattr(Player, '3', Player.three)

def scenarii(player):
    for tries in itertools.product('FUABCXYZ123NRT', repeat=MOVES_REQUIRED):
        player.reset()
        points = 0
        for try_ in tries:
            if player.invalid_move(try_):
                break
            points += getattr(player, try_)()
        else:
            yield points, ''.join(tries)

if __name__ == '__main__':
    player = Player(sys.argv[1])
    print(max(scenarii(player))[1])

Tries every single possible output and keep the one that yield the maximum amount of points for this turn.


答:
CJam (54 bytes)

```<code>q_N/:A\,{_Am*:${~1$,<=},{~\,>}%La:L-}*A,A_&,-A*](\M*&!
</code>```

Takes input on stdin as newline-separated list.

Online demo

If we didn't have to handle duplicate codewords, this could be shortened to 44:

```<code>q_N/\,{_W$m*:${~1$,<=},{~\,>}%La:L-}*](\M*&!
</code>```

Or if CJam had an array subtraction which only removed one item from the first list for each item in the second, it could be 48...

Dissection

This is the Sardinas-Patterson algorithm but de-optimised. Since each dangling suffix only comes up at most once, running the main loop as many times as there are characters in the input (including separators) guarantees to be sufficient.

Note that I had to work around what is arguably a bug in the CJam interpreter:

```<code>"abc" "a" #   e# gives 0 as the index at which "a" is found
"abc" "d" #   e# gives -1 as the index at which "d" is found
"abc" ""  #   e# gives an error
</code>```

So the prefix check is complicated to 1$,<= instead of \#!

```<code>e# Take input, split, loop once per char
q_N/\,{
  e# Build the suffixes corresponding to top-of-stack and bottom-of-stack
  _W$m*
  e# Map each pair of Cartesian product to the suffix if one is the prefix of the other;
  e# otherwise remove from the array
  :${~1$,<=},{~\,>}%
  e# Filter out empty suffixes iff it's the first time round the loop
  La:L-
}*
e# If we generated an empty suffix then we've also looped enough times to generate all
e# of the keywords as suffixes corresponding to the empty fix, so do a set intersection
e# to test this condition.
](\M*&!
</code>```

Title: Is this uniquely concatenable?

Body:
In this challenge about prefix code, we learnt that prefix codes are uniquely concatenable.

That means, they can be joined together without separator, and without ambiguity.

For example, since [1,2,45] is a prefix code, I can join them together without separator as such: 1245245112145, and there will be no ambiguity.

However the converse is not always true.

For example, [3,34] is not a prefix code. However, I can do the same: 3333434334333, and there will be no ambiguity. You would just need a smarter parser.

However, [1,11] is not uniquely concatenable, because 1111 can be interpreted in 5 ways.

Goal

Your task is to write a program/function that takes a list of strings (ASCII) as input, and determine if they are uniquely concatenable.

Details

Duplicate counts as false.

Scoring

This is code-golf. Shortest solution in bytes wins.

Testcases

True:

```<code>[12,21,112]
[12,112,1112]
[3,4,35]
[2,3,352]
</code>```

False:

```<code>[1,1]
[1,2,112]
[1,23,4,12,34]
[1,2,35,4,123,58,8]
</code>```

Body:
CJam (54 bytes)

q_N/:A\,{_Am*:${~1$,<=},{~\,>}%La:L-}*A,A_&,-A*](\M*&!

Takes input on stdin as newline-separated list.

Online demo

If we didn't have to handle duplicate codewords, this could be shortened to 44:

q_N/\,{_W$m*:${~1$,<=},{~\,>}%La:L-}*](\M*&!

Or if CJam had an array subtraction which only removed one item from the first list for each item in the second, it could be 48...

Dissection

This is the Sardinas-Patterson algorithm but de-optimised. Since each dangling suffix only comes up at most once, running the main loop as many times as there are characters in the input (including separators) guarantees to be sufficient.

Note that I had to work around what is arguably a bug in the CJam interpreter:

"abc" "a" #   e# gives 0 as the index at which "a" is found
"abc" "d" #   e# gives -1 as the index at which "d" is found
"abc" ""  #   e# gives an error

So the prefix check is complicated to 1$,<= instead of \#!

e# Take input, split, loop once per char
q_N/\,{
  e# Build the suffixes corresponding to top-of-stack and bottom-of-stack
  _W$m*
  e# Map each pair of Cartesian product to the suffix if one is the prefix of the other;
  e# otherwise remove from the array
  :${~1$,<=},{~\,>}%
  e# Filter out empty suffixes iff it's the first time round the loop
  La:L-
}*
e# If we generated an empty suffix then we've also looped enough times to generate all
e# of the keywords as suffixes corresponding to the empty fix, so do a set intersection
e# to test this condition.
](\M*&!


问:
Reverse a 1-dimensional array
Note: This challenge is not the same.

Challenge

Believe it or not, we haven't got ONE challenge for reversing one-dimensional arrays (although we've got one for n-dimensional ones)! This should operate only on the 1st dimension, not on all dimensions of an array.

Rules

Standard loopholes are denied

[[1, 2], [3, 4]] becomes [[3, 4], [1, 2]], not [[4, 3], [2, 1]].

This is code-golf, but no answer is accepted. Go beat the others!

You can get the array any way, except hardcoding. You can also get a string and process it.

The input will be an array (yes, commas or no commas, it needs to be an array).

Test cases

These are the test cases:

```<code>[1, 2, 3, 4]
[1, 2, 'hello', 'world!']
[[1, 2, 3, 4], [2, 3, 4, 1]]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
</code>```

These are the supposed results:

```<code>[4, 3, 2, 1]
['world!', 'hello', 2, 1]
[[2, 3, 4, 1], [1, 2, 3, 4]]
[23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
</code>```

You may accept input as [1 2 3 4], or even 1 2 3 4, or any other form or array your language has.

答:
Python 2, 19 bytes

```<code>print input()[::-1]
</code>```

Title: Reverse a 1-dimensional array

Body:
Python 2, 19 bytes

print input()[::-1]


答:
Python, 16 bytes

```<code>lambda l:l[::-1]
</code>```

Please examine this answer again. I was a bit lazy answering this :P

Thanks to 55749 (J843136028) for suggesting to convert this to a function :)

Title: Reverse a 1-dimensional array

Body:
Note: This challenge is not the same.

Challenge

Believe it or not, we haven't got ONE challenge for reversing one-dimensional arrays (although we've got one for n-dimensional ones)! This should operate only on the 1st dimension, not on all dimensions of an array.

Rules

Standard loopholes are denied

[[1, 2], [3, 4]] becomes [[3, 4], [1, 2]], not [[4, 3], [2, 1]].

This is code-golf, but no answer is accepted. Go beat the others!

You can get the array any way, except hardcoding. You can also get a string and process it.

The input will be an array (yes, commas or no commas, it needs to be an array).

Test cases

These are the test cases:

```<code>[1, 2, 3, 4]
[1, 2, 'hello', 'world!']
[[1, 2, 3, 4], [2, 3, 4, 1]]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
</code>```

These are the supposed results:

```<code>[4, 3, 2, 1]
['world!', 'hello', 2, 1]
[[2, 3, 4, 1], [1, 2, 3, 4]]
[23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
</code>```

You may accept input as [1 2 3 4], or even 1 2 3 4, or any other form or array your language has.

Body:
Python, 16 bytes

lambda l:l[::-1]

Please examine this answer again. I was a bit lazy answering this :P

Thanks to 55749 (J843136028) for suggesting to convert this to a function :)


答:
05AB1E, 1 byte

Code:

```<code>R
</code>```

Try it online!.

Title: Reverse a 1-dimensional array

Body:
05AB1E, 1 byte

Code:

R

Try it online!.


答:
Ruby, 14 bytes

you can't get simpler than this:

```<code>->a{a.reverse}
</code>```

Title: Reverse a 1-dimensional array

Body:
Ruby, 14 bytes

you can't get simpler than this:

->a{a.reverse}


答:
Python 3, 16 bytes

```<code>lambda x:x[::-1]
</code>```

This isn't even enough characters to post as an answer.

Title: Reverse a 1-dimensional array

Body:
Python 3, 16 bytes

lambda x:x[::-1]

This isn't even enough characters to post as an answer.


答:
Jelly, 1 byte

```<code>Ṛ
</code>```

Try it online! It reverses an array. (yay this is my first Jelly answer!)

Title: Reverse a 1-dimensional array

Body:
Jelly, 1 byte

Ṛ

Try it online! It reverses an array. (yay this is my first Jelly answer!)


答:
Pyth, <s>2</s> 1 byte<s>s</s>

1 byte off thanks to Doorknob

```<code>_
</code>```

_ is reverse, and Pyth takes implicit input. Yes, my first Pyth answer is an underscore.

Title: Reverse a 1-dimensional array

Body:
Pyth, <s>2</s> 1 byte<s>s</s>

1 byte off thanks to Doorknob

_

_ is reverse, and Pyth takes implicit input. Yes, my first Pyth answer is an underscore.


答:
Jolf, 1 + 1 = 2 bytes

```<code>_
</code>```

Try it here! (bonus for polyglot with Pyth?) _ reverses (negates) an array. (Make sure pretty output is on.)

Title: Reverse a 1-dimensional array

Body:
Jolf, 1 + 1 = 2 bytes

_

Try it here! (bonus for polyglot with Pyth?) _ reverses (negates) an array. (Make sure pretty output is on.)


答:
JavaScript ES6, 14 bytes

```<code>x=>x.reverse()
</code>```

Simple enough. Anonymous lambda that reverses an array.

Title: Reverse a 1-dimensional array

Body:
JavaScript ES6, 14 bytes

x=>x.reverse()

Simple enough. Anonymous lambda that reverses an array.


答:
C, 65 bytes

Takes a pointer to the start of the list and a list length.

```<code>void f(int*a,int s){int t=*a;*a=a[--s];a[s--]=t;if(s>1)f(a+1,s);}
</code>```

This is a recursive algorithm that swaps the first element with the last, and then runs the same function on the middle.

Ungolfed:

```<code>void f(int* a, int s){
  int t = a[0];
  a[0] = a[--s];
  a[s--] = t;
  if(s > 1){
    f(a + 1, s - 2);
  }
}
</code>```

Title: Reverse a 1-dimensional array

Body:
C, 65 bytes

Takes a pointer to the start of the list and a list length.

void f(int*a,int s){int t=*a;*a=a[--s];a[s--]=t;if(s>1)f(a+1,s);}

This is a recursive algorithm that swaps the first element with the last, and then runs the same function on the middle.

Ungolfed:

void f(int* a, int s){
  int t = a[0];
  a[0] = a[--s];
  a[s--] = t;
  if(s > 1){
    f(a + 1, s - 2);
  }
}


答:
Python 3, <s>31</s> <s>30</s> 28 bytes

The straight up equation from this wiki article

```<code>lambda s,n:(s-2)*(n-1)*n/2+n
</code>```

Thanks to @Mego for saving a byte!

Title: Polygonal numbers

Body:
A polygonal number is the number of dots in a k-gon of size n.

You will be given n and k, and your task is to write a program/function that outputs/prints the corresponding number.

Scoring

This is code-golf. Shortest solution in bytes wins.

Example

The 3rd hexagon number (k=6, n=3) is 28 because there are 28 dots above.

Testcases

Can be generated from this Pyth test suite.

Usage: two lines per testcase, n above, k below.

```<code>n    k  output
10   3  55
10   5  145
100  3  5050
1000 24 10990000
</code>```

Further information

In Wikipedia: https://en.wikipedia.org/wiki/Polygonal_number

In Wolfram Mathworld: http://mathworld.wolfram.com/PolygonalNumber.html

In OEIS Wiki: http://oeis.org/wiki/Polygonal_numbers

OEIS sequences for n-gonal numbers for various n: 3 (A000217), 4 (A000290), 5 (A000326), 6 (A000384), 7 (A000566), 8 (A000567), 9 (A001106), 10 (A001107), 11 (A051682), 12 (A051624), 13 (A051865), 14 (A051866), 15 (A051867), 16 (A051868), 17 (A051869), 18 (A051870), 19 (A051871), 20 (A051872), 21 (A051873), 22 (A051874), 23 (A051875), 24 (A051876)

Body:
Python 3, <s>31</s> <s>30</s> 28 bytes

The straight up equation from this wiki article

lambda s,n:(s-2)*(n-1)*n/2+n

Thanks to @Mego for saving a byte!


答:
Molecule, 8 bytes

```<code>I"Ar"+`n
</code>```

Explanation:

```<code>I"Ar"+`n
I"Ar"    Read input, append the command (reverse array) as a string.
     +   concatenate the 2 strings
      `n set the program's source code to that new string.
</code>```

Simple I/O:

```<code>Input    | Output
[5 "n"]    [n 5.0]
['n 3]     [3.0 n]
</code>```

Title: Reverse a 1-dimensional array

Body:
Molecule, 8 bytes

I"Ar"+`n

Explanation:

I"Ar"+`n
I"Ar"    Read input, append the command (reverse array) as a string.
     +   concatenate the 2 strings
      `n set the program's source code to that new string.

Simple I/O:

Input    | Output
[5 "n"]    [n 5.0]
['n 3]     [3.0 n]


问:
Golf Text into DNA

Text to DNA golf

Challenge

Convert input into a DNA output.

Algorithm

Convert text into ASCII code points (e.g. codegolf -> [99, 111, 100, 101, 103, 111, 108, 102])

String the ASCII codes together (e.g. 99111100101103111108102)

Convert to binary (e.g. 10100111111001101001011010001000011001101011011110000110010111111011000000110)

Pad 0s onto the end to make an even number of characters (e.g. 101001111110011010010110100010000110011010110111100001100101111110110000001100)

Replace 00 with A, 01 with C, 10 with G, and 11 with T (e.g. GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA)

Output

Test Cases

```<code>codegolf > GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA
ppcg > GGCTAATTGTCGCACTT
} > TTGG (padding)
</code>```

Specifications

This is code-golf

Your program must accept spaces in input.

Your program must work for codegolf.

答:
CJam, <s>24</s> 23 bytes

Thanks to Dennis for saving 1 byte in a really clever way. :)

```<code>l:isi2b2/Wf%2fb"AGCT"f=
</code>```

Test it here.

Explanation

Very direct implementation of the specification. The only interesting bit is the padding to an even number of zeros (which was actually Dennis's idea). Instead of treating the digits in each pair in the usual order, we make the second bit the most significant one. That means, ending in a single bit is identical to appending a zero to it, which means we don't have to append the zero at all.

```<code>l          e# Read input.
:i         e# Convert to character codes.
si         e# Convert to flat string and back to integer.
2b         e# Convert to binary.
2/         e# Split into pairs.
Wf%        e# Reverse each pair.
2fb        e# Convert each pair back from binary, to get a value in [0 1 2 3].
"AGCT"f=   e# Select corresponding letter for each number.
</code>```

Title: Golf Text into DNA

Body:
CJam, <s>24</s> 23 bytes

Thanks to Dennis for saving 1 byte in a really clever way. :)

l:isi2b2/Wf%2fb"AGCT"f=

Test it here.

Explanation

Very direct implementation of the specification. The only interesting bit is the padding to an even number of zeros (which was actually Dennis's idea). Instead of treating the digits in each pair in the usual order, we make the second bit the most significant one. That means, ending in a single bit is identical to appending a zero to it, which means we don't have to append the zero at all.

l          e# Read input.
:i         e# Convert to character codes.
si         e# Convert to flat string and back to integer.
2b         e# Convert to binary.
2/         e# Split into pairs.
Wf%        e# Reverse each pair.
2fb        e# Convert each pair back from binary, to get a value in [0 1 2 3].
"AGCT"f=   e# Select corresponding letter for each number.


答:
Pyth, 25 bytes

```<code>sm@"ACGT"id2Pc.B*4sjkCMQ2
</code>```

Try it here!

Explanation

Burrowing the padding trick from Martins CJam answer.

```
sm@"ACGT"id2Pc.B*4sjkCMQ2    # Q = input

                     CMQ     # Map each character of Q to its character code
                  sjk        # Join into one string and convert to an integer
              .B*4           # Mulitply with 4 and convert to binary
             c          2    # Split into pairs
            P                # Discard the last pair
 m                           # Map each pair d
         id2                 # Convert pair from binary to decimal
  @"ACGT"                    # Use the result ^ as index into a lookup string
s                            # Join the resulting list into on string
```

Title: Golf Text into DNA

Body:
Text to DNA golf

Challenge

Convert input into a DNA output.

Algorithm

Convert text into ASCII code points (e.g. codegolf -> [99, 111, 100, 101, 103, 111, 108, 102])

String the ASCII codes together (e.g. 99111100101103111108102)

Convert to binary (e.g. 10100111111001101001011010001000011001101011011110000110010111111011000000110)

Pad 0s onto the end to make an even number of characters (e.g. 101001111110011010010110100010000110011010110111100001100101111110110000001100)

Replace 00 with A, 01 with C, 10 with G, and 11 with T (e.g. GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA)

Output

Test Cases

```<code>codegolf > GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA
ppcg > GGCTAATTGTCGCACTT
} > TTGG (padding)
</code>```

Specifications

This is code-golf

Your program must accept spaces in input.

Your program must work for codegolf.

Body:
Pyth, 25 bytes

sm@"ACGT"id2Pc.B*4sjkCMQ2

Try it here!

Explanation

Burrowing the padding trick from Martins CJam answer.

sm@"ACGT"id2Pc.B*4sjkCMQ2    # Q = input

                     CMQ     # Map each character of Q to its character code
                  sjk        # Join into one string and convert to an integer
              .B*4           # Mulitply with 4 and convert to binary
             c          2    # Split into pairs
            P                # Discard the last pair
 m                           # Map each pair d
         id2                 # Convert pair from binary to decimal
  @"ACGT"                    # Use the result ^ as index into a lookup string
s                            # Join the resulting list into on string