答:
CJam (22 bytes)

```<code>q~dX.5@6048e5\/#-*9e3>
</code>```

Online demo

Dissection

A quick explanation of the maths: if the halflife is λ then after time t the proportion of the radioactive material remaining is (1/2)^(t/λ), so the proportion decayed is 1 - (1/2)^(t/λ).

```<code>q~d         e# Parse input, ensuring that the later division will use doubles
X.5@6048e5\ e# Rearrange stack to: m 1 0.5 6048e5 λ
/#-*        e# Div, pow, sub, mul, giving the total mass decayed after a week
9e3>        e# Is it OVER 9000! ?
</code>```

Title: Curiosity killed the cat?

Body:
CJam (22 bytes)

q~dX.5@6048e5\/#-*9e3>

Online demo

Dissection

A quick explanation of the maths: if the halflife is λ then after time t the proportion of the radioactive material remaining is (1/2)^(t/λ), so the proportion decayed is 1 - (1/2)^(t/λ).

q~d         e# Parse input, ensuring that the later division will use doubles
X.5@6048e5\ e# Rearrange stack to: m 1 0.5 6048e5 λ
/#-*        e# Div, pow, sub, mul, giving the total mass decayed after a week
9e3>        e# Is it OVER 9000! ?


问:
Alphabet to Number and Number to Alphabet

Challenge

In this challenge you have to take a number as input and output the corresponding letter of the alphabet, and vice versa. (1 <=> A, 2 <=> B) etc.

```<code>1 -> A
2 -> B
...
26 -> Z

A -> 1
B -> 2
...
Z -> 26
</code>```

Rules

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

The input will only consist of either an uppercase letter from A to Z or an integer from 1 to 26 inclusive.

Trailing whitespaces (space and newline) are allowed.

ContentLicense: CC BY-SA 3.0

Body:
Brainfuck, 445 Characters

More a proof of concept than a golfed code.
Requires Unsigned, Non-wrapping Brainfuck.

,[>+>+<<-]>[<+>-]>>++[->++++++<]>[-<<<+++++>>>]<<<<[->-<]>[,<++++[->------------<]++++[->>------------<<][-<<++++++++++>>]>[-<+>]>[-<<++++++++++>>]>++[->++++++<]>+[-<+++++>]<-[-<<<+>>>]<<<.>]>[[-<+<+>>]>++[->++++++<]>+[-<+++++>]<-[-<<->>]<<[->+>+<<]>>>++++++++++<+[>[->+>+<<]>[-<<-[>]>>>[<[-<->]<[>]>>[[-]>>+<]>-<]<<]>>>+<<[-<<+>>]<<<]>>>>>[-<<<<<+>>>>>]<<<<<-[->+>+<<]>[-<++++++++++>]<[-<->]++++[-<++++++++++++>]++++[->>++++++++++++<<]>>.<<<.>]

With Comments

,[>+>+<<-] Firstly Duplicate it across two buffers
>[<+>-] Move the second buffer back to the first buffer
>>++[->++++++<]>[-<<<+++++>>>] Establish 60 in the second buffer
<<<<
Compare Buffers 1 and 2
[->-<]
>
[ If there's still data in buffer 2
, Write the value in the units column to buffer two
<
++++
[->------------<] Subtract 12 from the units buffer
++++
[->>------------<<] Subtract 12 from the tens buffer
[-<<++++++++++>>] Multiply buffer three by ten into buffer 1
>
[-<+>] Add the units
>
[-<<++++++++++>>] Add the tens
>++ Add 65 to the buffer
[->++++++<]>+
[-<+++++>]
<- Actually we need 64 because A is 1
[-<<<+>>>] Add 64 to the first buffer
<<<
. Print the new letter
> Move to blank buffer
]
>
[ Otherwise we're a letter
[-<+<+>>] Copy it back over the first two buffers
>++ Write 64 to the buffer
[->++++++<]>+
[-<+++++>]
<-
[-<<->>] Subtract 64 from the letter
<<[->+>+<<]
>>>++++++++++< Copy pasted Division step x = current buffer y = 10 rest of the buffers are conveniently blank

+
[>[->+>+<<]>[-<<-[>]>>>[<[-<->]<[>]>>[[-]>>+<]>-<]<<]>>>+<<[-<<+>>]<<<]>>>>>[-<<<<<+>>>>>]<<<<<
-
[->+>+<<]
>[-<++++++++++>]
<[-<->]
++++
[-<++++++++++++>]
++++
[->>++++++++++++<<]
>>.<<<.>
]


问:
Smallest positive integer not yet appeared so that the sum of the first n elements is divisible by n

Task

Given positive integer n, output a(n) where a is the sequence defined below:

a(n) is the smallest positive integer not yet appeared so that the sum of the first n elements in the sequence is divisible by n.

Example

a(1) is 1 because it is the smallest positive integer that has not appeared in the sequence, and 1 is divisible by 1.

a(10) is 16 because look at the first nine elements: 1,3,2,6,8,4,11,5,14. They sum up to 54, so for the first ten elements to sum up to a multiple of 10, a(10) would need to have a remainder of 6 when divided by 10. 6 has already appeared, so a(10) is 16 instead.

Testcases

```<code>n     a(n)
1     1
2     3
3     2
4     6
5     8
6     4
7     11
8     5
9     14
10    16
11    7
12    19
13    21
14    9
15    24
16    10
17    27
18    29
19    12
20    32
100   62
1000  1618
10000 16180
</code>```

a(n) from n=1 to n=10000

References

OEIS A019444

答:
Pyth - <s>23</s> <s>21</s> 18 bytes

Can probably streamline the generation process with more lambdas or other tricks, but this is my first answer in more than a month.

```<code>eem=+Yf!|}TY%+TsYh
</code>```

Try it online here.

Body:
Pyth - <s>23</s> <s>21</s> 18 bytes

Can probably streamline the generation process with more lambdas or other tricks, but this is my first answer in more than a month.

eem=+Yf!|}TY%+TsYh

Try it online here.


问:
Dense Number Sequence
OEIS: A167171

A dense number is a number that has exactly as many prime divisors as non-prime divisors (including 1 and itself as divisors). Equivalently, it is either a prime or a product of two distinct primes. The first 100 dense numbers are:

```<code>2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 31, 33, 34, 35, 37, 38, 39, 41, 43, 46, 47, 51, 53, 55, 57, 58, 59, 61, 62, 65, 67, 69, 71, 73, 74, 77, 79, 82, 83, 85, 86, 87, 89, 91, 93, 94, 95, 97, 101, 103, 106, 107, 109, 111, 113, 115, 118, 119, 122, 123, 127, 129, 131, 133, 134, 137, 139, 141, 142, 143, 145, 146, 149, 151, 155, 157, 158, 159, 161, 163, 166, 167, 173, 177, 178, 179, 181, 183, 185, 187, 191, 193, 194
</code>```

Given a nonnegative integer n, output dense(n). n may be 0-indexed or 1-indexed.

Reference implementation (Sage)

import itertools

def dense_numbers():
    n = 1
    while True:
        prime_divisors = [x for x in divisors(n) if x.is_prime()]
        non_prime_divisors = [x for x in divisors(n) if not x.is_prime()]
        if len(prime_divisors) == len(non_prime_divisors):
            yield n
        n += 1

N = 20

print itertools.islice(dense_numbers(), N, N+1).next()
```

Try it online

答:
Python, 79 bytes

f=lambda n,k=2:n<1or-~f(n-(sum((k%i<1)+2*(k%i**2<1)for i in range(2,k))<3),k+1)
```

Uses 1-based indexing. Test it on Ideone.

Title: Dense Number Sequence

Body:
Python, 79 bytes

f=lambda n,k=2:n<1or-~f(n-(sum((k%i<1)+2*(k%i**2<1)for i in range(2,k))<3),k+1)

Uses 1-based indexing. Test it on Ideone.


问:
Play a sound, any sound
Your program has to make the computer produce a sound, any sound.

Shortest code wins, not sooner than 10 days after the first valid answer. If there is a tie, the one submitted sooner, wins.

The program should run on a reasonable, not too uncommon personal computer.

Opening a pop-up, message box, etc. (for example, on a web page) does not count, as they might or might not produce a sound, depending on a lot of settings.

Just entering a wrong command or invalid character on a console and receiving a warning beep does not count, just as the compiler/interpreter/OS beeping on an error or crash does not count either. Your code must be a valid program.

答:
bash (Mac OS X) 5

```<code>say a
</code>```

although stylistically I prefer the somewhat longer:

```<code>say 'Hello, Code Golf !'
</code>```

Title: Play a sound, any sound

Body:
bash (Mac OS X) 5

say a

although stylistically I prefer the somewhat longer:

say 'Hello, Code Golf !'


问:
Calculate the difficulty of a Code Golf question

Briefing

The difficulty of a Code Golf question can be calculated as such:

$$\text{clamp} \left( \left\lceil \left( \frac v a \div 700 \right) \times 10 \right\rceil, 0, 10 \right)$$

Where \$v\$ is the number of views a question has

and \$a\$ is the number of answers a question has

and \$⌈x⌉\$ is the ceiling operator.

Also:

$$\text{clamp}(x, min, max) = \begin{cases}
min & x < min \\
x   & min \le x \le max \\
max & max < x
\end{cases}$$

This question's current difficulty: ***

Task

Write a program that will take two integers (v and a) and output the difficulty in asterisks (*).

The input can be in the form of an array, a separated string or as separate function arguments

Test Data

```<code>Views   Answers Difficulty  Program Output
163     2       2           **
548     22      1           *
1452    24      1           *
1713    37      1           *
4162    32      2           **
3067    15      3           ***
22421   19      10          **********
</code>```

Example with pseudocode

```<code>v: 1713
a: 37
out = clamp(ceil(((v/a)/700)*10), 0, 10); // evaluates to 1
//program will output '*'
</code>```

The shortest code in bytes wins! Trailing/ leading spaces are allowed.

答:
C, <s>54</s>, <s>51</s>, <s>50</s>, 49 bytes

Assuming that v is positive or zero and a positive, the x < min clamping case is never met, since there is no way the result of the ceiling operation can be negative. Additionally, integer maths on non-negative values always yields the floor of the result, so we add 1 to get the ceiling.

This solution requires a write function, works on Linux at least.

```<code>F(v,a){write(1,"**********",(v/=a*70)>9?10:v+1);}
</code>```

Test main:

```<code>int main() {
  F(163, 2);
  putchar('\n');
  F(548, 22);
  putchar('\n');
  F(1452, 24);
  putchar('\n');
  F(1713, 37);
  putchar('\n');
  F(4162, 32);
  putchar('\n');
  F(3067, 15);
  putchar('\n');
  F(22421, 19);
  putchar('\n');
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
C, <s>54</s>, <s>51</s>, <s>50</s>, 49 bytes

Assuming that v is positive or zero and a positive, the x < min clamping case is never met, since there is no way the result of the ceiling operation can be negative. Additionally, integer maths on non-negative values always yields the floor of the result, so we add 1 to get the ceiling.

This solution requires a write function, works on Linux at least.

F(v,a){write(1,"**********",(v/=a*70)>9?10:v+1);}

Test main:

int main() {
  F(163, 2);
  putchar('\n');
  F(548, 22);
  putchar('\n');
  F(1452, 24);
  putchar('\n');
  F(1713, 37);
  putchar('\n');
  F(4162, 32);
  putchar('\n');
  F(3067, 15);
  putchar('\n');
  F(22421, 19);
  putchar('\n');
}


问:
Curiosity killed the cat?
Some people say curiosity killed the cat. Other say it was the box and poison. The RSPCA say Erwin Schrödinger needs to lose the right to own pets.

With animal rights activists outside his house. The <s>cat murderer</s> scientist Schrödinger has finally come up with his greatest invention. A special, radioactive mix of unobtanium and handwavium that can have any half life, and a single gram of the product is capable of killing any living creature. Unfortunately, when he tried to test it on his final cat: Bob, he forgot that cats have 9 lives, and so would need 9 grams to kill. With some water but no food, poor Bob will live exactly 1 week (7 days) if the product doesn't kill him first.

The task:
Given an input of a mass in milligrams and a half-life in milliseconds -  both integers which can exceed 2^31, write a program that outputs whether or not the mystery super product kills the cat, or if it's 1 week time limit expires first. Assume true/yes/1/anything specified in the answer is for when he does not die from starvation.

For the product to kill him, a total of 9 grams must decay. So out of a sample of 18 grams, 1 half-life must pass. If the sample contains less than or equal to 9 grams, this will never be achieved, and so it can be immediately assumed 1 week will pass before 9 grams decays.

You may assume:

Bob dies the microsecond 9 grams has decayed.

The change is mass due to decay does not matter.

All days and times follow generally accepted earth time.

The box Bob is sealed in is unbreakable and unopenable, so there is no chance of death from other causes.

Oxygen is also no issue.

If both happen at the exact same time either output is acceptable.

All inputs should be below 2^63-1

Test cases:

Example:

```<code>18000 604800001
</code>```

For 9 grams to decay, exactly 1 half life must pass (18000/2 = 9000 milligrams or 9 grams). 1 half life is 604800001 milliseconds, or 168 hours and 1 millisecond, or exactly 1 week and 1 millisecond. Since Bob dies of hunger at exactly 1 week, the output is false as he died from hunger just before the 9 gram product limit was reached

```<code>8000 40000 false

70000 800 true

18000 604800000 either

18000 604800001 false

18000 604799999 true

1 1 false

100000 1 true

1000000000 1000000000 true
</code>```

Scoring:
Naturally we want Bob's suffering to end quickly, and so a shorter half-life is best. Half-life and byte both end in E, so clearly the shortest byte count wins.

答:
Actually, 20 bytes

```<code>5╤:6048*/1½ⁿ1-*93╤*<
</code>```

Try it online!

Explanation:

```<code>5╤:6048*/1½ⁿ1-*93╤*<
5╤                    10**5
  :6048               6048
       *              6048*10**5 (milliseconds in 1 week)
        /             divide by half-life
         1½ⁿ          (1/2)**(^)
            1-        1-(^) (% of sample decayed after 1 week)
              *       multiply by sample mass (mass decayed after 1 week)
               93╤*   9*10**3 (9000)
                   <  is 9000 < sample mass decayed?
</code>```

Title: Curiosity killed the cat?

Body:
Actually, 20 bytes

5╤:6048*/1½ⁿ1-*93╤*<

Try it online!

Explanation:

5╤:6048*/1½ⁿ1-*93╤*<
5╤                    10**5
  :6048               6048
       *              6048*10**5 (milliseconds in 1 week)
        /             divide by half-life
         1½ⁿ          (1/2)**(^)
            1-        1-(^) (% of sample decayed after 1 week)
              *       multiply by sample mass (mass decayed after 1 week)
               93╤*   9*10**3 (9000)
                   <  is 9000 < sample mass decayed?


问:
Code golf ABC's: The ASCII Box Challenge
Given two positive integers, 'a' and 'b', output an ascii-art "box" that is a characters wide and b characters tall. For example, with '4' and '6':

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

Simple right? Here's the twist: The border of the box must be the characters of "a" and "b" alternating. This starts at the top left corner, and continues in a clockwise spiral. For example, the previous example with 4 and 6 should be

```<code>4646
6  4
4  6
6  4
4  6
6464
</code>```

A and B may be two-digit numbers. For example, the inputs "10" and "3" should output this:

```<code>1031031031
1        0
3013013013
</code>```

In order to keep the output relatively small, you do not have to support three or more digit numbers. Also, since inputs are restricted to positive integers, '0' is an invalid input, which you do not have to handle.

Here are some more test cases:

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

353
5 5
3 3
5 5
353

Input: (1, 1)
Output:

1

Input: (4, 4)
Output:

4444
4  4
4  4
4444

Input: (27, 1)
Output:

271271271271271271271271271

Input: (1, 17)
Output:

1
1
7
1
1
7
1
1
7
1
1
7
1
1
7
1
1

Input: (12, 34):
Output:

123412341234
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
432143214321
</code>```

You may take input and output in any reasonable format, and standard loopholes are banned. Since this is code-golf, the shortest answer in bytes wins!

答:
Pyth, <s>65</s> 51 bytes

```
<s>juXGhHX@GhHeH@jkQ~hZ{s[+L]0UhQ+R]thQUeQ+L]teQ_UhQ+R]0_UeQ)m*;hQeQ</s>
AQjuXGhHX@GhHeH@jkQ~hZ{s[,L0G,RtGH_,LtHG_,R0H)m*;GH
```

Try it online!

Body:
Pyth, <s>65</s> 51 bytes

<s>juXGhHX@GhHeH@jkQ~hZ{s[+L]0UhQ+R]thQUeQ+L]teQ_UhQ+R]0_UeQ)m*;hQeQ</s>
AQjuXGhHX@GhHeH@jkQ~hZ{s[,L0G,RtGH_,LtHG_,R0H)m*;GH

Try it online!


答:
Actually, 14 bytes

```<code>:70a\\u9ukm'**
</code>```

Try it online!

Takes advantage of the fact that 0 views and 0 answers is impossible, and thus ceil(v/a) > 0.

Explanation:

```<code>:70a\\u9ukm'**
:70             push 70 ([70 a v])
   a            invert stack ([v a 70])
    \\          integer division twice ([v//a//70])
      u         add 1 ([v//a//70 + 1])
       9uk      push 10, make stack into list ([[v//a//70+1, 10]])
          m     minimum of list
           '**  push "*", repeat
</code>```

Title: Calculate the difficulty of a Code Golf question

Body:
Briefing

The difficulty of a Code Golf question can be calculated as such:

$$\text{clamp} \left( \left\lceil \left( \frac v a \div 700 \right) \times 10 \right\rceil, 0, 10 \right)$$

Where \$v\$ is the number of views a question has

and \$a\$ is the number of answers a question has

and \$⌈x⌉\$ is the ceiling operator.

Also:

$$\text{clamp}(x, min, max) = \begin{cases}
min & x < min \\
x   & min \le x \le max \\
max & max < x
\end{cases}$$

This question's current difficulty: ***

Task

Write a program that will take two integers (v and a) and output the difficulty in asterisks (*).

The input can be in the form of an array, a separated string or as separate function arguments

Test Data

```<code>Views   Answers Difficulty  Program Output
163     2       2           **
548     22      1           *
1452    24      1           *
1713    37      1           *
4162    32      2           **
3067    15      3           ***
22421   19      10          **********
</code>```

Example with pseudocode

```<code>v: 1713
a: 37
out = clamp(ceil(((v/a)/700)*10), 0, 10); // evaluates to 1
//program will output '*'
</code>```

The shortest code in bytes wins! Trailing/ leading spaces are allowed.

Body:
Actually, 14 bytes

:70a\\u9ukm'**

Try it online!

Takes advantage of the fact that 0 views and 0 answers is impossible, and thus ceil(v/a) > 0.

Explanation:

:70a\\u9ukm'**
:70             push 70 ([70 a v])
   a            invert stack ([v a 70])
    \\          integer division twice ([v//a//70])
      u         add 1 ([v//a//70 + 1])
       9uk      push 10, make stack into list ([[v//a//70+1, 10]])
          m     minimum of list
           '**  push "*", repeat


答:
Dyalog APL, 19 bytes

9E3≤⊣-⊣×.5*6048E5÷⊢
```

9E3≤ is 9000 smaller than or equal to

⊣- the left argument (mass) minus

⊣× the left argument times

.5*  ½ to the power of

6048E5÷⊢ 604800000 divided by the right argument (half-life)

No need for parentheses, as APL is strictly right-to-left.

TryAPL online!

Title: Curiosity killed the cat?

Body:
Some people say curiosity killed the cat. Other say it was the box and poison. The RSPCA say Erwin Schrödinger needs to lose the right to own pets.

With animal rights activists outside his house. The <s>cat murderer</s> scientist Schrödinger has finally come up with his greatest invention. A special, radioactive mix of unobtanium and handwavium that can have any half life, and a single gram of the product is capable of killing any living creature. Unfortunately, when he tried to test it on his final cat: Bob, he forgot that cats have 9 lives, and so would need 9 grams to kill. With some water but no food, poor Bob will live exactly 1 week (7 days) if the product doesn't kill him first.

The task:
Given an input of a mass in milligrams and a half-life in milliseconds -  both integers which can exceed 2^31, write a program that outputs whether or not the mystery super product kills the cat, or if it's 1 week time limit expires first. Assume true/yes/1/anything specified in the answer is for when he does not die from starvation.

For the product to kill him, a total of 9 grams must decay. So out of a sample of 18 grams, 1 half-life must pass. If the sample contains less than or equal to 9 grams, this will never be achieved, and so it can be immediately assumed 1 week will pass before 9 grams decays.

You may assume:

Bob dies the microsecond 9 grams has decayed.

The change is mass due to decay does not matter.

All days and times follow generally accepted earth time.

The box Bob is sealed in is unbreakable and unopenable, so there is no chance of death from other causes.

Oxygen is also no issue.

If both happen at the exact same time either output is acceptable.

All inputs should be below 2^63-1

Test cases:

Example:

```<code>18000 604800001
</code>```

For 9 grams to decay, exactly 1 half life must pass (18000/2 = 9000 milligrams or 9 grams). 1 half life is 604800001 milliseconds, or 168 hours and 1 millisecond, or exactly 1 week and 1 millisecond. Since Bob dies of hunger at exactly 1 week, the output is false as he died from hunger just before the 9 gram product limit was reached

```<code>8000 40000 false

70000 800 true

18000 604800000 either

18000 604800001 false

18000 604799999 true

1 1 false

100000 1 true

1000000000 1000000000 true
</code>```

Scoring:
Naturally we want Bob's suffering to end quickly, and so a shorter half-life is best. Half-life and byte both end in E, so clearly the shortest byte count wins.

Body:
Dyalog APL, 19 bytes

9E3≤⊣-⊣×.5*6048E5÷⊢

9E3≤ is 9000 smaller than or equal to

⊣- the left argument (mass) minus

⊣× the left argument times

.5*  ½ to the power of

6048E5÷⊢ 604800000 divided by the right argument (half-life)

No need for parentheses, as APL is strictly right-to-left.

TryAPL online!


答:
Actually, 12 bytes

All credits to Dennis for his algorithm.

```<code>`w♂N;*2%Y`╓N
</code>```

Try it online!

```<code>`w♂N;*2%Y`╓N

`        `     define a function
 w             prime factorization in exponent form:
               18 = (2^1)*(3^2) becomes [[2,1],[3,2]]
  ♂N           get the last element (exponent) of each sublist
    ;*         dot-product with self; equivalent to squaring
               each item and then taking the sum
      2%Y      test divisibility by 2
          ╓    first (input) solutions to the above function
           N   get the last element.
</code>```

Title: Dense Number Sequence

Body:
OEIS: A167171

A dense number is a number that has exactly as many prime divisors as non-prime divisors (including 1 and itself as divisors). Equivalently, it is either a prime or a product of two distinct primes. The first 100 dense numbers are:

```<code>2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 31, 33, 34, 35, 37, 38, 39, 41, 43, 46, 47, 51, 53, 55, 57, 58, 59, 61, 62, 65, 67, 69, 71, 73, 74, 77, 79, 82, 83, 85, 86, 87, 89, 91, 93, 94, 95, 97, 101, 103, 106, 107, 109, 111, 113, 115, 118, 119, 122, 123, 127, 129, 131, 133, 134, 137, 139, 141, 142, 143, 145, 146, 149, 151, 155, 157, 158, 159, 161, 163, 166, 167, 173, 177, 178, 179, 181, 183, 185, 187, 191, 193, 194
</code>```

Given a nonnegative integer n, output dense(n). n may be 0-indexed or 1-indexed.

Reference implementation (Sage)

import itertools

def dense_numbers():
    n = 1
    while True:
        prime_divisors = [x for x in divisors(n) if x.is_prime()]
        non_prime_divisors = [x for x in divisors(n) if not x.is_prime()]
        if len(prime_divisors) == len(non_prime_divisors):
            yield n
        n += 1

N = 20

print itertools.islice(dense_numbers(), N, N+1).next()
```

Try it online

Body:
Actually, 12 bytes

All credits to Dennis for his algorithm.

`w♂N;*2%Y`╓N

Try it online!

`w♂N;*2%Y`╓N

`        `     define a function
 w             prime factorization in exponent form:
               18 = (2^1)*(3^2) becomes [[2,1],[3,2]]
  ♂N           get the last element (exponent) of each sublist
    ;*         dot-product with self; equivalent to squaring
               each item and then taking the sum
      2%Y      test divisibility by 2
          ╓    first (input) solutions to the above function
           N   get the last element.


问:
Is this square symmetrical?
Write a program or function that takes in a 4×4 text grid consisting of exactly 4 A's, 4 B's, 4 C's, and 4 D's, such as:

```<code>ACDC
BBCA
BADD
ABCD
</code>```

The ABCD's may be in any arrangement but there will always be 4 of each. You can assume the input is valid. If desired you can also assume it has a trailing newline and/or that it comes as one line in reading order, e.g. ACDCBBCABADDABCD. You may also replace the characters ABCD with 0123 or 1234 respectively, if desired (but that's all).

Output a truthy value if the text grid has any form of reflective or rotational symmetry. Specifically:

If there is a central horizontal line of symmetry. e.g.

```<code>BACD
BACD
BACD \___ bottom mirrors top
BACD /
</code>```

If there is a central vertical line of symmetry. e.g.

```<code>BCCB
DAAD
CAAC
BDDB
  \/___ right mirrors left
</code>```

If there is a diagonal line of symmetry (in either direction). e.g.

```<code>     ___ diagonally mirrored
    /
ABDC
BACD
DCAB
CDBA
    \___ diagonally mirrored
</code>```

If there is 90° rotational symmetry. e.g.

```<code>BDAB
ACCD    same if rotated 90 degrees (or 180 or 270)
DCCA
BADB
</code>```

If there is 180° rotational symmetry. e.g.

```<code>DBCA
BDCA    same if rotated 180 degrees
ACDB
ACBD
</code>```

(Note that translational symmetry doesn't come into play here.)

Output a falsy value if the grid doesn't have one of the symmetries mentioned above. e.g. the very first example grid.

The shortest code in bytes wins.

答:
CJam, 16 bytes

```<code>{{z_W%_}4*;])e=}
</code>```

An unnamed block which expects the input as a list of four strings on top of the stack and leaves a 0 (falsy) for asymmetric inputs and a positive integer (truthy) for symmetric inputs.

Test it here. Or run a full test suite.

Explanation

The symmetries of the square are the elements of the dihedral group of order 8 (which are just the 4 rotations of the square and the same 4 rotations of some reflected version of the square). It's not possible to generate this group from repeated application of a single permutation. But two reflections always give some rotation. Hence, the entire group can be generated by alternating between two reflections four times. (We just need to make sure that the two reflections give the 90 degree or 270 degree rotation, not 0 or 180.)

The challenge asks whether the input square is equal to any of the other 7 symmetries. So this answer just generates all of them and then checks whether the input is among the others.

```<code>{      e# Run this block 4 times.
  z_   e# Transpose the grid and duplicate it. (This is one type of reflection.)
  W%_  e# Reverse the lines and duplicate it. (This is another type of
       e# reflection. Together they rotate the grid by 90 degrees.)
}4*    e# The last element will be the original grid again.
;      e# Discard one copy of that original grid.
]      e# Wrap all symmetries in a list.
)      e# Pull off the original grid.
e=     e# Count how many times it appears among the other symmetries.
</code>```

To see how the repeated application of z and W% generates all symmetries, have a look at this "diagram":

```<code>     0123
     4567
     89ab
     cdef

     original

 z   048c       W%       37bf
-->  159d  ----------->  26ae
     26ae                159d
     37bf                048c

     diag. refl.         rot. 90 degrees ccw

 z   3210       W%       fedc
-->  7654  ----------->  ba98
     ba98                7654
     fedc                3210

     vert. refl.        rot. 180 degrees

 z   fb73       W%       c840
-->  ea62  ----------->  d951
     d951                ea62
     c840                fb73

     antidiag. refl.     rot. 270 degrees ccw

 z   cdef       W%       0123
-->  89ab  ----------->  4567
     4567                89ab
     0123                cdef

     horiz. refl.        original
</code>```

Title: Is this square symmetrical?

Body:
CJam, 16 bytes

{{z_W%_}4*;])e=}

An unnamed block which expects the input as a list of four strings on top of the stack and leaves a 0 (falsy) for asymmetric inputs and a positive integer (truthy) for symmetric inputs.

Test it here. Or run a full test suite.

Explanation

The symmetries of the square are the elements of the dihedral group of order 8 (which are just the 4 rotations of the square and the same 4 rotations of some reflected version of the square). It's not possible to generate this group from repeated application of a single permutation. But two reflections always give some rotation. Hence, the entire group can be generated by alternating between two reflections four times. (We just need to make sure that the two reflections give the 90 degree or 270 degree rotation, not 0 or 180.)

The challenge asks whether the input square is equal to any of the other 7 symmetries. So this answer just generates all of them and then checks whether the input is among the others.

{      e# Run this block 4 times.
  z_   e# Transpose the grid and duplicate it. (This is one type of reflection.)
  W%_  e# Reverse the lines and duplicate it. (This is another type of
       e# reflection. Together they rotate the grid by 90 degrees.)
}4*    e# The last element will be the original grid again.
;      e# Discard one copy of that original grid.
]      e# Wrap all symmetries in a list.
)      e# Pull off the original grid.
e=     e# Count how many times it appears among the other symmetries.

To see how the repeated application of z and W% generates all symmetries, have a look at this "diagram":

     0123
     4567
     89ab
     cdef

     original

 z   048c       W%       37bf
-->  159d  ----------->  26ae
     26ae                159d
     37bf                048c

     diag. refl.         rot. 90 degrees ccw

 z   3210       W%       fedc
-->  7654  ----------->  ba98
     ba98                7654
     fedc                3210

     vert. refl.        rot. 180 degrees

 z   fb73       W%       c840
-->  ea62  ----------->  d951
     d951                ea62
     c840                fb73

     antidiag. refl.     rot. 270 degrees ccw

 z   cdef       W%       0123
-->  89ab  ----------->  4567
     4567                89ab
     0123                cdef

     horiz. refl.        original


答:
Dyalog APL, <s>37</s> <s>19</s> 17 bytes

@ngn reduced it by 20 bytes!

8>≢(∪⊢,⌽¨,⍉¨)⍣≡⊂⎕
```

TryAPL online!

Title: Is this square symmetrical?

Body:
Write a program or function that takes in a 4×4 text grid consisting of exactly 4 A's, 4 B's, 4 C's, and 4 D's, such as:

```<code>ACDC
BBCA
BADD
ABCD
</code>```

The ABCD's may be in any arrangement but there will always be 4 of each. You can assume the input is valid. If desired you can also assume it has a trailing newline and/or that it comes as one line in reading order, e.g. ACDCBBCABADDABCD. You may also replace the characters ABCD with 0123 or 1234 respectively, if desired (but that's all).

Output a truthy value if the text grid has any form of reflective or rotational symmetry. Specifically:

If there is a central horizontal line of symmetry. e.g.

```<code>BACD
BACD
BACD \___ bottom mirrors top
BACD /
</code>```

If there is a central vertical line of symmetry. e.g.

```<code>BCCB
DAAD
CAAC
BDDB
  \/___ right mirrors left
</code>```

If there is a diagonal line of symmetry (in either direction). e.g.

```<code>     ___ diagonally mirrored
    /
ABDC
BACD
DCAB
CDBA
    \___ diagonally mirrored
</code>```

If there is 90° rotational symmetry. e.g.

```<code>BDAB
ACCD    same if rotated 90 degrees (or 180 or 270)
DCCA
BADB
</code>```

If there is 180° rotational symmetry. e.g.

```<code>DBCA
BDCA    same if rotated 180 degrees
ACDB
ACBD
</code>```

(Note that translational symmetry doesn't come into play here.)

Output a falsy value if the grid doesn't have one of the symmetries mentioned above. e.g. the very first example grid.

The shortest code in bytes wins.

Body:
Dyalog APL, <s>37</s> <s>19</s> 17 bytes

@ngn reduced it by 20 bytes!

8>≢(∪⊢,⌽¨,⍉¨)⍣≡⊂⎕

TryAPL online!


答:
Brachylog, <s>38</s> 36 bytes

```<code>@eL:1fbeL
(L;?:raL)(.;L$\.;L$/.;Lr.)
</code>```

Try it online!

This expects a list of strings as input. This prints either true. or false..

Explanation

Main predicate:

```<code>@eL    Split each line into a list of chars ; call that list of lists L
:1f    Find all symmetries
b      Remove the first one (the identity)
eL     L is an element of that list of symmetries
</code>```

Predicate 1: Output is one of the 8 symmetries of the input.

```<code>(
    L             L = Input
;             Or
    ?:raL         L = reverse all lines of the input
)
(
    .             Output = L
;             Or
    L$\.          Output = transpose of L
;             Or
    L$/.          Output = antitranspose of L
;             Or
    Lr.           Output = reverse of L
)
</code>```

Title: Is this square symmetrical?

Body:
Brachylog, <s>38</s> 36 bytes

@eL:1fbeL
(L;?:raL)(.;L$\.;L$/.;Lr.)

Try it online!

This expects a list of strings as input. This prints either true. or false..

Explanation

Main predicate:

@eL    Split each line into a list of chars ; call that list of lists L
:1f    Find all symmetries
b      Remove the first one (the identity)
eL     L is an element of that list of symmetries

Predicate 1: Output is one of the 8 symmetries of the input.

(
    L             L = Input
;             Or
    ?:raL         L = reverse all lines of the input
)
(
    .             Output = L
;             Or
    L$\.          Output = transpose of L
;             Or
    L$/.          Output = antitranspose of L
;             Or
    Lr.           Output = reverse of L
)


Title: Code golf ABC's: The ASCII Box Challenge

Body:
Given two positive integers, 'a' and 'b', output an ascii-art "box" that is a characters wide and b characters tall. For example, with '4' and '6':

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

Simple right? Here's the twist: The border of the box must be the characters of "a" and "b" alternating. This starts at the top left corner, and continues in a clockwise spiral. For example, the previous example with 4 and 6 should be

```<code>4646
6  4
4  6
6  4
4  6
6464
</code>```

A and B may be two-digit numbers. For example, the inputs "10" and "3" should output this:

```<code>1031031031
1        0
3013013013
</code>```

In order to keep the output relatively small, you do not have to support three or more digit numbers. Also, since inputs are restricted to positive integers, '0' is an invalid input, which you do not have to handle.

Here are some more test cases:

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

353
5 5
3 3
5 5
353

Input: (1, 1)
Output:

1

Input: (4, 4)
Output:

4444
4  4
4  4
4444

Input: (27, 1)
Output:

271271271271271271271271271

Input: (1, 17)
Output:

1
1
7
1
1
7
1
1
7
1
1
7
1
1
7
1
1

Input: (12, 34):
Output:

123412341234
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
432143214321
</code>```

You may take input and output in any reasonable format, and standard loopholes are banned. Since this is code-golf, the shortest answer in bytes wins!

Body:
Python 2, 199 bytes

w,h=input()
s=(`w`+`h`)*w*h
r=[s[:w]]+[[" "for i in[0]*w]for j in[0]*(h-2)]+[s[w+h-2:2*w+h-2][::-1]]*(h>1)
for y in range(1,h-1):r[y][w-1],r[y][0]=s[w+y-1],s[w+h+w-2-y]
print"\n".join(map("".join,r))


问:
Deciphering XKCD colors
Randall Munroe (author of XKCD) held a survey to give names to colors. The main outcome is a list of names for the 954 most common RGB monitor colors.

For ease of programming, here is the list in plain text: http://xkcd.com/color/rgb.txt. Beware, the first line is not data, but contains the license.

Write a program or function that takes a valid color name from above list as input and outputs the associated RGB color code. Your program does not have to handle invalid inputs in any defined manner.

Standard loopholes apply. Additionally, your answer must not use pre-defined (built-in or external) color code <-> color name maps. (This includes the linked list.) Shortest code in bytes wins. If you read from a file, the file's byte count must be included.

Examples:

```<code>dark peach -> #de7e5d
robin's egg blue -> #98eff9
pink/purple -> #ef1de7
</code>```

答:
Go, 6709 bytes

Code is 404 bytes, data is 6305 bytes

```<code>package main
import ("bytes"
"compress/flate"
"fmt"
"os")
func main(){t:=make([]byte,6643)
i:=os.Args[1]
copy(t,i)
s:=[]byte{byte(len(i))<<4|t[0]>>1&8|t[0]&7,t[1]&6<<5|t[2]&30|t[3]>>2&1,t[3]<<7|t[4]&1<<3|t[5]&20|t[6]&6<<4|t[7]&3,t[8]&3|t[9]&1<<3|t[10]&1<<4|t[11]&1<<5|t[12]&4}
f,_:=os.Open("f")
flate.NewReader(f).Read(t)
for i:=0;;i+=7{
if bytes.Equal(s,t[i:i+4]){fmt.Printf("#%X", t[i+4:i+7])
return}}}
</code>```

The Data is encoded with xxd -p. Extract into a file simply named f with xxd -r paste f. The code can be ran as go run file.go "tree green"

Title: Deciphering XKCD colors

Body:
Go, 6709 bytes

Code is 404 bytes, data is 6305 bytes

package main
import ("bytes"
"compress/flate"
"fmt"
"os")
func main(){t:=make([]byte,6643)
i:=os.Args[1]
copy(t,i)
s:=[]byte{byte(len(i))<<4|t[0]>>1&8|t[0]&7,t[1]&6<<5|t[2]&30|t[3]>>2&1,t[3]<<7|t[4]&1<<3|t[5]&20|t[6]&6<<4|t[7]&3,t[8]&3|t[9]&1<<3|t[10]&1<<4|t[11]&1<<5|t[12]&4}
f,_:=os.Open("f")
flate.NewReader(f).Read(t)
for i:=0;;i+=7{
if bytes.Equal(s,t[i:i+4]){fmt.Printf("#%X", t[i+4:i+7])
return}}}

The Data is encoded with xxd -p. Extract into a file simply named f with xxd -r paste f. The code can be ran as go run file.go "tree green"


答:
05AB1E, 13 bytes

```<code>4Fø€JÂD}\\)¹å
</code>```

Explanation

Uses the method expertly explained by Martin in his CJam answer.

```<code>4F     }       # 4 times do:
  ø€J          # zip and join each
     ÂD        # bifurcate, duplicate
        \\     # delete the top 2 items on the stack
          )    # wrap stack in list
           ¹å  # check if input is in that list
</code>```

Try it online

Title: Is this square symmetrical?

Body:
05AB1E, 13 bytes

4Fø€JÂD}\\)¹å

Explanation

Uses the method expertly explained by Martin in his CJam answer.

4F     }       # 4 times do:
  ø€J          # zip and join each
     ÂD        # bifurcate, duplicate
        \\     # delete the top 2 items on the stack
          )    # wrap stack in list
           ¹å  # check if input is in that list

Try it online


答:
TSQL, <s>229</s> 225 bytes

Be aware TSQL has no build-in for rotating, so this is part the code.

Returning -1 for true 0 for false

Golfed:

```<code>DECLARE @1 char(16)='BCCBDAADCAACBDDB'

DECLARE @i INT=0,@ char(16)=0WHILE @i<16SELECT
@=substring(@1,@i*4%16+@i/4+1,1)+@,@i+=1SELECT~count(*)/2FROM (SELECT
left(x,8)a,right(x,4)b,substring(x,9,4)c
FROM(values(@1),(@))x(x))x
WHERE a in(reverse(b+c),b+c,reverse(c+b))
</code>```

Ungolfed:

```<code>DECLARE @1 char(16)='BCCBDAADCAACBDDB'

DECLARE @i INT=0,@ char(16)=0
WHILE @i<16
  SELECT @=substring(@1,@i*4%16+@i/4+1,1)+@,@i+=1
SELECT~count(*)/2
FROM
  (SELECT left(x,8)a,right(x,4)b,substring(x,9,4)c
   FROM(values(@1),(@))x(x))x
WHERE a in(reverse(b+c),b+c,reverse(c+b))
</code>```

Fiddle

Title: Is this square symmetrical?

Body:
TSQL, <s>229</s> 225 bytes

Be aware TSQL has no build-in for rotating, so this is part the code.

Returning -1 for true 0 for false

Golfed:

DECLARE @1 char(16)='BCCBDAADCAACBDDB'

DECLARE @i INT=0,@ char(16)=0WHILE @i<16SELECT
@=substring(@1,@i*4%16+@i/4+1,1)+@,@i+=1SELECT~count(*)/2FROM (SELECT
left(x,8)a,right(x,4)b,substring(x,9,4)c
FROM(values(@1),(@))x(x))x
WHERE a in(reverse(b+c),b+c,reverse(c+b))

Ungolfed:

DECLARE @1 char(16)='BCCBDAADCAACBDDB'

DECLARE @i INT=0,@ char(16)=0
WHILE @i<16
  SELECT @=substring(@1,@i*4%16+@i/4+1,1)+@,@i+=1
SELECT~count(*)/2
FROM
  (SELECT left(x,8)a,right(x,4)b,substring(x,9,4)c
   FROM(values(@1),(@))x(x))x
WHERE a in(reverse(b+c),b+c,reverse(c+b))

Fiddle


答:
C#, 301 bytes

I'm sure there is a lot more golfing that can be done here but I'm just happy I got a solution that worked.

I found a bug where the bottom line was in the wrong order, damnit!

```<code>a=>b=>{var s=new string[b];int i=4,c=b-2,k=a;var t="";for(;i++<2*(a+b);)t+=t.EndsWith(a+"")?b:a;s[0]=t.Substring(0,a);if(b>2){for(i=0;++i<b-1;)s[i]=(a<2?t.Substring(1,c):t.Substring(2*a+c))[c-i]+(a>1?new string(' ',a-2)+t.Substring(a,c)[i-1]:"");for(;--k>=0;)s[b-1]+=t.Substring(a+c,a)[k];}return s;};
</code>```

Old version: 280 bytes

```<code>a=>b=>{var s=new string[b];int i=4,c=b-2;var t="";for(;i++<2*(a+b);)t+=t.EndsWith(a+"")?b:a;s[0]=t.Substring(0,a);if(b>2){for(i=0;++i<b-1;)s[i]=(a<2?t.Substring(1,c):t.Substring(2*a+c))[c-i]+(a>1?new string(' ',a-2)+t.Substring(a,c)[i-1]:"");s[b-1]=t.Substring(a+c,a);}return s;};
</code>```

Body:
C#, 301 bytes

I'm sure there is a lot more golfing that can be done here but I'm just happy I got a solution that worked.

I found a bug where the bottom line was in the wrong order, damnit!

a=>b=>{var s=new string[b];int i=4,c=b-2,k=a;var t="";for(;i++<2*(a+b);)t+=t.EndsWith(a+"")?b:a;s[0]=t.Substring(0,a);if(b>2){for(i=0;++i<b-1;)s[i]=(a<2?t.Substring(1,c):t.Substring(2*a+c))[c-i]+(a>1?new string(' ',a-2)+t.Substring(a,c)[i-1]:"");for(;--k>=0;)s[b-1]+=t.Substring(a+c,a)[k];}return s;};

Old version: 280 bytes

a=>b=>{var s=new string[b];int i=4,c=b-2;var t="";for(;i++<2*(a+b);)t+=t.EndsWith(a+"")?b:a;s[0]=t.Substring(0,a);if(b>2){for(i=0;++i<b-1;)s[i]=(a<2?t.Substring(1,c):t.Substring(2*a+c))[c-i]+(a>1?new string(' ',a-2)+t.Substring(a,c)[i-1]:"");s[b-1]=t.Substring(a+c,a);}return s;};


问:
A047841: Autobiographical numbers

Definition

Here is the process to describe a number:

For each number from 0 to 9 that is present in the number:

Write down the frequency of that digit and then the digit.

For example, for the number 10213223:

There is 1 occurrence of 0,

2 occurrences of 1,

3 occurrences of 2,

2 occurrences of 3.

Therefore, the number that describes 10213223 is 10213223 (10 from the first property, 21 from the second, etc.).

Note that the number of occurrences of a digit may be greater than 9.

Task

You are to print/output all numbers that describe themselves.

Specs

Standard loopholes apply, except that you are allowed to hardcode the output or store information related to the output in your program.

The numbers in the output can be in any order.

The numbers in the output are allowed to have duplicates.

You may use any separator, if you choose to print instead of output.

You are allowed to prefix and/or postfix output if you choose to print instead of output.

The separator and the prefix and the postfix may not contain any digits (U+0030 to U+0039).

The solution must compute in one day.

Full list (109 items)

```<code>22
10213223
10311233
10313314
10313315
10313316
10313317
10313318
10313319
21322314
21322315
21322316
21322317
21322318
21322319
31123314
31123315
31123316
31123317
31123318
31123319
31331415
31331416
31331417
31331418
31331419
31331516
31331517
31331518
31331519
31331617
31331618
31331619
31331718
31331719
31331819
1031223314
1031223315
1031223316
1031223317
1031223318
1031223319
3122331415
3122331416
3122331417
3122331418
3122331419
3122331516
3122331517
3122331518
3122331519
3122331617
3122331618
3122331619
3122331718
3122331719
3122331819
10413223241516
10413223241517
10413223241518
10413223241519
10413223241617
10413223241618
10413223241619
10413223241718
10413223241719
10413223241819
41322324151617
41322324151618
41322324151619
41322324151718
41322324151719
41322324151819
41322324161718
41322324161719
41322324161819
41322324171819
1051322314251617
1051322314251618
1051322314251619
1051322314251718
1051322314251719
1051322314251819
1051322325161718
1051322325161719
1051322325161819
1051322325171819
5132231425161718
5132231425161719
5132231425161819
5132231425171819
5132232516171819
106132231415261718
106132231415261719
106132231415261819
106132231426171819
106132231526171819
613223141526171819
1011112131415161718
1011112131415161719
1011112131415161819
1011112131415171819
1011112131416171819
1011112131516171819
1011112141516171819
1011113141516171819
1111213141516171819
10713223141516271819
101112213141516171819
</code>```

References

Autobiographical numbers: OEIS A047841

Biographical number: OEIS A047842

答:
dc, 487 bytes

Hardcoded the solution. I start with 22 and add the differences to get the the next numbers. Some returning operations like adding 1 five times in a row are stored in registers.

This is my first program ever written in dc so it can probably golfed a lot more.

[1+d1+d1+d1+d1+d]sa[1+d1+d1+d1+d97+d]sb[1+d1+d99+d1+d100+d]sc[1+d1+d1+d98+dlcx]sd[1+d100+d10000+d]se22d10213201+d98010+d2081+dlax11008995+dlax9800995+dlax208096+dlbxldx999891495+dlax2091108096+dlbxldx10410100909697+dldx30909100909798+dlcx9899+dlex1009999990079798+dlcx10909899+dlex4080909099989899+dlex1091000000+d100999998899089899+d1+d100+d10910000+d10 8^+d50709091 10 10^*+d397888989888989899+dlex10 6^+d10 8^+d10 10^+d10 12^+d1001 10 14^*+d9602010000000100000+d90398989999999900000+f

You can execute the program using dc -e "[solution]", where [solution] is the string above. It outputs the numbers in reverse order. dc -e "[solution]" | sort -n for output in the same order as the list.

Title: A047841: Autobiographical numbers


答:
JavaScript, 213 212 202

```<code>c=>a=>{for(a=$=a,c=_=c,l=c*a*2,b=0,s=Array(l+1).join(c+""+a),O=W=s.substr(0,a),W=W.substr(0,a-2).replace(/./g," ");--_;)O+="\n"+s[l-c+_]+W+s[$++];return O+"\n"+[...s.substr(l-a-c+1,a)].reverse().join``}
</code>```

Surely has room for improvement.

Edit: Saved a byte thanks to TheLethalCoder

Body:
JavaScript, 213 212 202

c=>a=>{for(a=$=a,c=_=c,l=c*a*2,b=0,s=Array(l+1).join(c+""+a),O=W=s.substr(0,a),W=W.substr(0,a-2).replace(/./g," ");--_;)O+="\n"+s[l-c+_]+W+s[$++];return O+"\n"+[...s.substr(l-a-c+1,a)].reverse().join``}

Surely has room for improvement.

Edit: Saved a byte thanks to TheLethalCoder


问:
Chess conversion
There's quite a lot of work that's been done in the world of chess.  For example, there is a standardized file format, .pgn, that describes a chess game, including the list of moves.  Additionally, there's another file format .fen, that describes a board position.  The challenge today is to convert a list of chess moves (in algebraic notation) to a board position.

Definitions

Position [a-h][1-8]:  Given by appending the row (file) and the column (rank).  Defines one of the 64 possible positions on the board.

Piece[KQRBNP]?:  Represents the King, Queen, Rook, Bishop, KNight, Pawn.  In algebraic notation, P is not used.  When used on a board, letters are uppercase if they are White, otherwise lowercase.

Move [KQRBN]?[a-h]?[1-8]?x?[a-h][1-8](=[KQRBN])?(+*?)?|O-O(-O): A piece followed by the position it is moving to.

If the piece is ambiguous, then the row, or the column, or both are given.

If the piece is capturing a piece, then x is placed between the piece and the position.

If the move is a castling, then O-O is given for king-side, otherwise O-O-O.

If a pawn is being promoted, the move is appended with = followed by the piece it is being promoted to.

If a move puts the king in check, it is appended with a +.

If a move puts the king in checkmate, its appended with #.

The color of the piece is determined by the turn number (White and black alternate turns, starting with black.)

Board(([1-8]|[KQRBNPkqrbnp])*\/){8}: Rows are given by listing the pieces in row order.  If there are empty squares, each run of empty square is given using the length of the run.  Rows are separated using /

A board's initial position is rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR, which represents:

```<code>rnbqkbnr
pppppppp

PPPPPPPP
RNBQKBNR
</code>```

You need to take a list of Moves and return a Board.  You can assume that your input is valid.

Examples

```<code>                     -> rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
e4                   -> rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR
e4,c5                -> rnbqkbnr/pp1ppppp/8/2p5/4P3/8/PPPP1PPP/RNBQKBNR
e4,d5,exd5,e5        -> rnbqkbnr/ppp2ppp/8/3Pp3/8/8/PPPP1PPP/RNBQKBNR
e4,d5,exd5,e5,dxe6   -> rnbqkbnr/ppp2ppp/4P3/8/8/8/PPPP1PPP/RNBQKBNR
e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4 -> r1bqk2r/ppp2pp1/4Pn2/2P4p/6nP/8/PPP2PPN/RNBQKB1R
e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4 -> r1bqk2r/ppp2pp1/4P3/2P4p/3Q2nP/6P1/PPP2n1N/RNB1KB1R
e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4,Bf4,O-O -> r1bq1rk1/ppp2pp1/4P3/2P4p/3Q1BnP/6P1/PPP2n1N/RN2KB1R
e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4,Bf4,O-O,Na3,Nxh1,O-O-O,Qg5,exf7+ -> r1b2rk1/ppp2Pp1/8/2P3qp/3Q1BnP/N5P1/PPP4N/2KR1B1n
e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4,Bf4,O-O,Na3,Nxh1,O-O-O,Qg5,exf7+,Kh7,Bxg5,Rd8,f8=Q -> r1br1Q2/ppp3pk/8/2P3Bp/3Q2nP/N5P1/PPP4N/2KR1B1n
e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4,Bf4,O-O,Na3,Nxh1,O-O-O,Qg5,exf7+,Kh7,Bxg5,Rd8,f8=Q,Ngf2,c6,Rd7,cxd7,b6,d8=Q,c6,Q4d6,Ba6,Qd8f6 -> r4Q2/p5pk/bppQ1Q2/6Bp/7P/N5P1/PPP2n1N/2KR1B1n
e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4,Bf4,O-O,Na3,Nxh1,O-O-O,Qg5,exf7+,Kh7,Bxg5,Rd8,f8=Q,Ngf2,c6,Rd7,cxd7,b6,d8=Q,c6,Q4d6,Ba6,Qd8f6,Rb8,Qdd8,b5,Qc5,b4,Qxb8,bxa3,Rd3,Nxd3+,Kd1,axb2,Bh3,b1=Q+,Kd2,Qxa2,Qh6+,gxh6,Qcd6,Qa1,Qbc7+,Kh8,Qdd8# -> 3Q3k/p1Q5/b1p4p/6Bp/7P/3n2PB/2PK3N/q6n
</code>```

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

Title: Chess conversion

Body:
Javascript (ES6), <s>1024</s> 995 bytes

This is an early and still bulky attempt. I just stopped optimizing it when the 1K limit was reached.

It's probably not bullet-proof and only considers promotions to a Queen. But it does pass the test case.

Edit: 995 bytes - a few obvious optimizations

Source

F=i=>{B=[];b=0;X=[8,2,4,12,16,4,2,8,1];for(n=120;n--;B[n]=n<8?X[n]|32:n<24?33:n>111?X[n-112]
:n>95|0);Y=j=>(M[j]?M[j].charCodeAt(0)-97:8)|(M[++j]?(8-M[j])*16:128);G=_=>(F&8||!(F&7^f&7))
&&(F&128||!(F&112^f&112))&&B[f]==p;Z=d=>{for(k=f,u=1;(k+=d)!=T;)u&=!B[k]};Q=(j,...D)=>D.some
(d=>(j&2?!((f-T)%d)&&(Z(f<T?d:-d),u):T-f==d||(j&&f-T==d))&&(S=f));i.split(',').forEach(m=>{
if(m[0]=='O'){S=b?4:116;m[4]?(T=S-2,B[S-1]=B[S-4],B[S-4]=0):(T=S+2,B[S+1]=B[S+3],B[S+3]=0)}
else{M=m.match(/([B-R])?([a-h])?(\d)?x?([a-h])?(\d)?(=Q)?/);p=X["QKBNRP".indexOf(M[1]||'P')+
3]|b;F=Y(2);M[4]?T=Y(4):(T=F,F=136);for(f=120,S=0;f--;)G()&&(p&4&&Q(2,15,17),p&8&&Q(2,1,16),
p&2&&Q(1,14,18,31,33),p&16&&Q(1,1,15,16,17),p&1&&Q(0,b-16,2*b-32));for(f=120;p&1&&!S&&f--;)
G()&&Q(0,b-15,b-17);B[S]&1&&(S-T)%16&&!B[T]&&(B[T+16-b]=0)}B[T]=B[S];B[S]=0;M[6]&&(B[T]^=13)
;b^=32});for(r='',y=0;y<8;y++){for(x=z=0;x<8;x++)(b=B[y*16+x])?(p=".PN.B...R...Q...K"[b&31],
r+=(z||'')+(b&32?p.toLowerCase():p),z=0):z++;r+=(z||'')+(y<7?'/':'')}return r}

Full executable snippet

F=i=>{B=[];b=0;X=[8,2,4,12,16,4,2,8,1];for(n=120;n--;B[n]=n<8?X[n]|32:n<24?33:n>111?X[n-112]:n>95|0);Y=j=>(M[j]?M[j].charCodeAt(0)-97:8)|(M[++j]?(8-M[j])*16:128);G=_=>(F&8||!(F&7^f&7))&&(F&128||!(F&112^f&112))&&B[f]==p;Z=d=>{for(k=f,u=1;(k+=d)!=T;)u&=!B[k]};Q=(j,...D)=>D.some(d=>(j&2?!((f-T)%d)&&(Z(f<T?d:-d),u):T-f==d||(j&&f-T==d))&&(S=f));i.split(',').forEach(m=>{if(m[0]=='O'){S=b?4:116;m[4]?(T=S-2,B[S-1]=B[S-4],B[S-4]=0):(T=S+2,B[S+1]=B[S+3],B[S+3]=0)}else{M=m.match(/([B-R])?([a-h])?(\d)?x?([a-h])?(\d)?(=Q)?/);p=X["QKBNRP".indexOf(M[1]||'P')+3]|b;F=Y(2);M[4]?T=Y(4):(T=F,F=136);for(f=120,S=0;f--;)G()&&(p&4&&Q(2,15,17),p&8&&Q(2,1,16),p&2&&Q(1,14,18,31,33),p&16&&Q(1,1,15,16,17),p&1&&Q(0,b-16,2*b-32));for(f=120;p&1&&!S&&f--;)G()&&Q(0,b-15,b-17);B[S]&1&&(S-T)%16&&!B[T]&&(B[T+16-b]=0)}B[T]=B[S];B[S]=0;M[6]&&(B[T]^=13);b^=32});for(r='',y=0;y<8;y++){for(x=z=0;x<8;x++)(b=B[y*16+x])?(p=".PN.B...R...Q...K"[b&31],r+=(z||'')+(b&32?p.toLowerCase():p),z=0):z++;r+=(z||'')+(y<7?'/':'')}return r}

console.log(F(
  "e4,d5,exd5,e5,dxe6,Bc5,Nf3,Nf6,d4,Nc6,dxc5,Ne5,h4,h5,Nh2,Neg4,g3,Nxf2,Qd4,N6g4,Bf4," +
  "O-O,Na3,Nxh1,O-O-O,Qg5,exf7+,Kh7,Bxg5,Rd8,f8=Q,Ngf2,c6,Rd7,cxd7,b6,d8=Q,c6,Q4d6,Ba6," +
  "Qd8f6,Rb8,Qdd8,b5,Qc5,b4,Qxb8,bxa3,Rd3,Nxd3+,Kd1,axb2,Bh3,b1=Q+,Kd2,Qxa2,Qh6+,gxh6," +
  "Qcd6,Qa1,Qbc7+,Kh8,Qdd8#"
));


问:
Match up to 10 in an array

Challenge

Given an array of single digit number, work out if any 2 of them add up to 10 and print them out

Example

Input

(1,2,3,4,5,5,6,7)

This returns ((4,6),(5,5),(3,7))

Input

(1,2,3,4,5)

This returns (). as there is only one 5

Input

(5,5,5,5,5)

This returns ((5,5),(5,5)) as there is odd number of 5s and each 5 can be used only once

Rules

Here are the rules!

Assume input will only be an unsorted array of positive single digit integers

Each number will be pair up only once, which means if there are three 5s it only form 1 pair (5,5). If there are (3,3,7) it will only form 1 pair (3,7)

For the input: You can use any type of parentheses(or lack of) as long as readers can tell that the input is a single array of numbers.

For the output: It must look like an array of pairs. Where the array is the same form as your input.(If you did not use any parenheses in your input, you have to use some kind of symbols so that any readers can tell they are pairs in an array)

Test Cases

```<code>(1,2,3,4,5,5,6,7) =((4,6),(5,5),(3,7))
(1,2,3,4,5) = ()
(5,5,5,5,5) = ((5,5),(5,5))
(1,2,3,3,4,5,6,7)=((3,7),(4,6))
(9,8,7,6,4,4,3,1)=((9,1),(7,3),(6,4))
</code>```

Good luck!

The shorter an answer is, the better!

Edit 1: update the rules and Testcases from comments

Edit 2: update rules to define format of input.

Edit 3: update rules to define format of output. trying to be as accommodating as possible.

答:
Perl 52

```<code>perl -ne '$a{$y=9-$_}&&0*$a{$y++}--*print"$y,$_"or$a{$_-1}++'
</code>```

Proof :

```<code>> cat test
1
2
3
4
5
5
6
7
> perl -ne '$a{$y=9-$_}&&0*$a{$y++}--*print"$y,$_"or$a{$_-1}++' < test
5,5
4,6
3,7
</code>```

And there is an ungolfed commented code :

```<code>while(<>) {     # made by the -n option

    # We are looking for (P,Q) pairs where P+Q=10
    # Each P entry will come in $_="P\n" (because $_ will not be chopped)
    # We choose to store the number of occurence of P in $a{P-1}
    # (For instance, if there have been five '3's in the input, then $a{2}=5)

    $y=9-$_;        # if Q=P-10, then $y=Q-1
    if ($a{$y}) {   # check if there was a Q (so $a{Q-1} != 0)
        $a{$y++}--;   # If so 'consume' this Q, and let $y=Q
        print"$y,$_"; # ... and output "Q,P\n"
    } else {
        $a{$_-1}++;   # P is not forming a new pair, so 'count it'.
                    # $a{$_} would not work because of the un-chopped \n, thus the '-1'
    }

}
</code>```

Maybe the explanations looks like pidgin French (I'm not a native english writer), so if someone wants to edit it and make it more understandable, please do so.

Title: Match up to 10 in an array

Body:
Perl 52

perl -ne '$a{$y=9-$_}&&0*$a{$y++}--*print"$y,$_"or$a{$_-1}++'

Proof :

> cat test
1
2
3
4
5
5
6
7
> perl -ne '$a{$y=9-$_}&&0*$a{$y++}--*print"$y,$_"or$a{$_-1}++' < test
5,5
4,6
3,7

And there is an ungolfed commented code :

while(<>) {     # made by the -n option

    # We are looking for (P,Q) pairs where P+Q=10
    # Each P entry will come in $_="P\n" (because $_ will not be chopped)
    # We choose to store the number of occurence of P in $a{P-1}
    # (For instance, if there have been five '3's in the input, then $a{2}=5)

    $y=9-$_;        # if Q=P-10, then $y=Q-1
    if ($a{$y}) {   # check if there was a Q (so $a{Q-1} != 0)
        $a{$y++}--;   # If so 'consume' this Q, and let $y=Q
        print"$y,$_"; # ... and output "Q,P\n"
    } else {
        $a{$_-1}++;   # P is not forming a new pair, so 'count it'.
                    # $a{$_} would not work because of the un-chopped \n, thus the '-1'
    }

}

Maybe the explanations looks like pidgin French (I'm not a native english writer), so if someone wants to edit it and make it more understandable, please do so.


问:
Convert from base 10 to base 2 without built-in base conversions
Background:

You have been given an assignment to convert base 10 numbers to base 2 without using any premade base conversion functions. You can't use any imported libraries either.

Problem:

Convert an input string from base 10 (decimal) to base 2 (binary). You may not use any premade base conversion code/functions/methods, or imported libraries. Since this is code-golf, the shortest answer in bytes will win.

Input will be anything from -32768 to 32767 (include sign byte handling in your code)

答:
Haskell, 66 bytes

```<code>c 0=0
c n=c(div n 2)*10+mod n 2
b('-':r)='-':b r
b r=show.c.read$r
</code>```

Call with b "-1023", add main=interact b for a complete program or
try it on Ideon.

c performs the conversion for positive integers.

b r=show.c.read$r converts a string to a number, applies c and converts back to string.

b('-':r)='-':b r strips a possible leading - and re-appends it to the result.

Body:
Haskell, 66 bytes

c 0=0
c n=c(div n 2)*10+mod n 2
b('-':r)='-':b r
b r=show.c.read$r

Call with b "-1023", add main=interact b for a complete program or
try it on Ideon.

c performs the conversion for positive integers.

b r=show.c.read$r converts a string to a number, applies c and converts back to string.

b('-':r)='-':b r strips a possible leading - and re-appends it to the result.


问:
Print a 10 by 10 grid of asterisks

Background

This is a standard textbook example to demonstrate for loops.

This is one of the first programs I learnt when I started learning programming ~10 years ago.

Task

You are to print this exact text:

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

Specs

You may have extra trailing newlines.

You may have extra trailing spaces (U+0020) at the end of each line, including the extra trailing newlines.

Scoring

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

答:
Jade & CSS, <s>41</s> 36 bytes

```<code>- for (x=0;x++<10;)
  **********<br>
</code>```

Jade is a HTML pre-processor. I'm unsure if using this is breaking any rule or if I have to include something else in the byte count. This also beats my previous entry of 60 bytes.

See it on Codepen: http://codepen.io/409/pen/ZOPgdJ

Thanks to Business Cat for saving 5 bytes.

Title: Print a 10 by 10 grid of asterisks

Body:
Jade & CSS, <s>41</s> 36 bytes

- for (x=0;x++<10;)
  **********<br>

Jade is a HTML pre-processor. I'm unsure if using this is breaking any rule or if I have to include something else in the byte count. This also beats my previous entry of 60 bytes.

See it on Codepen: http://codepen.io/409/pen/ZOPgdJ

Thanks to Business Cat for saving 5 bytes.


问:
Output the nth rational number according to the Stern-Brocot sequence
The Stern-Brocot sequence is a Fibonnaci-like sequence which can be constructed as follows:

Initialise the sequence with s(1) = s(2) = 1

Set counter n = 1

Append s(n) + s(n+1) to the sequence

Append s(n+1) to the sequence

Increment n, return to step 3

This is equivalent to:

Amongst other properties, the Stern-Brocot sequence can be used to generate every possible positive rational number. Every rational number will be generated exactly once, and it will always appear in its simplest terms; for example, 1/3 is the 4th rational number in the sequence, but the equivalent numbers 2/6, 3/9 etc won't appear at all.

We can define the nth rational number as r(n) = s(n) / s(n+1), where s(n) is the nth Stern-Brocot number, as described above.

Your challenge is to write a program or function which will output the nth rational number generated using the Stern-Brocot sequence.

The algorithms described above are 1-indexed; if your entry is 0-indexed, please state in your answer

The algorithms described are for illustrative purposes only, the output can be derived in any way you like (other than hard-coding)

Input can be via STDIN, function parameters, or any other reasonable input mechanism

Ouptut can be to STDOUT, console, function return value, or any other reasonable output stream

Output must be as a string in the form a/b, where a and b are the relevant entries in the Stern-Brocot sequence. Evaluating the fraction before output is not permissable. For example, for input 12, output should be 2/5, not 0.4.

Standard loopholes are disallowed

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

Test cases

The test cases here are 1-indexed.

```<code>n    r(n)
--  ------
1    1/1
2    1/2
3    2/1
4    1/3
5    3/2
6    2/3
7    3/1
8    1/4
9    4/3
10   3/5
11   5/2
12   2/5
13   5/3
14   3/4
15   4/1
16   1/5
17   5/4
18   4/7
19   7/3
20   3/8
50   7/12
100  7/19
1000 11/39
</code>```

OEIS entry: A002487

Excellent Numberphile video discussing the sequence: Infinite Fractions

答:
Haskell, <s>78 77 65</s> 58 bytes

Shamelessly stealing the optimized approach gives us:

```<code>(s#t)0=show s++'/':show t
(s#t)n=t#(s+t-2*mod s t)$n-1
1#1
</code>```

Thanks to @nimi for golfing a few bytes using an infix function!

(Still) uses 0-based indexing.

The old approach:

```<code>s=(!!)(1:1:f 0)
f n=s n+s(n+1):s(n+1):(f$n+1)
r n=show(s n)++'/':(show.s$n+1)
</code>```

Damn the output format... And indexing operators. EDIT: And precedence.

Fun fact: if heterogenous lists were a thing, the last line could be:

```<code>r n=show>>=[s!!n,'/',s!!(n+1)]
</code>```

Body:
Haskell, <s>78 77 65</s> 58 bytes

Shamelessly stealing the optimized approach gives us:

(s#t)0=show s++'/':show t
(s#t)n=t#(s+t-2*mod s t)$n-1
1#1

Thanks to @nimi for golfing a few bytes using an infix function!

(Still) uses 0-based indexing.

The old approach:

s=(!!)(1:1:f 0)
f n=s n+s(n+1):s(n+1):(f$n+1)
r n=show(s n)++'/':(show.s$n+1)

Damn the output format... And indexing operators. EDIT: And precedence.

Fun fact: if heterogenous lists were a thing, the last line could be:

r n=show>>=[s!!n,'/',s!!(n+1)]


答:
Ruby, 128 bytes

```<code>->w,h{s="%d%d"%[w,h]*q=w+h;a=[s[0,w]];(h-2).times{|i|a<<(s[2*q-5-i].ljust(w-1)+s[w+i,1])[-w,w]};puts a,h>1?(s[q-2,w].reverse):p}
</code>```

Outputs trailing newline if height is 1.

Ideone link: https://ideone.com/96WYHt

Body:
Ruby, 128 bytes

->w,h{s="%d%d"%[w,h]*q=w+h;a=[s[0,w]];(h-2).times{|i|a<<(s[2*q-5-i].ljust(w-1)+s[w+i,1])[-w,w]};puts a,h>1?(s[q-2,w].reverse):p}

Outputs trailing newline if height is 1.

Ideone link: https://ideone.com/96WYHt


问:
Solve a Solitaire Chess Puzzle
Recently, I was introduced to a puzzle game known as Solitaire Chess. I'll summarize the rules here:

The board is a 4x4 checkerboard.

All pieces are the same color (no teams) and all pieces can capture any other piece.

Every move must be a capture. No moving to empty squares.

There must be exactly one piece remaining at the end.

All pieces move exactly like they do in chess, with one modification: the pawn can capture in any diagonal direction (which technically makes it a ferz). For the benefit of those who may not know, I have included movement diagrams.

None of the other rules of chess (such as check, castling, etc.) apply here. It's all about captures.

King (K)

```<code>K * . . | * K * . | * * * .
* * . . | * * * . | * K * .
. . . . | . . . . | * * * .
. . . . | . . . . | . . . .
</code>```

Queen (Q)

```<code>Q * * * | * Q * * | * * * .
* * . . | * * * . | * Q * *
* . * . | . * . * | * * * .
* . . * | . * . . | . * . *
</code>```

Rook (R)

```<code>R * * * | * R * * | . * . .
* . . . | . * . . | * R * *
* . . . | . * . . | . * . .
* . . . | . * . . | . * . .
</code>```

Bishop (B)

```<code>B . . . | . B . . | * . * .
. * . . | * . * . | . B . .
. . * . | . . . * | * . * .
. . . * | . . . . | . . . *
</code>```

Knight (N)

```<code>N . . . | . N . . | . . . *
. . * . | . . . * | . N . .
. * . . | * . * . | . . . *
. . . . | . . . . | * . * .
</code>```

Pawn (P)

```<code>P . . . | . P . . | * . * .
. * . . | * . * . | . P . .
. . . . | . . . . | * . * .
. . . . | . . . . | . . . .
</code>```

Input/output

For reference, the sample puzzle from the Solitaire Chess webpage will be used:

```<code>. . . .
. B . .
R P . .
. . . N
</code>```

The solution is to take the pawn with the knight, then take the knight with the rook, and finally take the bishop with the rook.

Input

Input must be in one of three forms; you are free to pick the one that is most convenient for you.

A string of characters such as .....B..RP.....N, with or without newlines. The character representing a blank space may be any character that isn't one of KQRBNP.

A list of lists (or a flattened list) where the elements are either characters or numbers, like so: [['.', '.', '.', '.'], ['.', 'B', '.', '.'], ['R', 'P', '.', '.'], ['.', '.', '.', 'N']] or [[0, 0, 0, 0], [0, 4, 0, 0], [3, 6, 0, 0], [0, 0, 0, 5]]. For the former, the character that represents a blank space may be anything that isn't one of KQRBNP. For the latter, I've given pieces the number that corresponds to their rank in my earlier list of moves (1 is a king, 4 is a bishop, 6 is a pawn, etc.). You are free to change the numbering.

A list of coordinates where each element has the form [x, y, 'c'], like so: [[1, 2, 'B'], [0, 1, 'R'], [1, 1, 'P'], [3, 0, 'N']].

If you pick one of the list-based input formats, the separators and delimiters may be any reasonable and understandable characters.

Output

Output must be a sequence of moves or a sequence of board states. Some puzzles have more than one solution; you may output one or all of them. If you choose to output a sequence of board states, each board must be in one of the three input formats, with a reasonable separator (such as newlines) between them.

If you choose to output a sequence of moves, they must be expressed as a list of pairs of coordinate pairs, like so: [[[3,0], [1,1]], [[0,1], [1,1]], [[1,1], [1,2]]]. [0,0] represents the bottom left corner, and again, separating and delimiting characters may be any reasonable choice.

If a given board cannot be solved, output any falsy value (0, empty string, etc.). If a given board has fewer than two pieces, behavior is undefined.

Test Cases

Note: outputs are only given as a list of pairs of coordinates since the other formats should be fairly easy to check for correctness (and I didn't feel like typing out all the possible output formats). Also, for the puzzles that have more than one solution, only one possibility is provided.

Input 1:

```<code>. . . N
. . . .
. R . .
. . B .

...N.....R....B.

[['.', '.', '.', 'N'], ['.', '.', '.', '.'], ['.', 'R', '.', '.'], ['.', '.', 'B', '.']]

[[0, 0, 0, 5], [0, 0, 0, 0], [0, 3, 0, 0], [0, 0, 4, 0]]

[[3, 3, 'N'], [1, 1, 'R'], [2, 0, 'B']]
</code>```

Output 1:

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

Input 2:

```<code>. . . .
. B . .
R P . .
. . . N

.....B..RP.....N

[['.', '.', '.', '.'], ['.', 'B', '.', '.'], ['R', 'P', '.', '.'], ['.', '.', '.', 'N']]

[[0, 0, 0, 0], [0, 4, 0, 0], [3, 6, 0, 0], [0, 0, 0, 5]]

[[1, 2, 'B'], [0, 1, 'R'], [1, 1, 'P'], [3, 0, 'N']]
</code>```

Output 2:

```<code>Q * * * | * Q * * | * * * .
* * . . | * * * . | * Q * *
* . * . | . * . * | * * * .
* . . * | . * . . | . * . *
</code>```0

Input 3:

```<code>Q * * * | * Q * * | * * * .
* * . . | * * * . | * Q * *
* . * . | . * . * | * * * .
* . . * | . * . . | . * . *
</code>```1

Output 3:

```<code>Q * * * | * Q * * | * * * .
* * . . | * * * . | * Q * *
* . * . | . * . * | * * * .
* . . * | . * . . | . * . *
</code>```2

Input 4:

```<code>. . . N
. . . R
R B B .
N P P .

...N...RRBB.NPP.

[['.', '.', '.', 'N'], ['.', '.', '.', 'R'], ['R', 'B', 'B', '.'], ['N', 'P', 'P', '.']]

[[0, 0, 0, 5], [0, 0, 0, 3], [3, 4, 4, 0], [5, 6, 6, 0]]

[[3, 3, 'N'], [3, 2, 'R'], [0, 1, 'R'], [1, 1, 'B'], [2, 1, 'B'], [0, 0, 'N'], [1, 0, 'P'], [2, 0, 'P']]
</code>```

Output 4:

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

Input 5:

```<code>P . . .
. R . .
R . R .
. R . .

P....R..R.R..R..

[['P', '.', '.', '.'], ['.', 'R', '.', '.'], ['R', '.', 'R', '.'], ['.', 'R', '.', '.']]

[[6, 0, 0, 0], [0, 3, 0, 0], [3, 0, 3, 0], [0, 3, 0, 0]]

[[0, 3, 'P'], [1, 2, 'R'], [0, 1, 'R'], [2, 1, 'R'], [1, 0, 'R']]
</code>```

Output 5:

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

Input 6:

```<code>. P . N
K . . .
. . B .
. . R Q

.P.NK.....B...RQ

[['.', 'P', '.', 'N'], ['K', '.', '.', '.'], ['.', '.', 'B', '.'], ['.', '.', 'R', 'Q']]

[[0, 6, 0, 5], [1, 0, 0, 0], [0, 0, 4, 0], [0, 0, 3, 2]]

[[1, 3, 'P'], [3, 3, 'N'], [0, 2, 'K'], [2, 1, 'B'], [2, 0, 'R'], [3, 0, 'Q']]
</code>```

Output 6:

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

Title: Solve a Solitaire Chess Puzzle

Body:
Haskell, <s>226</s> <s>195</s> <s>191</s> 188 bytes

Returns a list of all solutions. Each solution is a list of moves.
Returns an empty list if there is no solution.

Saved 4 bytes Thanks to Lynn.

Try it online

m"P"=[2]
m"N"=[5]
m"K"=[1,2]
m"R"=[1,4,9]
m"B"=[2,8,18]
m _=m"B"++m"R"
l%x=[z|z<-l,fst z/=x]
f[_]=[[]]
f l=[(i,j):r|(i@(s,t),a)<-l,(j@(u,v),_)<-l,(s-u)^2+(t-v)^2`elem`m a,r<-f$(j,a):l%i%j]

Usage:

main = do
    print $ f [((3, 3), "N"), ((1, 1), "R")]
    putStrLn""
    mapM_ print $ f [((3, 3), "N"), ((1, 1), "R"), ((2, 0), "B")]
    putStrLn""
    mapM_ print $ f [((1, 2), "B"), ((0, 1), "R"), ((1, 1), "P"), ((3, 0), "N")]
    putStrLn""
    mapM_ print $ f [((1, 3), "P"), ((3, 3), "N"), ((0, 2), "K"), ((2, 1), "B"), ((2, 0), "R"), ((3, 0), "Q")]

Output:

[]

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

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

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


答:
C (GCC), 79 bytes

Uses 0-based indexing.

s(n){return!n?:n%2?s(n/2):s(-~n/2)+s(~-n/2);}r(n){printf("%d/%d",s(n),s(n+1));}
```

Ideone

Title: Output the nth rational number according to the Stern-Brocot sequence

Body:
The Stern-Brocot sequence is a Fibonnaci-like sequence which can be constructed as follows:

Initialise the sequence with s(1) = s(2) = 1

Set counter n = 1

Append s(n) + s(n+1) to the sequence

Append s(n+1) to the sequence

Increment n, return to step 3

This is equivalent to:

Amongst other properties, the Stern-Brocot sequence can be used to generate every possible positive rational number. Every rational number will be generated exactly once, and it will always appear in its simplest terms; for example, 1/3 is the 4th rational number in the sequence, but the equivalent numbers 2/6, 3/9 etc won't appear at all.

We can define the nth rational number as r(n) = s(n) / s(n+1), where s(n) is the nth Stern-Brocot number, as described above.

Your challenge is to write a program or function which will output the nth rational number generated using the Stern-Brocot sequence.

The algorithms described above are 1-indexed; if your entry is 0-indexed, please state in your answer

The algorithms described are for illustrative purposes only, the output can be derived in any way you like (other than hard-coding)

Input can be via STDIN, function parameters, or any other reasonable input mechanism

Ouptut can be to STDOUT, console, function return value, or any other reasonable output stream

Output must be as a string in the form a/b, where a and b are the relevant entries in the Stern-Brocot sequence. Evaluating the fraction before output is not permissable. For example, for input 12, output should be 2/5, not 0.4.

Standard loopholes are disallowed

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

Test cases

The test cases here are 1-indexed.

```<code>n    r(n)
--  ------
1    1/1
2    1/2
3    2/1
4    1/3
5    3/2
6    2/3
7    3/1
8    1/4
9    4/3
10   3/5
11   5/2
12   2/5
13   5/3
14   3/4
15   4/1
16   1/5
17   5/4
18   4/7
19   7/3
20   3/8
50   7/12
100  7/19
1000 11/39
</code>```

OEIS entry: A002487

Excellent Numberphile video discussing the sequence: Infinite Fractions

Body:
C (GCC), 79 bytes

Uses 0-based indexing.

s(n){return!n?:n%2?s(n/2):s(-~n/2)+s(~-n/2);}r(n){printf("%d/%d",s(n),s(n+1));}

Ideone


答:
MATL, <s>32</s> 30 bytes

```<code>1i:"tt@TF-)sw@)v]tGq)V47bG)Vhh
</code>```

This uses a direct approach: generates enough members of the sequence, picks the two desired ones and formats the output.

Try it online!

Body:
MATL, <s>32</s> 30 bytes

1i:"tt@TF-)sw@)v]tGq)V47bG)Vhh

This uses a direct approach: generates enough members of the sequence, picks the two desired ones and formats the output.

Try it online!


答:
Python 2, <s>85</s> 81 bytes

```<code>x,s=input(),[1,1]
for i in range(x):s+=s[i]+s[i+1],s[i+1]
print`s[x-1]`+"/"+`s[x]`
</code>```

This submission is 1-indexed.

Using a recursive function, 85 bytes:

```<code>s=lambda x:int(x<1)or x%2 and s(x/2)or s(-~x/2)+s(~-x/2)
lambda x:`s(x)`+"/"+`s(x+1)`
</code>```

If an output like True/2 is acceptable, here's one at 81 bytes:

```<code>s=lambda x:x<1 or x%2 and s(x/2)or s(-~x/2)+s(~-x/2)
lambda x:`s(x)`+"/"+`s(x+1)`
</code>```

Body:
Python 2, <s>85</s> 81 bytes

x,s=input(),[1,1]
for i in range(x):s+=s[i]+s[i+1],s[i+1]
print`s[x-1]`+"/"+`s[x]`

This submission is 1-indexed.

Using a recursive function, 85 bytes:

s=lambda x:int(x<1)or x%2 and s(x/2)or s(-~x/2)+s(~-x/2)
lambda x:`s(x)`+"/"+`s(x+1)`

If an output like True/2 is acceptable, here's one at 81 bytes:

s=lambda x:x<1 or x%2 and s(x/2)or s(-~x/2)+s(~-x/2)
lambda x:`s(x)`+"/"+`s(x+1)`


答:
Perl, <s>61</s> 60 bytes

Includes +3 for -p0a

Give input square on STDIN, prints 0 for no symmetry, otherwise some positive number

```<code>./symmetry.pl
DBCA
BDCA
ACDB
ACBD
^D
</code>```

symmetry.pl:

```<code>#!/usr/bin/perl -p0a
s,.,chop$F[$i++/($j-4?1:4)%4],eg;$\+=$$_++;++$j<8&&redo}{
</code>```

Title: Is this square symmetrical?

Body:
Write a program or function that takes in a 4×4 text grid consisting of exactly 4 A's, 4 B's, 4 C's, and 4 D's, such as:

```<code>ACDC
BBCA
BADD
ABCD
</code>```

The ABCD's may be in any arrangement but there will always be 4 of each. You can assume the input is valid. If desired you can also assume it has a trailing newline and/or that it comes as one line in reading order, e.g. ACDCBBCABADDABCD. You may also replace the characters ABCD with 0123 or 1234 respectively, if desired (but that's all).

Output a truthy value if the text grid has any form of reflective or rotational symmetry. Specifically:

If there is a central horizontal line of symmetry. e.g.

```<code>BACD
BACD
BACD \___ bottom mirrors top
BACD /
</code>```

If there is a central vertical line of symmetry. e.g.

```<code>BCCB
DAAD
CAAC
BDDB
  \/___ right mirrors left
</code>```

If there is a diagonal line of symmetry (in either direction). e.g.

```<code>     ___ diagonally mirrored
    /
ABDC
BACD
DCAB
CDBA
    \___ diagonally mirrored
</code>```

If there is 90° rotational symmetry. e.g.

```<code>BDAB
ACCD    same if rotated 90 degrees (or 180 or 270)
DCCA
BADB
</code>```

If there is 180° rotational symmetry. e.g.

```<code>DBCA
BDCA    same if rotated 180 degrees
ACDB
ACBD
</code>```

(Note that translational symmetry doesn't come into play here.)

Output a falsy value if the grid doesn't have one of the symmetries mentioned above. e.g. the very first example grid.

The shortest code in bytes wins.

Body:
Perl, <s>61</s> 60 bytes

Includes +3 for -p0a

Give input square on STDIN, prints 0 for no symmetry, otherwise some positive number

./symmetry.pl
DBCA
BDCA
ACDB
ACBD
^D

symmetry.pl:

#!/usr/bin/perl -p0a
s,.,chop$F[$i++/($j-4?1:4)%4],eg;$\+=$$_++;++$j<8&&redo}{


答:
C, 311 bytes

char s[5];sprintf(s,"%d%d",a, b);int z=strlen(s);int i=0;while(i2){i=1;while(i1){printf("\n%c%*c",l,a-1,r);}else{printf("\n%c",l);}i++;}}printf("\n");if(b>1){i=0;while(i<a){printf("%c",s[(2*a+b-i-3)%z]);i++;}printf("\n");}
```

Uses automatically included libraries stdio.h and string.h.

Body:
Given two positive integers, 'a' and 'b', output an ascii-art "box" that is a characters wide and b characters tall. For example, with '4' and '6':

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

Simple right? Here's the twist: The border of the box must be the characters of "a" and "b" alternating. This starts at the top left corner, and continues in a clockwise spiral. For example, the previous example with 4 and 6 should be

```<code>4646
6  4
4  6
6  4
4  6
6464
</code>```

A and B may be two-digit numbers. For example, the inputs "10" and "3" should output this:

```<code>1031031031
1        0
3013013013
</code>```

In order to keep the output relatively small, you do not have to support three or more digit numbers. Also, since inputs are restricted to positive integers, '0' is an invalid input, which you do not have to handle.

Here are some more test cases:

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

353
5 5
3 3
5 5
353

Input: (1, 1)
Output:

1

Input: (4, 4)
Output:

4444
4  4
4  4
4444

Input: (27, 1)
Output:

271271271271271271271271271

Input: (1, 17)
Output:

1
1
7
1
1
7
1
1
7
1
1
7
1
1
7
1
1

Input: (12, 34):
Output:

123412341234
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
432143214321
</code>```

You may take input and output in any reasonable format, and standard loopholes are banned. Since this is code-golf, the shortest answer in bytes wins!

Body:
C, 311 bytes

char s[5];sprintf(s,"%d%d",a, b);int z=strlen(s);int i=0;while(i<a){printf("%c",s[i++%z]);}if(b>2){i=1;while(i<b-1){char r=s[(a+i-1)%z];char l=s[(2*a+2*b-i-4)%z];if(a>1){printf("\n%c%*c",l,a-1,r);}else{printf("\n%c",l);}i++;}}printf("\n");if(b>1){i=0;while(i<a){printf("%c",s[(2*a+b-i-3)%z]);i++;}printf("\n");}

Uses automatically included libraries stdio.h and string.h.


答:
05AB1E, <s>34</s> <s>33</s> <s>25</s> 23 bytes

```<code>XX‚¹GÂ2£DO¸s¦ìì¨}R2£'/ý
</code>```

Explanation

```<code>XX‚                        # push [1,1]
   ¹G           }          # input-1 times do
     Â                     # bifurcate
      2£                   # take first 2 elements of reversed list
        DO¸                # duplicate and sum 1st copy, s(n)+s(n+1)
           s¦              # cut away the first element of 2nd copy, s(n)
             ìì            # prepend both to list
               ¨           # remove last item in list
                 R2£       # reverse and take the first 2 elements
                    '/ý    # format output
                           # implicitly print
</code>```

Try it online

Saved 2 bytes thanks to Adnan.

Body:
05AB1E, <s>34</s> <s>33</s> <s>25</s> 23 bytes

XX‚¹GÂ2£DO¸s¦ìì¨}R2£'/ý

Explanation

XX‚                        # push [1,1]
   ¹G           }          # input-1 times do
     Â                     # bifurcate
      2£                   # take first 2 elements of reversed list
        DO¸                # duplicate and sum 1st copy, s(n)+s(n+1)
           s¦              # cut away the first element of 2nd copy, s(n)
             ìì            # prepend both to list
               ¨           # remove last item in list
                 R2£       # reverse and take the first 2 elements
                    '/ý    # format output
                           # implicitly print

Try it online

Saved 2 bytes thanks to Adnan.


答:
PHP 5.6, 66 bytes

function a($v,$a){echo str_repeat('*',max(0,min(10,1+$v/$a/70)));}
```

First we simplify the equation to v/a/70. From there we add 1 since PHP will use this number as an integer for the str_repeat, essentially doing abs($number+1). Then we use the hand-rolled clamp function of max($min_number, min($max_number, $the_number)) to keep it between 1 and 10.

The substr version is a few bytes shorter (due to not having to have to build in the clamp functionality), but this one was more fun to make.

Body:
Briefing

The difficulty of a Code Golf question can be calculated as such:

$$\text{clamp} \left( \left\lceil \left( \frac v a \div 700 \right) \times 10 \right\rceil, 0, 10 \right)$$

Where \$v\$ is the number of views a question has

and \$a\$ is the number of answers a question has

and \$⌈x⌉\$ is the ceiling operator.

Also:

$$\text{clamp}(x, min, max) = \begin{cases}
min & x < min \\
x   & min \le x \le max \\
max & max < x
\end{cases}$$

This question's current difficulty: ***

Task

Write a program that will take two integers (v and a) and output the difficulty in asterisks (*).

The input can be in the form of an array, a separated string or as separate function arguments

Test Data

```<code>Views   Answers Difficulty  Program Output
163     2       2           **
548     22      1           *
1452    24      1           *
1713    37      1           *
4162    32      2           **
3067    15      3           ***
22421   19      10          **********
</code>```

Example with pseudocode

```<code>v: 1713
a: 37
out = clamp(ceil(((v/a)/700)*10), 0, 10); // evaluates to 1
//program will output '*'
</code>```

The shortest code in bytes wins! Trailing/ leading spaces are allowed.

Body:
PHP 5.6, 66 bytes

function a($v,$a){echo str_repeat('*',max(0,min(10,1+$v/$a/70)));}

First we simplify the equation to v/a/70. From there we add 1 since PHP will use this number as an integer for the str_repeat, essentially doing abs($number+1). Then we use the hand-rolled clamp function of max($min_number, min($max_number, $the_number)) to keep it between 1 and 10.

The substr version is a few bytes shorter (due to not having to have to build in the clamp functionality), but this one was more fun to make.


问:
Golf me a card dealer
Frank has been working IT his whole life. Each day he responds to tickets, organizes equipment, and reports to his boss. One day, near the closing time on friday, Frank is doing his final inventory and sorting come cables in the supply closet. Suddenly, the door closes and locks from the outside! Such audacity! Frank shakes the door to try and let anyone know that he's stuck in the closet. Blast, nobody comes to his aid. With no cellphone, and no internet connection, Frank settles in with his laptop. After countless games of solitaire, frank decides to make his own card game....

Challenge:

In this case, you are frank (but not really). Your challenge is to create a dealer that can deal hands of cards, that could be dealt realistically. Your program needs to do 2 things: deal hands of cards according to an input, and take all the hands and reshuffle them. You must do this in the least ammount of bytes possible.

Rules:

Possible cards include all classic numbers and faces (a,2,3,4,5,6,7,8,9,10,j,q,k) and all suits (c,s,h,d), and two jokers (0j).

If a card is dealt, it cannot be dealt again until the program is given the reshuffle command, or it runs out of cards.

valid inputs are 'd' to deal a hand of 6 cards, and 'r' to reshuffle. NOTE that you can only deal out 9 hands before you run out of cards. Your program can either:

Automatically reshuffle,

Or give a 'X' to indicate that the dealer is out of cards.

your program needs to be able to take multiple commands over its running span.

All possible hands need to be able to be dealt in every order. Though, your program does NOT have to be random.

Examples:

We deal twice, the first hand yields the 2 of hearts, a 4 of spades, 9 of clubs, a joker, an ace of spades, and a 6 of diamonds. The second hand yields the 3 of hearts, the 10 of diamonds, the 10 of clubs, the king of clubs, the ace of diamonds, and the queen of spades. this is VALID because this is possible in real life.

d

  2h4s9c0jas6d

  d

  3h10d10ckcadqs

We deal twice, the first hand yields a mass of 5 cards (indicated by the dashes) and a 6 of hearts. The second hand deals another mass of 5 cards (again, the dashes) and another 6 of hearts. This is INVALID because it cannot happen in real life.

d

  -----6h

  d

  6h-----

we deal once, reset, and deal again. some of the cards from the first and the second deal match. this is VALID because cardstacks are renewed when shuffled.

d

  123456

  r

d

  456789

Scoring:

As with any golf, the lowest byte count wins! Good luck!

答:
PowerShell v2+, <s>174</s> 158 bytes

```<code>$a=(2..10+[char[]]'ajqk'|%{$i=$_;[char[]]'cshd'|%{"$i$_"}})+'0j'+'1j';$x=,0
for(){switch(read-host){'d'{$a|?{$_-notin$x}|Random -c 6|%{$x+=$_;$_}}'r'{$x=,0}}}
</code>```

Creates an array of the number and suit combinations, plus two jokers (note they're unique), stores that into $a. This forms our full deck. Sets array $x equal to [0]. This represents the cards that we've already dealt. Then enters an infinite for loop. Performs a read-host to get the d or r (other behavior is undefined).

For dealing, pipes $a a Where-Object to pull out the items that are -notin$x (i.e., the cards we haven't dealt yet). Those are piped to Get-Random with a -count of 6, which will randomly select 6 distinct elements. We store those newly-dealt cards into $x, and the card is placed $_ onto the pipeline, which will get flushed when the next read-host happens and output one-per-line thanks to the default behavior of Write-Output. If the user attempts to deal when $a = $x (i.e., all cards have been dealt), then the Get-Random will be selecting from nothing, and so nothing will be output.

For the reshuffling, we just set $x back to ,0 as the original array.

Note you'll need to ctrl-c or otherwise force quit the program.

Example execution

```<code>PS C:\Tools\Scripts\golfing> .\golf-card-dealer.ps1
d
8c
5h
as
ah
1j
ac
d
5d
2h
8s
6h
2c
qs
d
8h
6d
10c
10h
6s
4h
d
js
9h
4c
6c
qd
kd
d
3d
jc
8d
2s
3h
4d
d
kh
jd
3c
0j
jh
10d
d
9s
7s
ks
kc
qc
9d
d
5s
9c
7c
4s
10s
7d
d
7h
5c
3s
qh
2d
ad
d
d
d
r
d
3c
qs
2s
kd
2h
qc
d
ks
2d
5s
qd
kc
js

PS C:\Tools\Scripts\golfing>
</code>```

Title: Golf me a card dealer

Body:
PowerShell v2+, <s>174</s> 158 bytes

$a=(2..10+[char[]]'ajqk'|%{$i=$_;[char[]]'cshd'|%{"$i$_"}})+'0j'+'1j';$x=,0
for(){switch(read-host){'d'{$a|?{$_-notin$x}|Random -c 6|%{$x+=$_;$_}}'r'{$x=,0}}}

Creates an array of the number and suit combinations, plus two jokers (note they're unique), stores that into $a. This forms our full deck. Sets array $x equal to [0]. This represents the cards that we've already dealt. Then enters an infinite for loop. Performs a read-host to get the d or r (other behavior is undefined).

For dealing, pipes $a a Where-Object to pull out the items that are -notin$x (i.e., the cards we haven't dealt yet). Those are piped to Get-Random with a -count of 6, which will randomly select 6 distinct elements. We store those newly-dealt cards into $x, and the card is placed $_ onto the pipeline, which will get flushed when the next read-host happens and output one-per-line thanks to the default behavior of Write-Output. If the user attempts to deal when $a = $x (i.e., all cards have been dealt), then the Get-Random will be selecting from nothing, and so nothing will be output.

For the reshuffling, we just set $x back to ,0 as the original array.

Note you'll need to ctrl-c or otherwise force quit the program.

Example execution

PS C:\Tools\Scripts\golfing> .\golf-card-dealer.ps1
d
8c
5h
as
ah
1j
ac
d
5d
2h
8s
6h
2c
qs
d
8h
6d
10c
10h
6s
4h
d
js
9h
4c
6c
qd
kd
d
3d
jc
8d
2s
3h
4d
d
kh
jd
3c
0j
jh
10d
d
9s
7s
ks
kc
qc
9d
d
5s
9c
7c
4s
10s
7d
d
7h
5c
3s
qh
2d
ad
d
d
d
r
d
3c
qs
2s
kd
2h
qc
d
ks
2d
5s
qd
kc
js

PS C:\Tools\Scripts\golfing>


答:
MATL, 20 bytes

```<code>FT+"@:qtPXnosV47]xhh
</code>```

This uses the characterization in terms of binomial coefficients given in the OEIS page.

The algorithm works in theory for all numbers, but in practice it is limited by MATL's numerical precision, and so it doesn't work for large entries. The result is accurate for inputs up to 20 at least.

Try it online!

Explanation

```<code>FT+      % Implicitly take input n. Add [0 1] element-wise. Gives [n n+1]
"        % For each k in [n n+1]
  @:q    %   Push range [0 1 ... k-1]
  tP     %   Duplicate and flip: push [k-1 ... 1 0]
  Xn     %   Binomial coefficient, element-wise. Gives an array
  os     %   Number of odd entries in that array
  V      %   Convert from number to string
  47     %   Push 47, which is ASCII for '\'
]        % End for each
x        % Remove second 47
hh       % Concatenate horizontally twice. Automatically transforms 47 into '\'
         % Implicitly display
</code>```

Body:
MATL, 20 bytes

FT+"@:qtPXnosV47]xhh

This uses the characterization in terms of binomial coefficients given in the OEIS page.

The algorithm works in theory for all numbers, but in practice it is limited by MATL's numerical precision, and so it doesn't work for large entries. The result is accurate for inputs up to 20 at least.

Try it online!

Explanation

FT+      % Implicitly take input n. Add [0 1] element-wise. Gives [n n+1]
"        % For each k in [n n+1]
  @:q    %   Push range [0 1 ... k-1]
  tP     %   Duplicate and flip: push [k-1 ... 1 0]
  Xn     %   Binomial coefficient, element-wise. Gives an array
  os     %   Number of odd entries in that array
  V      %   Convert from number to string
  47     %   Push 47, which is ASCII for '\'
]        % End for each
x        % Remove second 47
hh       % Concatenate horizontally twice. Automatically transforms 47 into '\'
         % Implicitly display


答:
Pyth - <s>42</s> 41 bytes

Will need to restructure this.

```<code>VcQ\rj<c9.S++M*+md"jqka"}2T"cshd"m"0j"2lN
</code>```

Try it online here.

Stops giving cards after 9 deals.

Title: Golf me a card dealer

Body:
Frank has been working IT his whole life. Each day he responds to tickets, organizes equipment, and reports to his boss. One day, near the closing time on friday, Frank is doing his final inventory and sorting come cables in the supply closet. Suddenly, the door closes and locks from the outside! Such audacity! Frank shakes the door to try and let anyone know that he's stuck in the closet. Blast, nobody comes to his aid. With no cellphone, and no internet connection, Frank settles in with his laptop. After countless games of solitaire, frank decides to make his own card game....

Challenge:

In this case, you are frank (but not really). Your challenge is to create a dealer that can deal hands of cards, that could be dealt realistically. Your program needs to do 2 things: deal hands of cards according to an input, and take all the hands and reshuffle them. You must do this in the least ammount of bytes possible.

Rules:

Possible cards include all classic numbers and faces (a,2,3,4,5,6,7,8,9,10,j,q,k) and all suits (c,s,h,d), and two jokers (0j).

If a card is dealt, it cannot be dealt again until the program is given the reshuffle command, or it runs out of cards.

valid inputs are 'd' to deal a hand of 6 cards, and 'r' to reshuffle. NOTE that you can only deal out 9 hands before you run out of cards. Your program can either:

Automatically reshuffle,

Or give a 'X' to indicate that the dealer is out of cards.

your program needs to be able to take multiple commands over its running span.

All possible hands need to be able to be dealt in every order. Though, your program does NOT have to be random.

Examples:

We deal twice, the first hand yields the 2 of hearts, a 4 of spades, 9 of clubs, a joker, an ace of spades, and a 6 of diamonds. The second hand yields the 3 of hearts, the 10 of diamonds, the 10 of clubs, the king of clubs, the ace of diamonds, and the queen of spades. this is VALID because this is possible in real life.

d

  2h4s9c0jas6d

  d

  3h10d10ckcadqs

We deal twice, the first hand yields a mass of 5 cards (indicated by the dashes) and a 6 of hearts. The second hand deals another mass of 5 cards (again, the dashes) and another 6 of hearts. This is INVALID because it cannot happen in real life.

d

  -----6h

  d

  6h-----

we deal once, reset, and deal again. some of the cards from the first and the second deal match. this is VALID because cardstacks are renewed when shuffled.

d

  123456

  r

d

  456789

Scoring:

As with any golf, the lowest byte count wins! Good luck!

Body:
Pyth - <s>42</s> 41 bytes

Will need to restructure this.

VcQ\rj<c9.S++M*+md"jqka"}2T"cshd"m"0j"2lN

Try it online here.

Stops giving cards after 9 deals.