问:
Checkmate (aka the urinal problem)
My Precalc teacher has one of his favorite problems that he made up (or more likely <s>stole</s> inspired by xkcd) that involves a row of n urinals. "Checkmate" is a situation in which every urinal is already occupied OR has an occupied urinal next to them. For instance, if a person is an X, then

X-X--X

is considered checkmate. Note that a person cannot occupy a urinal next to an already occupied urinal.

Task

Your program will take a number through stdin, command line args, or a function argument. Your program will then print out or return the number of ways that checkmate can occur in with the inputted number of urinals.

Examples

0 -> 1 (the null case counts as checkmate)

1 -> 1 (X)

2 -> 2 (X- or -X)

3 -> 2 (X-X or -X-)

4 -> 3 (X-X-, -X-X, or X--X)

5 -> 4 (X-X-X, X--X-, -X-X-, or -X--X)

6 -> 5 (X-X-X-, X--X-X, X-X--X, -X--X- or -X-X-X)

7 -> 7 (X-X-X-X, X--X-X-, -X-X--X, -X--X-X, X-X--X-, X--X--X or -X-X-X-)

8 -> 9 (-X--X--X, -X--X-X-, -X-X--X-, -X-X-X-X, X--X--X-, X--X-X-X, X-X--X-X, X-X-X--X, X-X-X-X-)

...

Scoring

The smallest program in bytes wins.

答:
PHP, <s>105</s> <s>113</s> 93 bytes

+3 for n=1; +9 for $argv, -1-3 golfed

-20: noticed that I don´t have to the combinations, but only their count

```<code>for($i=1<<$n=$argv[1];$i--;)$r+=!preg_match("#11|(0|^)0[0,]#",sprintf("%0{$n}b,",$i));echo$r;
</code>```

run with -r

loop from 2**n-1 to 0:

check binary n-digit representation for 11, 000, 00 at the beginning or the end, or a single 0

if no match, increase result

print result

same size, slightly simpler regex

```<code>for($i=1<<$n=$argv[1];--$i;)$r+=!preg_match("#11|^00|00[,0]#",sprintf("%0{$n}b,",$i));echo$r;
</code>```

loop from 2**n-1 to 1 (instead of 0)

check binary representation for 11, 00 at the beginning or the end, or 000

prints nothing for n=0

PHP, 82 bytes

Arnauld´s answer ported and golfed:

```<code>for($i=$k=1<<$n=$argv[1];--$i;)$r+=!($i&$x=$i/2|$i*2)&&(($i|$x)&~$k)==$k-1;echo$r;
</code>```

prints nothing for n=0

Title: Checkmate (aka the urinal problem)

Body:
PHP, <s>105</s> <s>113</s> 93 bytes

+3 for n=1; +9 for $argv, -1-3 golfed

-20: noticed that I don´t have to the combinations, but only their count

for($i=1<<$n=$argv[1];$i--;)$r+=!preg_match("#11|(0|^)0[0,]#",sprintf("%0{$n}b,",$i));echo$r;

run with -r

loop from 2**n-1 to 0:

check binary n-digit representation for 11, 000, 00 at the beginning or the end, or a single 0

if no match, increase result

print result

same size, slightly simpler regex

for($i=1<<$n=$argv[1];--$i;)$r+=!preg_match("#11|^00|00[,0]#",sprintf("%0{$n}b,",$i));echo$r;

loop from 2**n-1 to 1 (instead of 0)

check binary representation for 11, 00 at the beginning or the end, or 000

prints nothing for n=0

PHP, 82 bytes

Arnauld´s answer ported and golfed:

for($i=$k=1<<$n=$argv[1];--$i;)$r+=!($i&$x=$i/2|$i*2)&&(($i|$x)&~$k)==$k-1;echo$r;

prints nothing for n=0


答:
Python 2, 42 40 39 35 bytes

```<code>f=lambda n:n>1and f(n-2)+f(n-3)or 1
</code>```

Generating the actual sets:

```<code>lambda n:["{:0{}b}".format(i,n).replace("0","-").replace("1","X")for i in range(2**n)if"11"not in"{:0{}b}".format(i*2,2+n).replace("000","11")]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Checkmate (aka the urinal problem)

Body:
My Precalc teacher has one of his favorite problems that he made up (or more likely <s>stole</s> inspired by xkcd) that involves a row of n urinals. "Checkmate" is a situation in which every urinal is already occupied OR has an occupied urinal next to them. For instance, if a person is an X, then

X-X--X

is considered checkmate. Note that a person cannot occupy a urinal next to an already occupied urinal.

Task

Your program will take a number through stdin, command line args, or a function argument. Your program will then print out or return the number of ways that checkmate can occur in with the inputted number of urinals.

Examples

0 -> 1 (the null case counts as checkmate)

1 -> 1 (X)

2 -> 2 (X- or -X)

3 -> 2 (X-X or -X-)

4 -> 3 (X-X-, -X-X, or X--X)

5 -> 4 (X-X-X, X--X-, -X-X-, or -X--X)

6 -> 5 (X-X-X-, X--X-X, X-X--X, -X--X- or -X-X-X)

7 -> 7 (X-X-X-X, X--X-X-, -X-X--X, -X--X-X, X-X--X-, X--X--X or -X-X-X-)

8 -> 9 (-X--X--X, -X--X-X-, -X-X--X-, -X-X-X-X, X--X--X-, X--X-X-X, X-X--X-X, X-X-X--X, X-X-X-X-)

...

Scoring

The smallest program in bytes wins.

Body:
Python 2, 42 40 39 35 bytes

f=lambda n:n>1and f(n-2)+f(n-3)or 1

Generating the actual sets:

lambda n:["{:0{}b}".format(i,n).replace("0","-").replace("1","X")for i in range(2**n)if"11"not in"{:0{}b}".format(i*2,2+n).replace("000","11")]


问:
Telegraphy Golf: Decode Baudot Code

Background

In 1870 Émile Baudot invented Baudot Code, a fixed-length character
encoding for telegraphy. He designed the code to be entered from a
manual keyboard with just five keys; two operated with the left hand and
three with the right:

The right index, middle and ring fingers operate the I, II, and
III keys, respectively, and the left index and middle fingers operate
IV and Ⅴ. (Henceforth I'll use the more familiar numerals 1–5.) Characters are entered as chords. To enter the letter
"C," for example, the operator presses the 1, 3, and 4 keys
simultaneously, whereupon a rotating brush arm reads each key in
sequence and transmits a current or, for keys not depressed, no current.
In modern terms, this is a 5-bit least-significant-bit-first
binary encoding, in which our example, "C," is encoded as 10110.

5 bits??

You might be thinking that 5 bits, which can express at most 32 unique
symbols, isn't enough for even all of the English letters and numerals,
to say nothing of punctuation. Baudot had a trick up his sleeve, though:
His character set is actually two distinct sets: Letters and
Figures, and he defined two special codes to switch between them.
Letter Shift (LS), which switches to Letters mode, is activated by pressing
the 5 key alone (00001), and Figure Shift (FS) is activated with the
4 key (00010).

Challenge

Your challenge is to write a program or function that decodes Baudot
Code transmissions.

A real transmission would begin with some initialization bits, plus a
start and stop bit before and after each character, but we're going to
skip those and only worry about the 5 unique bits for each character.
Input and output formats are discussed below.

Baudot's Code

There are two different versions of Baudot Code: Continental and U.K.
We're going use the U.K. version, which doesn't include characters
like "É" from Baudot's native French. We're also going to leave out all
of the symbols in the U.K. version that aren't among the printable ASCII
characters. You will only have to decode the characters in the table
below, all of which are printable ASCII characters except the final three control characters that are explained below the table.

The "Ltr" column shows the characters in Letter mode and "Fig" shows the
Figure mode characters:

        Encoding             Encoding
Ltr Fig  12345       Ltr Fig  12345
--- --- --------     --- --- --------
 A   1   10000        P   +   11111
 B   8   00110        Q   /   10111
 C   9   10110        R   -   00111
 D   0   11110        S       00101
 E   2   01000        T       10101
 F       01110        U   4   10100
 G   7   01010        V   '   11101
 H       11010        W   ?   01101
 I       01100        X       01001
 J   6   10010        Y   3   00100
 K   (   10011        Z   :   11001
 L   =   11011        -   .   10001
 M   )   01011        ER  ER  00011
 N       01111        FS  SP  00010
 O   5   11100        SP  LS  00001
 /       11000
```
<p>The last three rows in the right column are control characters:</p>
<ul>
<li><p><strong><code>ER</code></strong> is <em>Erasure</em>. Baudot's telegraphy machines would print an
asterisk-like symbol for this character to tell the reader that the
preceding character should be ignored, but we're going to be even
nicer to the reader and <em>actually omit (do not print) the preceding
character</em>. It acts the same in both Letter and Figure mode.</p>
</li>
<li><p><strong><code>FS</code></strong> is <em>Figure Shift</em>. This switches the character set from
Letters to Figures. If the decoder is <em>already</em> in Figure mode,
FS is treated as a <em>Space</em> (ergo <code>SP</code> in the "Ltr" column). When the decoder is in Figure mode it stays in Figure mode until an LS character is received.</p>
</li>
<li><p><strong><code>LS</code></strong> is <em>Letter Shift</em>. It switches the character set from
Figures to Letters. If the decoder is already in Letter mode, LS is treated as a <em>Space</em>. When in Letter mode the decoder stays in Letter mode until an FS character is received.</p>
</li>
</ul>
<p>The decoder always starts in Letter mode.</p>
<p>Here's an example with Figure Shift, Letter Shift, and Space:</p>
<pre class="lang-none prettyprint-override"><code>01011 10000 00100 00001 00010 10000 11100 00001 10101 11010
  M     A     Y   LS/SP FS/SP   1     5   LS/SP   T     H
</code>```

This yields the message MAY 15TH. As you can see, the first 00001 (Letter Shift/Space) character acts as a space, because the decoder is already in Letter mode. The next character, 00010 (Figure Shift/Space) switches the decoder to Figure mode to print 15. Then 00001 appears again, but this time it acts as Letter Shift to put the decoder back in Letter mode.

For your convenience, here are the characters in a format that's perhaps
easier to digest in an editor, sorted by code:

A,1,10000|E,2,01000|/,,11000|Y,3,00100|U,4,10100|I,,01100|O,5,11100|FS,SP,00010|J,6,10010|G,7,01010|H,,11010|B,8,00110|C,9,10110|F,,01110|D,0,11110|SP,LS,00001|-,.,10001|X,,01001|Z,:,11001|S,,00101|T,,10101|W,?,01101|V,',11101|ER,ER,00011|K,(,10011|M,),01011|L,=,11011|R,-,00111|Q,/,10111|N,,01111|P,+,11111
```
<h2>Input</h2>
<p>Input will be a string, array, or list of bits in
least-significant-bit-first order. Each character will be represented by a quintet of 5 bits. Bits may be in any reasonable format, e.g. a
binary string, an array of <code>0</code>s and <code>1</code>s, a string of <code>"0"</code> and <code>"1"</code>
characters, a single very large number, etc., as long as it maps
directly to the bits of the transmission.</p>
<p>Every transmission will have at least one printable quintet and at most
255 quintets (printable or otherwise), i.e. 5–1,275 bits inclusive.</p>
<p>The input can contain <em>only</em> the bits of the transmission, with two
allowed exceptions: Any number of leading or trailing <code>0</code> bits and/or,
for string input, a single trailing newline may be added to the
transmission. Leading or trailing bits or characters <em>cannot</em> be added
before or after each quintet, i.e. you cannot pad each quintet to 8 bits (or take each quintet as a single number in an array—unless your language has a 5-bit integer type)
or separate quintets with any additional bits, e.g. <code>"01111\n11100"</code>.</p>
<h3>Notes & edge cases</h3>
<ol>
<li><p>The transmission will contain only the characters in the "Ltr" and
"Fig" columns in the table above. You will never receive e.g.
<code>01110</code> in Figure mode, because it is absent from the "Fig" column.</p>
</li>
<li><p>It is assumed that the decoder will always be in Letter mode at the
beginning of a transmission. However, the first character <em>may</em> be an
FS character to switch to Figure mode immediately.</p>
</li>
<li><p>When the decoder is in Letter mode, it may receive an LS character, and when it is in Figure mode it may receive an FS character. In either event a Space character must be printed (see Output).</p>
</li>
<li><p>The ER character will never be the first character in a transmission, nor will it ever immediately follow an LS, FS, or another ER.</p>
</li>
<li><p>An FS character may immediately follow an LS character and vice versa.</p>
</li>
<li><p>Neither the LS nor FS character will be the last character in any transmission.</p>
</li>
<li><p>The <code>/</code> and <code>-</code> characters may be received in either Letter mode
(codes <code>11000</code> and <code>10001</code>, respectively) or Figure mode (<code>10111</code>
and <code>00111</code>).</p>
</li>
</ol>
<h2>Output</h2>
<p>Output may be in any reasonable format, the most reasonable being ASCII
(or UTF-8, for which all of the represented characters are the same as
ASCII). Please indicate in your answer if your output is in another
encoding or format.</p>
<h3>Notes</h3>
<ul>
<li>The space character (see 3. above) should be an ASCII space (0x20)
or your encoding's equivalent, i.e. what you get when you press the
space bar.</li>
</ul>
<h1>Winning</h1>
<p>This is code-golf. The shortest code in bytes wins.</p>
<h1>Restrictions</h1>
<ul>
<li><p>Standard loopholes are forbidden.</p>
</li>
<li><p>Trailing spaces and/or a single trailing newline are allowed. Leading spaces or other characters (that are not part of the transmission) are disallowed.</p>
</li>
<li><p>You may not use any built-in or library functions that decode Baudot Code (or any of its descendants, e.g. Murray Code, ITA-1, etc.).</p>
</li>
</ul>
<h1>Test Cases</h1>
<pre class="lang-none prettyprint-override"><code>Input: 001101000010100111101110010101
Output: BAUDOT
</code>```

Input: 11010010001001100011110111101111100
Output: HELLO
```

<pre class="lang-none prettyprint-override"><code>Input: 01011100000010000001000101000011100000011010111010
Output: MAY 15TH
</code>```

Input: 0001000100010000001000001011101110011100101010010110101010001111100101
Output: 32 FOOTSTEPS
```

<pre class="lang-none prettyprint-override"><code>Input: 10110000110101011100111100001111011010000001101110
Output: GOLF
</code>```

Input: 000100011000001111100000100010110111001100010110010000111111
Output: 8D =( :P
```

<pre class="lang-none prettyprint-override"><code>Input: 0000100001000010000100010001111011111011000011100010001
Output (4 leading spaces):     -/=/-
</code>```

答:
Batch, <s>306</s> 304 bytes

```<code>@echo off
set/pc=
set r=
set d=! !!YSBREXGMIWFNA-JKUTCQ/ZHLOVDP!! !3!8-2!7)!?!!1.6(4!9/!:!=5'0+
set s=2
:l
set/an=(s^&32)+0%c:~,2%%%6*8+0x%c:~2,3%%%14
set c=%c:~5%
if %n%==%s% set/as^^=35&goto l
call set r=%%r%%%%d:~%n%,1%%
if %r:~-1%==! set r=%r:~,-2%&goto l
if not "%c%"=="" goto l
echo %r%
</code>```

Takes input on STDIN. Since Batch has no binary conversion, I have to fake it using octal and hex conversion.

The first two digits are converted from octal (I can't use decimal because the first digit might be 0). Possible values are 00, 01, 10 and 11. The latter two have value 8 and 9 but I want 2 or 3 so I take the remainder modulo 6.

The last three digits are converted from hexadecimal. Digits are either 14 or 252 times their desired value, to I take the remainder modulo 14 (252=14*18).

c is the coded string

r is the result so far

d is the decoding array

s is the the index (taking the shift state into account) of the character that switches shift state

n is the binary decode plus bit 5 of s, which either equals the shift state, in which case the shift state is toggled, or indexes into the decoding array to find the next character (or ! to erase)

ContentLicense: CC BY-SA 4.0

Title: Telegraphy Golf: Decode Baudot Code

Body:
Batch, <s>306</s> 304 bytes

@echo off
set/pc=
set r=
set d=! !!YSBREXGMIWFNA-JKUTCQ/ZHLOVDP!! !3!8-2!7)!?!!1.6(4!9/!:!=5'0+
set s=2
:l
set/an=(s^&32)+0%c:~,2%%%6*8+0x%c:~2,3%%%14
set c=%c:~5%
if %n%==%s% set/as^^=35&goto l
call set r=%%r%%%%d:~%n%,1%%
if %r:~-1%==! set r=%r:~,-2%&goto l
if not "%c%"=="" goto l
echo %r%

Takes input on STDIN. Since Batch has no binary conversion, I have to fake it using octal and hex conversion.

The first two digits are converted from octal (I can't use decimal because the first digit might be 0). Possible values are 00, 01, 10 and 11. The latter two have value 8 and 9 but I want 2 or 3 so I take the remainder modulo 6.

The last three digits are converted from hexadecimal. Digits are either 14 or 252 times their desired value, to I take the remainder modulo 14 (252=14*18).

c is the coded string

r is the result so far

d is the decoding array

s is the the index (taking the shift state into account) of the character that switches shift state

n is the binary decode plus bit 5 of s, which either equals the shift state, in which case the shift state is toggled, or indexes into the decoding array to find the next character (or ! to erase)


Title: Telegraphy Golf: Decode Baudot Code

Body:
Background

In 1870 Émile Baudot invented Baudot Code, a fixed-length character
encoding for telegraphy. He designed the code to be entered from a
manual keyboard with just five keys; two operated with the left hand and
three with the right:

The right index, middle and ring fingers operate the I, II, and
III keys, respectively, and the left index and middle fingers operate
IV and Ⅴ. (Henceforth I'll use the more familiar numerals 1–5.) Characters are entered as chords. To enter the letter
"C," for example, the operator presses the 1, 3, and 4 keys
simultaneously, whereupon a rotating brush arm reads each key in
sequence and transmits a current or, for keys not depressed, no current.
In modern terms, this is a 5-bit least-significant-bit-first
binary encoding, in which our example, "C," is encoded as 10110.

5 bits??

You might be thinking that 5 bits, which can express at most 32 unique
symbols, isn't enough for even all of the English letters and numerals,
to say nothing of punctuation. Baudot had a trick up his sleeve, though:
His character set is actually two distinct sets: Letters and
Figures, and he defined two special codes to switch between them.
Letter Shift (LS), which switches to Letters mode, is activated by pressing
the 5 key alone (00001), and Figure Shift (FS) is activated with the
4 key (00010).

Challenge

Your challenge is to write a program or function that decodes Baudot
Code transmissions.

A real transmission would begin with some initialization bits, plus a
start and stop bit before and after each character, but we're going to
skip those and only worry about the 5 unique bits for each character.
Input and output formats are discussed below.

Baudot's Code

There are two different versions of Baudot Code: Continental and U.K.
We're going use the U.K. version, which doesn't include characters
like "É" from Baudot's native French. We're also going to leave out all
of the symbols in the U.K. version that aren't among the printable ASCII
characters. You will only have to decode the characters in the table
below, all of which are printable ASCII characters except the final three control characters that are explained below the table.

The "Ltr" column shows the characters in Letter mode and "Fig" shows the
Figure mode characters:

        Encoding             Encoding
Ltr Fig  12345       Ltr Fig  12345
--- --- --------     --- --- --------
 A   1   10000        P   +   11111
 B   8   00110        Q   /   10111
 C   9   10110        R   -   00111
 D   0   11110        S       00101
 E   2   01000        T       10101
 F       01110        U   4   10100
 G   7   01010        V   '   11101
 H       11010        W   ?   01101
 I       01100        X       01001
 J   6   10010        Y   3   00100
 K   (   10011        Z   :   11001
 L   =   11011        -   .   10001
 M   )   01011        ER  ER  00011
 N       01111        FS  SP  00010
 O   5   11100        SP  LS  00001
 /       11000
```
<p>The last three rows in the right column are control characters:</p>
<ul>
<li><p><strong><code>ER</code></strong> is <em>Erasure</em>. Baudot's telegraphy machines would print an
asterisk-like symbol for this character to tell the reader that the
preceding character should be ignored, but we're going to be even
nicer to the reader and <em>actually omit (do not print) the preceding
character</em>. It acts the same in both Letter and Figure mode.</p>
</li>
<li><p><strong><code>FS</code></strong> is <em>Figure Shift</em>. This switches the character set from
Letters to Figures. If the decoder is <em>already</em> in Figure mode,
FS is treated as a <em>Space</em> (ergo <code>SP</code> in the "Ltr" column). When the decoder is in Figure mode it stays in Figure mode until an LS character is received.</p>
</li>
<li><p><strong><code>LS</code></strong> is <em>Letter Shift</em>. It switches the character set from
Figures to Letters. If the decoder is already in Letter mode, LS is treated as a <em>Space</em>. When in Letter mode the decoder stays in Letter mode until an FS character is received.</p>
</li>
</ul>
<p>The decoder always starts in Letter mode.</p>
<p>Here's an example with Figure Shift, Letter Shift, and Space:</p>
<pre class="lang-none prettyprint-override"><code>01011 10000 00100 00001 00010 10000 11100 00001 10101 11010
  M     A     Y   LS/SP FS/SP   1     5   LS/SP   T     H
</code>```

This yields the message MAY 15TH. As you can see, the first 00001 (Letter Shift/Space) character acts as a space, because the decoder is already in Letter mode. The next character, 00010 (Figure Shift/Space) switches the decoder to Figure mode to print 15. Then 00001 appears again, but this time it acts as Letter Shift to put the decoder back in Letter mode.

For your convenience, here are the characters in a format that's perhaps
easier to digest in an editor, sorted by code:

A,1,10000|E,2,01000|/,,11000|Y,3,00100|U,4,10100|I,,01100|O,5,11100|FS,SP,00010|J,6,10010|G,7,01010|H,,11010|B,8,00110|C,9,10110|F,,01110|D,0,11110|SP,LS,00001|-,.,10001|X,,01001|Z,:,11001|S,,00101|T,,10101|W,?,01101|V,',11101|ER,ER,00011|K,(,10011|M,),01011|L,=,11011|R,-,00111|Q,/,10111|N,,01111|P,+,11111
```
<h2>Input</h2>
<p>Input will be a string, array, or list of bits in
least-significant-bit-first order. Each character will be represented by a quintet of 5 bits. Bits may be in any reasonable format, e.g. a
binary string, an array of <code>0</code>s and <code>1</code>s, a string of <code>"0"</code> and <code>"1"</code>
characters, a single very large number, etc., as long as it maps
directly to the bits of the transmission.</p>
<p>Every transmission will have at least one printable quintet and at most
255 quintets (printable or otherwise), i.e. 5–1,275 bits inclusive.</p>
<p>The input can contain <em>only</em> the bits of the transmission, with two
allowed exceptions: Any number of leading or trailing <code>0</code> bits and/or,
for string input, a single trailing newline may be added to the
transmission. Leading or trailing bits or characters <em>cannot</em> be added
before or after each quintet, i.e. you cannot pad each quintet to 8 bits (or take each quintet as a single number in an array—unless your language has a 5-bit integer type)
or separate quintets with any additional bits, e.g. <code>"01111\n11100"</code>.</p>
<h3>Notes & edge cases</h3>
<ol>
<li><p>The transmission will contain only the characters in the "Ltr" and
"Fig" columns in the table above. You will never receive e.g.
<code>01110</code> in Figure mode, because it is absent from the "Fig" column.</p>
</li>
<li><p>It is assumed that the decoder will always be in Letter mode at the
beginning of a transmission. However, the first character <em>may</em> be an
FS character to switch to Figure mode immediately.</p>
</li>
<li><p>When the decoder is in Letter mode, it may receive an LS character, and when it is in Figure mode it may receive an FS character. In either event a Space character must be printed (see Output).</p>
</li>
<li><p>The ER character will never be the first character in a transmission, nor will it ever immediately follow an LS, FS, or another ER.</p>
</li>
<li><p>An FS character may immediately follow an LS character and vice versa.</p>
</li>
<li><p>Neither the LS nor FS character will be the last character in any transmission.</p>
</li>
<li><p>The <code>/</code> and <code>-</code> characters may be received in either Letter mode
(codes <code>11000</code> and <code>10001</code>, respectively) or Figure mode (<code>10111</code>
and <code>00111</code>).</p>
</li>
</ol>
<h2>Output</h2>
<p>Output may be in any reasonable format, the most reasonable being ASCII
(or UTF-8, for which all of the represented characters are the same as
ASCII). Please indicate in your answer if your output is in another
encoding or format.</p>
<h3>Notes</h3>
<ul>
<li>The space character (see 3. above) should be an ASCII space (0x20)
or your encoding's equivalent, i.e. what you get when you press the
space bar.</li>
</ul>
<h1>Winning</h1>
<p>This is code-golf. The shortest code in bytes wins.</p>
<h1>Restrictions</h1>
<ul>
<li><p>Standard loopholes are forbidden.</p>
</li>
<li><p>Trailing spaces and/or a single trailing newline are allowed. Leading spaces or other characters (that are not part of the transmission) are disallowed.</p>
</li>
<li><p>You may not use any built-in or library functions that decode Baudot Code (or any of its descendants, e.g. Murray Code, ITA-1, etc.).</p>
</li>
</ul>
<h1>Test Cases</h1>
<pre class="lang-none prettyprint-override"><code>Input: 001101000010100111101110010101
Output: BAUDOT
</code>```

Input: 11010010001001100011110111101111100
Output: HELLO
```

<pre class="lang-none prettyprint-override"><code>Input: 01011100000010000001000101000011100000011010111010
Output: MAY 15TH
</code>```

Input: 0001000100010000001000001011101110011100101010010110101010001111100101
Output: 32 FOOTSTEPS
```

<pre class="lang-none prettyprint-override"><code>Input: 10110000110101011100111100001111011010000001101110
Output: GOLF
</code>```

Input: 000100011000001111100000100010110111001100010110010000111111
Output: 8D =( :P
```

<pre class="lang-none prettyprint-override"><code>Input: 0000100001000010000100010001111011111011000011100010001
Output (4 leading spaces):     -/=/-
</code>```

Body:
PHP, 206 Bytes

foreach(str_split($argv[1],5)as$s)($k="# f*YSBREXGMIWFNA-JKUTCQ/ZHLOVDP#l *3#8-2#7)#?##1.6(4#9/#:#=5'0+"[32*$f+bindec($s)])=="*"?array_pop($a):($k=="f"?$f=1:($k=="l"?$f=0:($k=="#"?:$a[]=$k)));echo join($a);


答:
JavaScript (ES6) / Recursive, <s>30</s> 27 bytes

Edit: saved 3 bytes thanks to Shaun H

let

f=n=>n<3?n||1:f(n-2)+f(n-3)

for(var n = 1; n < 16; n++) {
  console.log(n, f(n));
}```
</div>
</div>
</p>
<h1>JavaScript (ES6) / Non-recursive <s>90</s> 77 bytes</h1>
<p><em>Edit: saved 13 bytes thanks to Conor O'Brien and Titus</em></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let f =

n=>[...Array(k=1<<n)].map((_,i)=>r+=!(i&(x=i>>1|i+i))&&((i|x)&~k)==k-1,r=0)|r

for(var n = 1; n < 16; n++) {
  console.log(n, f(n));
}</code>```

Title: Checkmate (aka the urinal problem)

Body:
JavaScript (ES6) / Recursive, <s>30</s> 27 bytes

Edit: saved 3 bytes thanks to Shaun H

let

f=n=>n<3?n||1:f(n-2)+f(n-3)

for(var n = 1; n < 16; n++) {
  console.log(n, f(n));
}

JavaScript (ES6) / Non-recursive <s>90</s> 77 bytes

Edit: saved 13 bytes thanks to Conor O'Brien and Titus

let f =

n=>[...Array(k=1<<n)].map((_,i)=>r+=!(i&(x=i>>1|i+i))&&((i|x)&~k)==k-1,r=0)|r

for(var n = 1; n < 16; n++) {
  console.log(n, f(n));
}


答:
Ruby, <s>58</s> 34 bytes

Heavily inspired by Geobits' original Java answer.

```<code>f=->n{n<3?n:n<6?n-1:f[n-1]+f[n-5]}
</code>```

See it on repl.it: https://repl.it/Dedh/1

First attempt

```<code>->n{(1...2**n).count{|i|!("%0#{n}b"%i)[/11|^00|000|00$/]}}
</code>```

See it on repl.it: https://repl.it/Dedh

Title: Checkmate (aka the urinal problem)

Body:
Ruby, <s>58</s> 34 bytes

Heavily inspired by Geobits' original Java answer.

f=->n{n<3?n:n<6?n-1:f[n-1]+f[n-5]}

See it on repl.it: https://repl.it/Dedh/1

First attempt

->n{(1...2**n).count{|i|!("%0#{n}b"%i)[/11|^00|000|00$/]}}

See it on repl.it: https://repl.it/Dedh


答:
Java 7, <s>65</s> 42 bytes

```<code>int g(int u){return u>1?g(u-2)+g(u-3):1;}
</code>```

The sequence just adds previous elements to get new ones. Hat tip to orlp and Rod for this shorter method ;)

Old:

```<code>int f(int u){return u<6?new int[]{1,1,2,2,3,4}[u]:f(u-1)+f(u-5);}
</code>```

After the fifth element, the gap in the sequence rises by the element five previous.

Title: Checkmate (aka the urinal problem)

Body:
Java 7, <s>65</s> 42 bytes

int g(int u){return u>1?g(u-2)+g(u-3):1;}

The sequence just adds previous elements to get new ones. Hat tip to orlp and Rod for this shorter method ;)

Old:

int f(int u){return u<6?new int[]{1,1,2,2,3,4}[u]:f(u-1)+f(u-5);}

After the fifth element, the gap in the sequence rises by the element five previous.


答:
Oasis, 5 bytes

Code

```<code>cd+2V
</code>```

Extended version

```<code>cd+211
</code>```

Explanation

```<code>1 = a(0)
1 = a(1)
2 = a(2)

a(n) = cd+
       c      # Calculate a(n - 2)
        d     # Calculate a(n - 3)
         +    # Add them up
</code>```

Try it online!

Title: Checkmate (aka the urinal problem)

Body:
Oasis, 5 bytes

Code

cd+2V

Extended version

cd+211

Explanation

1 = a(0)
1 = a(1)
2 = a(2)

a(n) = cd+
       c      # Calculate a(n - 2)
        d     # Calculate a(n - 3)
         +    # Add them up

Try it online!


问:
10 PRINT CHR$(205.5+RND(1)); : GOTO 10 in PHP (or anything else, for that matter)
Just had a 'spirited' conversation with a co-worker about the succinctness of the following BASIC statement:

```<code>10 PRINT CHR$(205.5+RND(1)); : GOTO 10
</code>```

It's the title of this book, and will simply print a sequence of / and \ characters, alternating between the two randomly, resulting in a pattern similar to this:

(Image borrowed from http://www.flickr.com/photos/rndmcnlly/5058442151/sizes/o/in/photostream/)

Being of a PHP proclivity, we wondered what the most compact way of writing the same thing in PHP would be, and came up with this:

```<code>while(1) { echo chr(47 + 45 * rand(0,1)); }
</code>```

chr(47) is a / character, and chr(92) is a \. So the statement echo chr(47 + 45 * rand(0,1)); will randomly alternate between the two, ad nauseam.

In a language of your choosing, write the shortest program or function to output an infinite random sequence of \ and / characters, where each character has an equal probability of being chosen.

答:
Python, 68

In the "my language sucks at this" category, we've got Python!

```<code>import random,sys
while 1:sys.stdout.write(random.choice('/\\'))
</code>```

Thanks to Ivo for a few chars on imports and choice.

OwnerDisplayName: Judy

Body:
Python, 68

In the "my language sucks at this" category, we've got Python!

import random,sys
while 1:sys.stdout.write(random.choice('/\\'))

Thanks to Ivo for a few chars on imports and choice.


答:
MATL, <s>25</s> 23 bytes

```<code>W:qB7BZ+t!XAw3BZ+!3>a>s
</code>```

Try it online! Or check all test cases.

Explanation

Two convolutions! Yay!

This builds an array, say A, where each possible configuration is a row. 1 in this array represents an occupied position. For example, for input 4 the array A is

```<code>0 0 0 0
0 0 0 1
0 0 1 0
···
1 1 1 0
1 1 1 1
</code>```

The code then convolves array A with [1 1 1]. This gives an array B. Occupied positions and neighbours of occupied positions in A give a nonzero result in array B:

```<code>0 0 0 0
0 0 1 1
0 1 1 1
···
2 3 2 1
2 3 3 2
</code>```

So the first condition for a configuration to be a checkmate is that B contains no zeros in that row. This means that in that row of A there no empty positions, or there were some but were neighbours of occupied positions.

We need a second condition. For example, the last row fulfills the above condition, but is not part of the solution because the configuration was not valid to begin with. A valid configurations cannot have two neighbouring occupied positions, i.e cannot have two contiguous 1's in A. Equivalently, it cannot have two contiguous values in B exceeding 1. So we can detect this by convolving B with [1 1] and checking that in the resulting array, C,

```<code>0 0 0 0
0 1 2 1
1 2 2 1
···
5 5 3 1
5 6 5 2
</code>```

no value in that row exceeds 3. The final result is the number of configurations that fulfill the two conditions.

```<code>W:q    % Range [0 1 ... n-1], where n is implicit input
B      % Convert to binary. Each number produces a row. This is array A
7B     % Push array [1 1 1]
Z+     % 2D convolution, keeping size. Entries that are 1 or are horizontal
       % neighbours of 1 produce a positive value. This is array B
t!     % Duplicate and transpose (rows become columns)
XA     % True for columns that contain no zeros
w      % Swap. Brings array B to top
3B     % Push array [1 1]
Z+     % 2D convolution, keeping size. Two horizontally contiguous entries
       % that exceed 1 will give a result exeeding 3. This is array C
!      % Transpose
3>     % Detect entries that exceed 3
a      % True for columns that contain at least one value that exceeds 3
>      % Element-wise greater-than comparison (logical and of first
       % condition and negated second condition)
s      % Sum (number of true values)
</code>```

Title: Checkmate (aka the urinal problem)

Body:
MATL, <s>25</s> 23 bytes

W:qB7BZ+t!XAw3BZ+!3>a>s

Try it online! Or check all test cases.

Explanation

Two convolutions! Yay!

This builds an array, say A, where each possible configuration is a row. 1 in this array represents an occupied position. For example, for input 4 the array A is

0 0 0 0
0 0 0 1
0 0 1 0
···
1 1 1 0
1 1 1 1

The code then convolves array A with [1 1 1]. This gives an array B. Occupied positions and neighbours of occupied positions in A give a nonzero result in array B:

0 0 0 0
0 0 1 1
0 1 1 1
···
2 3 2 1
2 3 3 2

So the first condition for a configuration to be a checkmate is that B contains no zeros in that row. This means that in that row of A there no empty positions, or there were some but were neighbours of occupied positions.

We need a second condition. For example, the last row fulfills the above condition, but is not part of the solution because the configuration was not valid to begin with. A valid configurations cannot have two neighbouring occupied positions, i.e cannot have two contiguous 1's in A. Equivalently, it cannot have two contiguous values in B exceeding 1. So we can detect this by convolving B with [1 1] and checking that in the resulting array, C,

0 0 0 0
0 1 2 1
1 2 2 1
···
5 5 3 1
5 6 5 2

no value in that row exceeds 3. The final result is the number of configurations that fulfill the two conditions.

W:q    % Range [0 1 ... n-1], where n is implicit input
B      % Convert to binary. Each number produces a row. This is array A
7B     % Push array [1 1 1]
Z+     % 2D convolution, keeping size. Entries that are 1 or are horizontal
       % neighbours of 1 produce a positive value. This is array B
t!     % Duplicate and transpose (rows become columns)
XA     % True for columns that contain no zeros
w      % Swap. Brings array B to top
3B     % Push array [1 1]
Z+     % 2D convolution, keeping size. Two horizontally contiguous entries
       % that exceed 1 will give a result exeeding 3. This is array C
!      % Transpose
3>     % Detect entries that exceed 3
a      % True for columns that contain at least one value that exceeds 3
>      % Element-wise greater-than comparison (logical and of first
       % condition and negated second condition)
s      % Sum (number of true values)


答:
Jelly, 19 bytes

The recursive solution is <s>probably</s> shorter...

```<code>Ḥ⁹_c@⁸
+3µ:2R0;ç€µS
</code>```

See it at TryItOnline

Or see the series for n = [0, 99], also at TryItOnline

How?

Returns the n+3th Padovan's number by counting combinations

```<code>Ḥ⁹_c@⁸ - Link 1, binomial(k, n-2k): k, n
Ḥ      - double(2k)
 ⁹     - right argument (n)
  _    - subtract (n-2k)
     ⁸ - left argument (k)
   c@  - binomial with reversed operands (binomial(k, n-2k))

+3µ:2R0;ç€µS - Main link: n
  µ       µ  - monadic chain separation
+3           - add 3 (n+3)
   :2        - integer divide by 2 ((n+3)//2)
     R       - range ([1,2,...,(n+3)//2]
      0;     - 0 concatenated with ([0,1,2,...,(n+3)//2]) - our ks
        ç€   - call previous link as a dyad for each
           S - sum
</code>```

Title: Checkmate (aka the urinal problem)

Body:
Jelly, 19 bytes

The recursive solution is <s>probably</s> shorter...

Ḥ⁹_c@⁸
+3µ:2R0;ç€µS

See it at TryItOnline

Or see the series for n = [0, 99], also at TryItOnline

How?

Returns the n+3th Padovan's number by counting combinations

Ḥ⁹_c@⁸ - Link 1, binomial(k, n-2k): k, n
Ḥ      - double(2k)
 ⁹     - right argument (n)
  _    - subtract (n-2k)
     ⁸ - left argument (k)
   c@  - binomial with reversed operands (binomial(k, n-2k))

+3µ:2R0;ç€µS - Main link: n
  µ       µ  - monadic chain separation
+3           - add 3 (n+3)
   :2        - integer divide by 2 ((n+3)//2)
     R       - range ([1,2,...,(n+3)//2]
      0;     - 0 concatenated with ([0,1,2,...,(n+3)//2]) - our ks
        ç€   - call previous link as a dyad for each
           S - sum


问:
Let's make a map of dungeon
Long time ago, when I was spending more time playing RPG, one of the issues what some players had, was to track party movement and to draw proper map.
So I come with idea, to check how you guys come deal with this issue.

Task is to write a function, which takes as input parameter list of directions (passed as structure of your choice) ^v<>, display map of dungeon.
In example for input: >>>vvv<<<^^^ output will be:

```<code>+----+               +----+
|    |               |>>>v|
| ++ |               |^++v|
| ++ |  because      |^++v|
|    |               |^<<<|
+----+               +----+
</code>```

Testcases

```<code>>>>>>>vvvvv<<<<^^^>>v

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

^^^^^vvv<<<^^vv>>>>>>>>vv>><<^^^^v>>>>v^<^

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

As it is golf code challenge, shortest code wins.

Happy golfing.

EDIT
Sorry for late edit, I didn't have much time recently.

Map is generated based on movement.  It should contain only corridors which were visited during walk. Hence creating one big room won't be a valid answer.

There are three valid symbols in the map:

| vertical wall

| horizontal wall

+ intersection of vertical and horizontal wall.

Maximum length of the path is 255 character (but if you can, do not limit yourself).

More test cases:

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

 +--+
 |  |
 +--+

 >^<v

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

I hope now everything is clear.

答:
C, 246 bytes

n,y,*g,*p;main(c,v)char**v;{for(n=c*2+3,g=calloc(n*n,8),p=g+(n+1)*(c+1);c--;y=*v[c],p-=(y>70?n:1)*(y%5%4?-1:1))*p=1;for(y=n-1;--y;)for(c=n-1;c--;putchar(c?" |-++|-+"[*p?0:p[1]|p[-1]|(p[n]|p[-n])*2|(p[1+n]|p[1-n]|p[n-1]|p[-n-1])*4]:10))p=g+y*n+c;}
```

<p>Takes input as separate characters, for example:</p>

<pre class="lang-sh prettyprint-override"><code>./mapper '>' '>' '>' 'v' 'v' 'v' '<' '<' '<' '^' '^' '^'
</code>```

Or more conveniently, this (intentionally unquoted!) format:

./mapper $(echo '>>>vvv<<<^^^' | fold -w1)
```

<p>Or for (pretty inefficient) random input:</p>

<pre class="lang-sh prettyprint-override"><code>./mapper $(LC_CTYPE=C tr -dc '0-3' < /dev/urandom | tr '0123' '<>^v' | head -c 10 | fold -w1)
</code>```

And finally, using awk to crop the result means we can get much bigger:

./mapper $(LC_CTYPE=C tr -dc '0-3' < /dev/urandom | tr '0123' '<>^v' | head -c 500 | fold -w1) | awk '/[^ ]/{l=match($0,"\\+");if(l&&(l<L||!L))L=l;v[i++]=$0}END{for(;j<i;){l=v[j++];print substr(l,L,match(l," *$")-L)}}'
```

<hr>

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

<hr>

<p>Outputs to stdout. Uses the fact that padding is allowed around the map (produces a map which has edge length 2*n+1, putting the final position in the middle).</p>

<h3>Breakdown</h3>

<p>This works by looping over the arguments in reverse and moving in reverse. It actually uses the fact that arg 0 is the program name; it doesn't matter what the name is, but it allows us to visit both the initial and last cell (as well as all cells in-between) without needing special handling.</p>

<pre class="lang-c prettyprint-override"><code>n,                                  // Size of internal grid
y,                                  // Loop counter / current character
*g,                                 // Internal grid memory
*p;                                 // Current working pointer
main(c,v)char**v;{                  // K&R style function declaration
    for(                            // Step 1: identify visited cells
        n=c*2+3,                    //  Set output grid size
        g=calloc(n*n,8),            //  Allocate map storage space
        p=g+(n+1)*(c+1);            //  Start at centre
        c--;                        //  Loop over directions in reverse
        y=*v[c],                    //  Get current direction
        p-=(y>70?n:1)*(y%5%4?-1:1)  //  Move in reverse
    )*p=1;                          //  Mark cell visited
    for(y=n-1;--y;)                 // For each row (except edges)
        for(c=n-1;c--;              //   For each column (except edges, +1 for \n)
            putchar(c?" |-++|-+"[   //   Print wall using lookup table
                *p?0:p[1]|p[-1]|(p[n]|p[-n])*2|(p[1+n]|p[1-n]|p[n-1]|p[-n-1])*4
            ]:10)                   //   Or newline
        )p=g+y*n+c;                 //   Set current cell (happens first)
}
</code>```

Title: Let's make a map of dungeon

Body:
C, 246 bytes

n,y,*g,*p;main(c,v)char**v;{for(n=c*2+3,g=calloc(n*n,8),p=g+(n+1)*(c+1);c--;y=*v[c],p-=(y>70?n:1)*(y%5%4?-1:1))*p=1;for(y=n-1;--y;)for(c=n-1;c--;putchar(c?" |-++|-+"[*p?0:p[1]|p[-1]|(p[n]|p[-n])*2|(p[1+n]|p[1-n]|p[n-1]|p[-n-1])*4]:10))p=g+y*n+c;}

Takes input as separate characters, for example:

./mapper '>' '>' '>' 'v' 'v' 'v' '<' '<' '<' '^' '^' '^'

Or more conveniently, this (intentionally unquoted!) format:

./mapper $(echo '>>>vvv<<<^^^' | fold -w1)

Or for (pretty inefficient) random input:

./mapper $(LC_CTYPE=C tr -dc '0-3' < /dev/urandom | tr '0123' '<>^v' | head -c 10 | fold -w1)

And finally, using awk to crop the result means we can get much bigger:

./mapper $(LC_CTYPE=C tr -dc '0-3' < /dev/urandom | tr '0123' '<>^v' | head -c 500 | fold -w1) | awk '/[^ ]/{l=match($0,"\\+");if(l&&(l<L||!L))L=l;v[i++]=$0}END{for(;j<i;){l=v[j++];print substr(l,L,match(l," *$")-L)}}'

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

Outputs to stdout. Uses the fact that padding is allowed around the map (produces a map which has edge length 2*n+1, putting the final position in the middle).

Breakdown

This works by looping over the arguments in reverse and moving in reverse. It actually uses the fact that arg 0 is the program name; it doesn't matter what the name is, but it allows us to visit both the initial and last cell (as well as all cells in-between) without needing special handling.

n,                                  // Size of internal grid
y,                                  // Loop counter / current character
*g,                                 // Internal grid memory
*p;                                 // Current working pointer
main(c,v)char**v;{                  // K&R style function declaration
    for(                            // Step 1: identify visited cells
        n=c*2+3,                    //  Set output grid size
        g=calloc(n*n,8),            //  Allocate map storage space
        p=g+(n+1)*(c+1);            //  Start at centre
        c--;                        //  Loop over directions in reverse
        y=*v[c],                    //  Get current direction
        p-=(y>70?n:1)*(y%5%4?-1:1)  //  Move in reverse
    )*p=1;                          //  Mark cell visited
    for(y=n-1;--y;)                 // For each row (except edges)
        for(c=n-1;c--;              //   For each column (except edges, +1 for \n)
            putchar(c?" |-++|-+"[   //   Print wall using lookup table
                *p?0:p[1]|p[-1]|(p[n]|p[-n])*2|(p[1+n]|p[1-n]|p[n-1]|p[-n-1])*4
            ]:10)                   //   Or newline
        )p=g+y*n+c;                 //   Set current cell (happens first)
}


问:
Find the largest number n positions away from n
A sequel to this question.

Task

Given an array of positive integers, find the largest element k for which:

There exists some positive integer distance n, so that the element in the array located n places to the left or right from k equals n.

The array is guaranteed to contain at least one element satisfying this condition.

The shortest code (in bytes) wins. You may choose whichever I/O format you like.

Example

Given the input

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

The eligible values are:

The 4, as there is a 7 located 7 positions to its right

The first 6, as there is a 3 located 3 positions to its right

The 3, as there is a 4 located 4 positions to its left

The 5, as there is a 2 located 2 positions to its right

The second 7, as there is a 3 located 3 positions to its left.

Of these values, the largest is 7.

Test cases

```<code>[1, 13] → 13
[2, 9, 8, 3, 72, 2] → 8
[5, 28, 14, 5, 6, 3, 4, 7] → 14
[1, 3, 5, 15, 4, 1, 2, 6, 7, 7] → 7
[5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3] → 5
[5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5] → 10
</code>```

答:
05AB1E, 21 bytes

```<code>vyN+Ny-})¹gL<Ãv¹yè})Z
</code>```

Explanation

```<code>v      }               # for each num in input
 yN+                   # push index + num
    Ny-                # push index - num
        )              # wrap stack in a list
         ¹gL<Ã         # remove indices outside the range of input
              v¹yè})   # get list of elements in input at the remaining indices
                    Z  # get max
</code>```

Try it online!

Body:
05AB1E, 21 bytes

vyN+Ny-})¹gL<Ãv¹yè})Z

Explanation

v      }               # for each num in input
 yN+                   # push index + num
    Ny-                # push index - num
        )              # wrap stack in a list
         ¹gL<Ã         # remove indices outside the range of input
              v¹yè})   # get list of elements in input at the remaining indices
                    Z  # get max

Try it online!


答:
Haskell, <s>61</s> <s>57</s> 55 bytes

```<code>f x=maximum[a|(n,a)<-x,(i,b)<-x,b==abs(n-i)]
f.zip[0..]
</code>```

Usage example: (f.zip[0..]) [5,28,14,5,6,3,4,7] -> 14.

(More or less) a direct implementation of the definition: for each index n of the input list x keep a := x!!n if there's an index i where b := x!!i equals abs(n-i). Find the maximum.

Edit: @xnor saved two bytes. Thanks!

Title: Find the largest number n positions away from n

Body:
A sequel to this question.

Task

Given an array of positive integers, find the largest element k for which:

There exists some positive integer distance n, so that the element in the array located n places to the left or right from k equals n.

The array is guaranteed to contain at least one element satisfying this condition.

The shortest code (in bytes) wins. You may choose whichever I/O format you like.

Example

Given the input

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

The eligible values are:

The 4, as there is a 7 located 7 positions to its right

The first 6, as there is a 3 located 3 positions to its right

The 3, as there is a 4 located 4 positions to its left

The 5, as there is a 2 located 2 positions to its right

The second 7, as there is a 3 located 3 positions to its left.

Of these values, the largest is 7.

Test cases

```<code>[1, 13] → 13
[2, 9, 8, 3, 72, 2] → 8
[5, 28, 14, 5, 6, 3, 4, 7] → 14
[1, 3, 5, 15, 4, 1, 2, 6, 7, 7] → 7
[5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3] → 5
[5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5] → 10
</code>```

Body:
Haskell, <s>61</s> <s>57</s> 55 bytes

f x=maximum[a|(n,a)<-x,(i,b)<-x,b==abs(n-i)]
f.zip[0..]

Usage example: (f.zip[0..]) [5,28,14,5,6,3,4,7] -> 14.

(More or less) a direct implementation of the definition: for each index n of the input list x keep a := x!!n if there's an index i where b := x!!i equals abs(n-i). Find the maximum.

Edit: @xnor saved two bytes. Thanks!


答:
Python 3, 85 80 72 Bytes

```<code>lambda l,e=enumerate:max(i for p,i in e(l)for s,j in e(l)if j==abs(s-p))
</code>```

Edit: -8 Bytes thanks to @Dennis

Body:
Python 3, 85 80 72 Bytes

lambda l,e=enumerate:max(i for p,i in e(l)for s,j in e(l)if j==abs(s-p))

Edit: -8 Bytes thanks to @Dennis


答:
Jelly, 10 bytes

```<code>,N+JFfJị¹Ṁ
</code>```

Try it online! or verify all test cases.

How it works

```<code>,N+JFfJị¹Ṁ  Main link. Argument: A (array)

,N          Pair A with -A (element-wise negative).
   J        Yield the indices of A [1, ..., len(A)].
  +         Add the elements of A (and their negatives) with the corr. indices.
    F       Flatten the resulting 2D array.
     fJ     Filter indices; remove invalid indices (not in [1, ..., len(A)]) from
            the generated array. The result is the list of all indices of eligible
            elements of A.
       ị¹   Retrieve the corresponding elements of A.
         Ṁ  Take the maximum.
</code>```

Body:
Jelly, 10 bytes

,N+JFfJị¹Ṁ

Try it online! or verify all test cases.

How it works

,N+JFfJị¹Ṁ  Main link. Argument: A (array)

,N          Pair A with -A (element-wise negative).
   J        Yield the indices of A [1, ..., len(A)].
  +         Add the elements of A (and their negatives) with the corr. indices.
    F       Flatten the resulting 2D array.
     fJ     Filter indices; remove invalid indices (not in [1, ..., len(A)]) from
            the generated array. The result is the list of all indices of eligible
            elements of A.
       ị¹   Retrieve the corresponding elements of A.
         Ṁ  Take the maximum.


问:
Count even steps of 196 algorithm
In the 196-algorithm one starts from an integer and then adds its reverse to it until a palindrome is reached, like this:

```<code>start -> 5280
5280 + 0825 = 6105
6105 + 5016 = 11121
11121 + 12111 = 23232
-end-
</code>```

Write a function that counts how many even numbers are visited before the algorithm ends. Starting and ending numbers are also counted, so, in the example above, visited are consider the numbers: 5280, 6105, 11121, 23232 but not 825, 5016 and 12111.

Examples:

```<code>f(5280) = 2
f(56) = 1
f(59) = 1
f(89) = 13
</code>```

Extended code golf rules apply: shortest number of instructions and operations (like +,-,mod,print,while,if,...) wins.

答:
Windows PowerShell, 16 instructions

```<code>function f($n){
  @(                                   # 1
    $(                                 # 1
      $n % 2                           # 1
      #1     1   1     2    1
      for(;-join"$n"[99..0]-ne$n) {    # 5
        # 1   1   1     2
        $n+=-join"$n"[99..0]           # 5
        $n % 2                         # 1
      }                                #
    ) -eq 0).Count                     # 2
}
</code>```

Notes:

I counted the following items as one instruction: String expansion ("$n"), operators (-ne, %, !, -join, $(), @()), cmdlets (%), keywords (for).

I counted indexes as two instructions since it's the index [] plus the range operator ..

I didn't count the function header.

History:

2011-02-15 02:49 (18) First attempt.

2011-02-15 02:55 (16) Got rid of the pipeline.

Title: Count even steps of 196 algorithm

Body:
Windows PowerShell, 16 instructions

function f($n){
  @(                                   # 1
    $(                                 # 1
      $n % 2                           # 1
      #1     1   1     2    1
      for(;-join"$n"[99..0]-ne$n) {    # 5
        # 1   1   1     2
        $n+=-join"$n"[99..0]           # 5
        $n % 2                         # 1
      }                                #
    ) -eq 0).Count                     # 2
}

Notes:

I counted the following items as one instruction: String expansion ("$n"), operators (-ne, %, !, -join, $(), @()), cmdlets (%), keywords (for).

I counted indexes as two instructions since it's the index [] plus the range operator ..

I didn't count the function header.

History:

2011-02-15 02:49 (18) First attempt.

2011-02-15 02:55 (16) Got rid of the pipeline.

ContentLicense: CC BY-SA 2.5


Body:
Ruby, 66 bytes

->a{i=-1;a.map{|e|i+=1;[a[j=i+e]||0,a[0>(k=i-e)?j:k]||0].max}.max}


问:
English to Alien translator

Briefing

Aliens have settled on earth and strangely enough, their alphabet is the exact same as ours. Their language is also very similar to ours with some very distinct and easy to compute differences.

Challenge

Take a string and output the alien's language equivalent. The translation works as such:

Swap all the vowels in the word with the corresponding:

```<code>  Vowel |   With
--------+--------
   a    |   obo
   e    |   unu
   i    |   ini
   o    |   api
   u    |   iki
</code>```

You may also write another translator to translate Alien->English, this is optional however.

Examples

```<code>Input: Shaun
Output: Shoboikin

Input: Java
Output: Jobovobo

Input: Hello, World!
Output: Hunullapi, Wapirld!
</code>```

If the vowel is capitalized then you capitalize the first letter..

```<code>Input: Alan
Output: Obolobon

Input: Australia
Output: Oboikistroboliniobo
</code>```

Rules

Standard loopholes apply

Must work for text that contains new lines

You can either write a function, lambda, or full program

Capingrobotikilobotiniapins apin wrinitining thunu runuvunursunu trobonslobotapir!

答:
C - 192 bytes

(newlines added for clarity)

int c,j,b;main(){
char*f[]={"bo","nu","ni","pi","ki",""},
s[]={14,16,0,-14,-12};
while(c=getchar()){for(b=j=0;j<10;++j)
{if(c=="aeiouAEIOU"[j]){c+=s[j%=5];b=1;break;}}
printf("%c%s",c,f[b?j:5]);}}
```

Just lookup tables and a boolean switch.

Lookup each letter in table (string) of vowels; if found, then modify it according to the rule in table s. Print each character followed by a string: if a vowel was found, print the character modified by the value in s followed by the rest of the syllable stored in table f; if a vowel was not found, print the original character and an empty string.

Title: English to Alien translator

Body:
C - 192 bytes

(newlines added for clarity)

int c,j,b;main(){
char*f[]={"bo","nu","ni","pi","ki",""},
s[]={14,16,0,-14,-12};
while(c=getchar()){for(b=j=0;j<10;++j)
{if(c=="aeiouAEIOU"[j]){c+=s[j%=5];b=1;break;}}
printf("%c%s",c,f[b?j:5]);}}

Just lookup tables and a boolean switch.

Lookup each letter in table (string) of vowels; if found, then modify it according to the rule in table s. Print each character followed by a string: if a vowel was found, print the character modified by the value in s followed by the rest of the syllable stored in table f; if a vowel was not found, print the original character and an empty string.


问:
Is it an Odd Word?

Challenge

Given a single word as input, determine if the word is odd or even.

Odd and Even words

Assume the general rules:

```<code>odd + odd = even
even + odd = odd
odd + even = odd
even + even = even
</code>```

In the alphabet, the odd letters are:

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

And the even letters are:

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

The same applies to capital letters (AEIOU are odd and BCDFGHJKLMNPQRSTVWXYZ are even).

You then 'add' each of the letters in the word together. For example, the word cats is equivalent to:

```<code>even + odd + even + even
</code>```

Which simplifies to:

```<code>odd + even
</code>```

Which simplifies further to:

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

So the word cats is odd.

Examples

```<code>Input:  trees
Output: even
</code>```

```<code>Input:  brush
Output: odd
</code>```

```<code>Input:  CAts
Output: odd
</code>```

```<code>Input:  Savoie
Output: even
</code>```

```<code>Input:  rhythm
Output: even
</code>```

Rules

All input will be a single word which will only contain alphabetical characters.

If the word is odd, output a truthy value. If the word is even, output a falsey value.

Winning

The shortest code in bytes wins.

答:
Mathematica, 44 bytes

```<code>OddQ@StringCount[#,Characters@"aeiouAEIOU"]&
</code>```

Gives True for an odd string and False for an even one.

Title: Is it an Odd Word?

Body:
Mathematica, 44 bytes

OddQ@StringCount[#,Characters@"aeiouAEIOU"]&

Gives True for an odd string and False for an even one.


答:
Pyth, <s>19</s> 17 bytes

Thanks to @Pietu1998 for -2 bytes

```<code>eS@LQ@UQs.e,-kb+b
</code>```

A program that takes input of a list on STDIN and prints the result.

Try it online

How it works

```<code>eS@LQ@UQs.e,-kb+b  Program. Input: Q
         .e        Map over Q (implicit input fill) with elements as b and indices as k:
            -kb     k-b
               +b   k+b (Implicit fill with k)
           ,        2-element list of those (possible indices)
        s          Flatten that
      UQ           Yield [0, 1, 2, 3..., len(Q)-1]
     @             Filter the flattened list by presence in the above, removing invalid
                   indices
  @LQ              Index into Q at those indices
 S                 Sort that
e                  Yield the last element of that, giving the maximum
                   Implicitly print
</code>```

Body:
Pyth, <s>19</s> 17 bytes

Thanks to @Pietu1998 for -2 bytes

eS@LQ@UQs.e,-kb+b

A program that takes input of a list on STDIN and prints the result.

Try it online

How it works

eS@LQ@UQs.e,-kb+b  Program. Input: Q
         .e        Map over Q (implicit input fill) with elements as b and indices as k:
            -kb     k-b
               +b   k+b (Implicit fill with k)
           ,        2-element list of those (possible indices)
        s          Flatten that
      UQ           Yield [0, 1, 2, 3..., len(Q)-1]
     @             Filter the flattened list by presence in the above, removing invalid
                   indices
  @LQ              Index into Q at those indices
 S                 Sort that
e                  Yield the last element of that, giving the maximum
                   Implicitly print


答:
JavaScript (ES6), 61 bytes

```<code>a=>Math.max(...a.filter((_,i)=>a.some((e,j)=>e==i-j|e==j-i)))
</code>```

Body:
JavaScript (ES6), 61 bytes

a=>Math.max(...a.filter((_,i)=>a.some((e,j)=>e==i-j|e==j-i)))


答:
JavaScript (ES6), 62 bytes

```<code>n=>[1,...Array(n)].reduce(($,_,i,a)=>a[i]=i<3?i:a[i-3]+a[i-2])
</code>```

This is the first time that I've needed two dummy variable names. A recursive version would probably be shorter, but I really like reduce... Edit: Found a solution, also 62 bytes, which only has one dummy variable:

```<code>n=>[1,...Array(n)].reduce((p,_,i,a)=>a[i]=i<5?i+2>>1:a[i-5]+p)
</code>```

Title: Checkmate (aka the urinal problem)

Body:
My Precalc teacher has one of his favorite problems that he made up (or more likely <s>stole</s> inspired by xkcd) that involves a row of n urinals. "Checkmate" is a situation in which every urinal is already occupied OR has an occupied urinal next to them. For instance, if a person is an X, then

X-X--X

is considered checkmate. Note that a person cannot occupy a urinal next to an already occupied urinal.

Task

Your program will take a number through stdin, command line args, or a function argument. Your program will then print out or return the number of ways that checkmate can occur in with the inputted number of urinals.

Examples

0 -> 1 (the null case counts as checkmate)

1 -> 1 (X)

2 -> 2 (X- or -X)

3 -> 2 (X-X or -X-)

4 -> 3 (X-X-, -X-X, or X--X)

5 -> 4 (X-X-X, X--X-, -X-X-, or -X--X)

6 -> 5 (X-X-X-, X--X-X, X-X--X, -X--X- or -X-X-X)

7 -> 7 (X-X-X-X, X--X-X-, -X-X--X, -X--X-X, X-X--X-, X--X--X or -X-X-X-)

8 -> 9 (-X--X--X, -X--X-X-, -X-X--X-, -X-X-X-X, X--X--X-, X--X-X-X, X-X--X-X, X-X-X--X, X-X-X-X-)

...

Scoring

The smallest program in bytes wins.

Body:
JavaScript (ES6), 62 bytes

n=>[1,...Array(n)].reduce(($,_,i,a)=>a[i]=i<3?i:a[i-3]+a[i-2])

This is the first time that I've needed two dummy variable names. A recursive version would probably be shorter, but I really like reduce... Edit: Found a solution, also 62 bytes, which only has one dummy variable:

n=>[1,...Array(n)].reduce((p,_,i,a)=>a[i]=i<5?i+2>>1:a[i-5]+p)


问:
Substring Chainification

Introduction

For this example, let's take the string Hello, World! and the array [3, 2, 3]. To find the substring chain, we go through the following process:

The first number of the array is 3, so we get the substring [0 - 3], which is Hel. After that, we remove the first 3 characters from the initial string, which leaves us with lo, World!.

The second number of the array is 2, so we get the substring [0 - 2] from our new string, which gives us lo. The leftover string becomes , World!.

The last number is a 3, which gives us , W. The substring chain is all of the substrings combined, which gives us:

```<code>['Hel', 'lo', ', W']
</code>```

For a more visual example:

```<code>[3, 2, 3], 'Hello, World!'
3 -> Hel
2 ->    lo
3 ->      , W
</code>```

The task

Given a non-empty string and a non-empty array only consisting of positive integers (> 0), output the substring chain. You may assume that the sum of all integers in the array does not exceed the length of the string.

You can also assume that the strings will never contain any newlines.

Test cases

```<code>Input: abcdefghijk, [2, 1, 3]
Output: ['ab', 'c', 'def']

Input: Code Golf, [4, 1]
Output: ['Code', ' ']

Input: Ayyy, [3]
Output: ['Ayy']

Input: lexicographically, [2, 2, 2, 7, 4]
Output: ['le', 'xi', 'co', 'graphic', 'ally']
</code>```

This is code-golf, so the submission with the smallest number of bytes wins!

答:
Vimscript, <s>79</s> 78 bytes

not very pretty, I'm sure it can be improved...

Takes a vim buffer, then call echom string(A([2,3])) to see the output

```<code>fu A(l)
let r=[]
for i in a:l
exe "norm d".i."l"
let r+=[@"]
endfo
retu r
endf
</code>```

I actually thought of cheating and outputing the string ["abc", "def"]... But I resisted :P

Explanation: Delete (puts in default register) each array items amounts of characters and adds it to the array r...  A boring answer indeed.

Title: Substring Chainification

Body:
Vimscript, <s>79</s> 78 bytes

not very pretty, I'm sure it can be improved...

Takes a vim buffer, then call echom string(A([2,3])) to see the output

fu A(l)
let r=[]
for i in a:l
exe "norm d".i."l"
let r+=[@"]
endfo
retu r
endf

I actually thought of cheating and outputing the string ["abc", "def"]... But I resisted :P

Explanation: Delete (puts in default register) each array items amounts of characters and adds it to the array r...  A boring answer indeed.


答:
Groovy (39 Bytes)

```<code>{s->s.collect{/aeiou/=~it?1:0}.sum()%2}
</code>```

https://groovyconsole.appspot.com/script/5195711326978048

Title: Is it an Odd Word?

Body:
Challenge

Given a single word as input, determine if the word is odd or even.

Odd and Even words

Assume the general rules:

```<code>odd + odd = even
even + odd = odd
odd + even = odd
even + even = even
</code>```

In the alphabet, the odd letters are:

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

And the even letters are:

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

The same applies to capital letters (AEIOU are odd and BCDFGHJKLMNPQRSTVWXYZ are even).

You then 'add' each of the letters in the word together. For example, the word cats is equivalent to:

```<code>even + odd + even + even
</code>```

Which simplifies to:

```<code>odd + even
</code>```

Which simplifies further to:

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

So the word cats is odd.

Examples

```<code>Input:  trees
Output: even
</code>```

```<code>Input:  brush
Output: odd
</code>```

```<code>Input:  CAts
Output: odd
</code>```

```<code>Input:  Savoie
Output: even
</code>```

```<code>Input:  rhythm
Output: even
</code>```

Rules

All input will be a single word which will only contain alphabetical characters.

If the word is odd, output a truthy value. If the word is even, output a falsey value.

Winning

The shortest code in bytes wins.

Body:
Groovy (39 Bytes)

{s->s.collect{/aeiou/=~it?1:0}.sum()%2}

https://groovyconsole.appspot.com/script/5195711326978048


问:
Make An ASCII Poker Chip Stack Arrangement
Poker has etiquette in how you arrange your chips, often enforced in tournaments - your chips may not be "hidden" from your opponents by being behind others, mostly to not hide some large denomination chip(s).

The Challenge

We are going to be playing poker in ASCII, so we need to write a function or program that will draw our ASCII chip stack arrangement given its total value, n.

Input

- A positive integer, n (up to 2**32-1 should be handled)

Output

- An ASCII representation of the stack arrangement as defined below.

This may contain white-space to the right of each line such that no line is longer than one more character than the length used by printable characters in the longest (bottom) line;

This may contain a single trailing new line; and

The characters representing chips may be in lowercase if you prefer.

The stack arrangement will:

Contain the fewest chips possible, given the denominations (see below);

Will have equal valued chips in "stacks" (columns);

Be ordered such that the shorter stacks are to the right of taller stacks; and

Be ordered such that stacks with greater denomination chips will be to the right of equal sized stacks of lower denominations (representing that they are visible to our opponent(s) on the right)

The chips themselves are to be represented as individual characters identifying their colour:

```<code>    White : 1    = W
      Red : 5    = R
    Green : 25   = G
    Black : 100  = B
   Yellow : 500  = Y
     Pink : 1K   = P
   Orange : 5K   = O
     Cyan : 25K  = C
  Magenta : 100K = M
Aqua-blue : 500K = A
 Lavender : 1M   = L
   Indigo : 5M   = I
Turquoise : 25M  = T
   Violet : 100M = V
   Silver : 500M = S
</code>```

Example

For n = 276,352 the smallest number of chips would be:

```<code>2 * 100K + 3 * 25K + 1 * 1K + 3 * 100 + 2 * 25 + 2 * 1
    MM         CCC       P        BBB       GG       WW
</code>```

The single P must go on the far right,

then the three stacks of size 2 must go next,

- but the MM must go furthest to the right followed by the GG and then the WW since 100K > 25 > 1
then the two stacks of size 3 go on the left,

- but the CCC must go to the right of the BBB since 25K > 100

Now we must place these chips into actual stacks, to make our output:

```<code>BC
BCWGM
BCWGMP
</code>```

Test Cases

```<code>Input:
1

Output:
W

Input:
9378278

Output:
L
LWGPCM
LWGPCMB
LWGPCMBI

Input:
22222222

Output:
ROI
ROI
ROIWBPML
ROIWBPML

Input:
1342185143

Output:
WRCIV
WRCIVOLS
WRCIVOLSGBMT

Input:
2147483647

Output:
RMIS
RMISPC
RMISPCWL
RMISPCWLGBYOTV

Input:
4294967295

Output:
S
S
S
S
SRML
SRMLGOIT
SRMLGOITBPCV
SRMLGOITBPCVA
</code>```

This is code-golf, so shortest code in bytes wins. No loopholes, yada yada, you know the drill.

答:
Mathematica, 440 bytes

```<code>n=Input[]
c=Characters["SVTILAMCOPYBGRW"]
l=Reap[Do[n=n-#[[-i]]*Sow[Floor[n/#[[-i]]]]&@FoldList[Times,1,{5,5,4,5,2,5,5,4,5,2,5,5,4,5}],{i,1,15}]][[2,1]]
StringJoin@@((StringJoin[#,"\n"])&/@StringJoin/@Reverse/@((PadRight[#,Max[l],""]&/@Sort[Table[If[l[[n]]>0,Table[c[[n]],l[[n]]],Nothing],{n,1,15}],If[Length[#1]==Length[#2],Position[c,#1[[1]]][[1,1]]<Position[c,#2[[1]]][[1,1]],Length[#1]<Length[#2]]&])[[All,#]]&/@Range[Max[l]])//Reverse)
</code>```

The ASCI-representation and right order swallows most of the code.

*Only works with Version11 and higher (use of Nothing)*

Body:
Mathematica, 440 bytes

n=Input[]
c=Characters["SVTILAMCOPYBGRW"]
l=Reap[Do[n=n-#[[-i]]*Sow[Floor[n/#[[-i]]]]&@FoldList[Times,1,{5,5,4,5,2,5,5,4,5,2,5,5,4,5}],{i,1,15}]][[2,1]]
StringJoin@@((StringJoin[#,"\n"])&/@StringJoin/@Reverse/@((PadRight[#,Max[l],""]&/@Sort[Table[If[l[[n]]>0,Table[c[[n]],l[[n]]],Nothing],{n,1,15}],If[Length[#1]==Length[#2],Position[c,#1[[1]]][[1,1]]<Position[c,#2[[1]]][[1,1]],Length[#1]<Length[#2]]&])[[All,#]]&/@Range[Max[l]])//Reverse)

The ASCI-representation and right order swallows most of the code.

*Only works with Version11 and higher (use of Nothing)*


问:
Jimmy these arrays down
My coworker, Jimmy is kinda new to C/C++. He's also kind of a slow learner. Now, to be fair, his code always compiles, but he has some really sloppy habits. For example, everybody knows that you can define an array like this:

```<code>int spam[] = {4, 8, 15, 16, 23, 42};
</code>```

Everybody that is, except for Jimmy. He is convinced that the only way to make an array is like this:

```<code>int spam[6];
spam[0] = 4;
spam[1] = 8;
spam[2] = 15;
spam[3] = 16;
spam[4] = 23;
spam[5] = 42;
</code>```

I keep fixing this for him in code-review, but he won't learn. So I need you to write a tool that automagically does this for him when he commits¹.

The challenge

I want you to write either a full program or a function that takes in a multiline string as input, and outputs the more compact version of the C array. The input will always follow this format, whitespace included:

```<code>identifier_one identifier_two[some_length];
identifier_two[0] = some_number;
identifier_two[1] = some_number;
identifier_two[2] = some_number;
...
identifier_two[some_length - 1] = some_number;
</code>```

In short, the input will always be valid and well defined C. In more detail:

All of the identifiers will be made up of just letters and underscores. The length will always be at least one, and there will never be any missing or out of bounds indexes. You may also assume that the indexes are in order. For example:

```<code>foo bar[3];
bar[0] = 1
bar[2] = 9;
</code>```

<s></s>

```<code>foo bar[1];
bar[0] = 1;
bar[1] = 3;
</code>```

and

```<code>foo bar[3];
bar[2] = 9;
bar[0] = 1
bar[1] = 3
</code>```

are all invalid inputs, and may cause undefined behavior in your submission. You may also assume that all of the numbers will be valid decimal numbers, negative or positive. The input will not have extraneous spaces. The output should always follow this format, whitespace included:

```<code>identifier_one identifier_two[] = {n1, n2, n3, ...};
</code>```

Here is some sample data:

```<code>Input:
spam eggs[10];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
eggs[4] = 3;
eggs[5] = 7;
eggs[6] = 888;
eggs[7] = 555;
eggs[8] = 0;
eggs[9] = -2;

Output:
spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};

Input:
char ans[2];
ans[0] = 52;
ans[1] = 50;

Output:
char ans[] = {52, 50};

Input:
blah_blah quux[1];
quux[0] = 105;

Output:
blah_blah quux[] = {105};
</code>```

You may take your input and output in any reasonable format, such as STDIN/STDOUT, function arguments and return value, reading and writing files etc. Standard loopholes apply. The shortest answer in bytes wins!

¹This is passive-aggressive and a terrible idea. You did not get this idea from me.

答:
V, <s>25</s>, 24 bytes

```<code>3wC] = {òJd2f $s, òhC};
</code>```

Try it online!
This contains an unprintable <esc> character, so here is a hexdump:

```<code>0000000: 3377 435d 203d 207b 1bf2 4a64 3266 2024  3wC] = {..Jd2f $
0000010: 732c 20f2 6843 7d3b                      s, .hC};
</code>```

Explanation:

```<code>3w                              "Move forward 3 words
  C     <esc>                   "Delete everything until the end of the line, and enter this text:
   ] = {                        "'] = {'
             ò         ò        "Recursively:
              J                 "  Join these two lines (which enters a space)
               d                "  Delete everything until you
                2f              "  (f)ind the (2)nd space
                   $            "  Move to the end of this line
                    s           "  Delete a character, and enter:
                     ,          "  ', '
                                "
                        h       "Move one character to the left
                         C      "Delete everything until the end of the line, and enter this text:
                          };    "'};'
</code>```

Title: Jimmy these arrays down

Body:
V, <s>25</s>, 24 bytes

3wC] = {òJd2f $s, òhC};

Try it online!
This contains an unprintable <esc> character, so here is a hexdump:

0000000: 3377 435d 203d 207b 1bf2 4a64 3266 2024  3wC] = {..Jd2f $
0000010: 732c 20f2 6843 7d3b                      s, .hC};

Explanation:

3w                              "Move forward 3 words
  C     <esc>                   "Delete everything until the end of the line, and enter this text:
   ] = {                        "'] = {'
             ò         ò        "Recursively:
              J                 "  Join these two lines (which enters a space)
               d                "  Delete everything until you
                2f              "  (f)ind the (2)nd space
                   $            "  Move to the end of this line
                    s           "  Delete a character, and enter:
                     ,          "  ', '
                                "
                        h       "Move one character to the left
                         C      "Delete everything until the end of the line, and enter this text:
                          };    "'};'


问:
Find the largest number that's adjacent to a zero
Challenge:

Take a vector / list of integers as input, and output the largest number that's adjacent to a zero.

Specifications:

As always, optional input and output format

You may assume that there will be at least one zero, and at least one non-zero element.

Test cases:

```<code>1 4 3 6 0 3 7 0
7

9 4 9 0 9 0 9 15 -2
9

-4 -6 -2 0 -9
-2

-11 0 0 0 0 0 -12 10
0

0 20
20
</code>```

Good luck and happy golfing!

答:
Perl, 42 bytes

Includes +1 for -p

Give the numbers on line on STDIN

```<code>largest0.pl <<< "8 4 0 0 5 1 2 6 9 0 6"
</code>```

largest0.pl:

```<code>#!/usr/bin/perl -p
($_)=sort{$b-$a}/(?<=\b0 )\S+|\S+(?= 0)/g
</code>```

Body:
Perl, 42 bytes

Includes +1 for -p

Give the numbers on line on STDIN

largest0.pl <<< "8 4 0 0 5 1 2 6 9 0 6"

largest0.pl:

#!/usr/bin/perl -p
($_)=sort{$b-$a}/(?<=\b0 )\S+|\S+(?= 0)/g


Title: Make An ASCII Poker Chip Stack Arrangement

Body:
Poker has etiquette in how you arrange your chips, often enforced in tournaments - your chips may not be "hidden" from your opponents by being behind others, mostly to not hide some large denomination chip(s).

The Challenge

We are going to be playing poker in ASCII, so we need to write a function or program that will draw our ASCII chip stack arrangement given its total value, n.

Input

- A positive integer, n (up to 2**32-1 should be handled)

Output

- An ASCII representation of the stack arrangement as defined below.

This may contain white-space to the right of each line such that no line is longer than one more character than the length used by printable characters in the longest (bottom) line;

This may contain a single trailing new line; and

The characters representing chips may be in lowercase if you prefer.

The stack arrangement will:

Contain the fewest chips possible, given the denominations (see below);

Will have equal valued chips in "stacks" (columns);

Be ordered such that the shorter stacks are to the right of taller stacks; and

Be ordered such that stacks with greater denomination chips will be to the right of equal sized stacks of lower denominations (representing that they are visible to our opponent(s) on the right)

The chips themselves are to be represented as individual characters identifying their colour:

```<code>    White : 1    = W
      Red : 5    = R
    Green : 25   = G
    Black : 100  = B
   Yellow : 500  = Y
     Pink : 1K   = P
   Orange : 5K   = O
     Cyan : 25K  = C
  Magenta : 100K = M
Aqua-blue : 500K = A
 Lavender : 1M   = L
   Indigo : 5M   = I
Turquoise : 25M  = T
   Violet : 100M = V
   Silver : 500M = S
</code>```

Example

For n = 276,352 the smallest number of chips would be:

```<code>2 * 100K + 3 * 25K + 1 * 1K + 3 * 100 + 2 * 25 + 2 * 1
    MM         CCC       P        BBB       GG       WW
</code>```

The single P must go on the far right,

then the three stacks of size 2 must go next,

- but the MM must go furthest to the right followed by the GG and then the WW since 100K > 25 > 1
then the two stacks of size 3 go on the left,

- but the CCC must go to the right of the BBB since 25K > 100

Now we must place these chips into actual stacks, to make our output:

```<code>BC
BCWGM
BCWGMP
</code>```

Test Cases

```<code>Input:
1

Output:
W

Input:
9378278

Output:
L
LWGPCM
LWGPCMB
LWGPCMBI

Input:
22222222

Output:
ROI
ROI
ROIWBPML
ROIWBPML

Input:
1342185143

Output:
WRCIV
WRCIVOLS
WRCIVOLSGBMT

Input:
2147483647

Output:
RMIS
RMISPC
RMISPCWL
RMISPCWLGBYOTV

Input:
4294967295

Output:
S
S
S
S
SRML
SRMLGOIT
SRMLGOITBPCV
SRMLGOITBPCVA
</code>```

This is code-golf, so shortest code in bytes wins. No loopholes, yada yada, you know the drill.

Body:
Ruby, 181 177 bytes

->n{*a=5*10**8
14.times{|i|a<<a[-1]/[5,4,5,5,2][i%5]}
a=a.zip("SVTILAMCOPYBGRW".chars).map{|v,c|[-(n/v),v,c,n%=v]}.sort
l=-a[0][0]
(1..l).map{|i|a.map{|d|l-i<-d[0]?d[2]:""}*""}}

Tests on Ideone.


问:
Hate/love conundrum

Challenge description

In this challenge, we only consider love and hate as feelings. If we want to utter a feeling expression of order N, we alternate between these two (starting with hate):

```<code>order | expression

1       I hate it.
2       I hate that I love it.
3       I hate that I love that I hate it.
4       I hate that I love that I hate that I love it.
</code>```

The pattern follows for every positive integer N. Given N, output the correspoinding feeling expression of order N.

Notes

Full stop (.) at the end of the expression is mandatory,

Trailing and leading whitespaces (including newlines) are permitted,

Output for a non-positive or non-integer N is undefined,

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

答:
dc, 75 bytes

```<code>?[1-lbP[I lov]P]sa[e that ]sb[[e it.]Pq]sc[1-[I hat]Pd2%1=ad1>clbPlxx]dsxx
</code>```

We're really just printing one chunk of string at a time here, and not leaving any garbage on the stack. This is great, we don't need to waste any bytes dealing with a register for our counter.

```<code>?                              #Input, works as our decrement counter
[1-lbP[I lov]P]sa              #Macro 'a' decrements our counter, prints string 'b',
                               #then prints 'I lov'
[e that ]sb                    #String 'b'
[[e it.]Pq]sc                  #Macro 'c' prints the tail end of our message and quits
[1-                            #I'll unfold our main macro here; first step is to
                               #decrement our counter
   [I hat]P                    #We always start by hating 'it,' no conditional needed
           d2%1=a              #Check the oddness of our counter; execute 'a' if odd
                 d1>c          #Check our counter; If we're done, execute 'c'
                     lbPlxx]   #Otherwise, print 'b' again and start this macro ('x') over
dsxx                           #Stores the above macro as 'x' and runs it.
</code>```

Title: Hate/love conundrum

Body:
dc, 75 bytes

?[1-lbP[I lov]P]sa[e that ]sb[[e it.]Pq]sc[1-[I hat]Pd2%1=ad1>clbPlxx]dsxx

We're really just printing one chunk of string at a time here, and not leaving any garbage on the stack. This is great, we don't need to waste any bytes dealing with a register for our counter.

?                              #Input, works as our decrement counter
[1-lbP[I lov]P]sa              #Macro 'a' decrements our counter, prints string 'b',
                               #then prints 'I lov'
[e that ]sb                    #String 'b'
[[e it.]Pq]sc                  #Macro 'c' prints the tail end of our message and quits
[1-                            #I'll unfold our main macro here; first step is to
                               #decrement our counter
   [I hat]P                    #We always start by hating 'it,' no conditional needed
           d2%1=a              #Check the oddness of our counter; execute 'a' if odd
                 d1>c          #Check our counter; If we're done, execute 'c'
                     lbPlxx]   #Otherwise, print 'b' again and start this macro ('x') over
dsxx                           #Stores the above macro as 'x' and runs it.


答:
Mathematica, 69 bytes

```<code>Max@MapIndexed[{If[#2[[1]]>#,a[[#2-#]],{}],a[[#2+#]]~Check~{}}&,a=#]&
</code>```

Anonymous function. Takes a list of integers as input and returns an integer as output. Ignore any messages generated.

Body:
A sequel to this question.

Task

Given an array of positive integers, find the largest element k for which:

There exists some positive integer distance n, so that the element in the array located n places to the left or right from k equals n.

The array is guaranteed to contain at least one element satisfying this condition.

The shortest code (in bytes) wins. You may choose whichever I/O format you like.

Example

Given the input

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

The eligible values are:

The 4, as there is a 7 located 7 positions to its right

The first 6, as there is a 3 located 3 positions to its right

The 3, as there is a 4 located 4 positions to its left

The 5, as there is a 2 located 2 positions to its right

The second 7, as there is a 3 located 3 positions to its left.

Of these values, the largest is 7.

Test cases

```<code>[1, 13] → 13
[2, 9, 8, 3, 72, 2] → 8
[5, 28, 14, 5, 6, 3, 4, 7] → 14
[1, 3, 5, 15, 4, 1, 2, 6, 7, 7] → 7
[5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3] → 5
[5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5] → 10
</code>```

Body:
Mathematica, 69 bytes

Max@MapIndexed[{If[#2[[1]]>#,a[[#2-#]],{}],a[[#2+#]]~Check~{}}&,a=#]&

Anonymous function. Takes a list of integers as input and returns an integer as output. Ignore any messages generated.


答:
J, 18 bytes

```<code>[:>./2(0&e.\#+/\)]
</code>```

Explanation

```<code>[:>./2(0&e.\#+/\)]  Input: array A
                 ]  Identity. Get A
     2              The constant 2
      (         )   Operate on 2 (LHS) and A (RHS)
               \    Get each subarray of size 2 from A and
             +/       Reduce it using addition
           \        Get each subarray of size 2 from A and
       0&e.           Test if 0 is a member of it
            #       Filter for the sums where 0 is contained
[:>./               Reduce using max and return
</code>```

Title: Find the largest number that's adjacent to a zero

Body:
Challenge:

Take a vector / list of integers as input, and output the largest number that's adjacent to a zero.

Specifications:

As always, optional input and output format

You may assume that there will be at least one zero, and at least one non-zero element.

Test cases:

```<code>1 4 3 6 0 3 7 0
7

9 4 9 0 9 0 9 15 -2
9

-4 -6 -2 0 -9
-2

-11 0 0 0 0 0 -12 10
0

0 20
20
</code>```

Good luck and happy golfing!

Body:
J, 18 bytes

[:>./2(0&e.\#+/\)]

Explanation

[:>./2(0&e.\#+/\)]  Input: array A
                 ]  Identity. Get A
     2              The constant 2
      (         )   Operate on 2 (LHS) and A (RHS)
               \    Get each subarray of size 2 from A and
             +/       Reduce it using addition
           \        Get each subarray of size 2 from A and
       0&e.           Test if 0 is a member of it
            #       Filter for the sums where 0 is contained
[:>./               Reduce using max and return


答:
Python 112 111

Very straightforward to me, please suggest any improvement that comes to mind.

```<code>def f(l):
 a,*b=l.split('\n')
 return a[:a.index('[')]+'[] = {'+', '.join(r.split(' = ')[1][:-1]for r in b)+'};'

# TEST

lines = """spam eggs[10];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
eggs[4] = 3;
eggs[5] = 7;
eggs[6] = 888;
eggs[7] = 555;
eggs[8] = 0;
eggs[9] = -2;"""
print (f(lines))
assert f(lines) == 'spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};'
</code>```

Title: Jimmy these arrays down

Body:
My coworker, Jimmy is kinda new to C/C++. He's also kind of a slow learner. Now, to be fair, his code always compiles, but he has some really sloppy habits. For example, everybody knows that you can define an array like this:

```<code>int spam[] = {4, 8, 15, 16, 23, 42};
</code>```

Everybody that is, except for Jimmy. He is convinced that the only way to make an array is like this:

```<code>int spam[6];
spam[0] = 4;
spam[1] = 8;
spam[2] = 15;
spam[3] = 16;
spam[4] = 23;
spam[5] = 42;
</code>```

I keep fixing this for him in code-review, but he won't learn. So I need you to write a tool that automagically does this for him when he commits¹.

The challenge

I want you to write either a full program or a function that takes in a multiline string as input, and outputs the more compact version of the C array. The input will always follow this format, whitespace included:

```<code>identifier_one identifier_two[some_length];
identifier_two[0] = some_number;
identifier_two[1] = some_number;
identifier_two[2] = some_number;
...
identifier_two[some_length - 1] = some_number;
</code>```

In short, the input will always be valid and well defined C. In more detail:

All of the identifiers will be made up of just letters and underscores. The length will always be at least one, and there will never be any missing or out of bounds indexes. You may also assume that the indexes are in order. For example:

```<code>foo bar[3];
bar[0] = 1
bar[2] = 9;
</code>```

<s></s>

```<code>foo bar[1];
bar[0] = 1;
bar[1] = 3;
</code>```

and

```<code>foo bar[3];
bar[2] = 9;
bar[0] = 1
bar[1] = 3
</code>```

are all invalid inputs, and may cause undefined behavior in your submission. You may also assume that all of the numbers will be valid decimal numbers, negative or positive. The input will not have extraneous spaces. The output should always follow this format, whitespace included:

```<code>identifier_one identifier_two[] = {n1, n2, n3, ...};
</code>```

Here is some sample data:

```<code>Input:
spam eggs[10];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
eggs[4] = 3;
eggs[5] = 7;
eggs[6] = 888;
eggs[7] = 555;
eggs[8] = 0;
eggs[9] = -2;

Output:
spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};

Input:
char ans[2];
ans[0] = 52;
ans[1] = 50;

Output:
char ans[] = {52, 50};

Input:
blah_blah quux[1];
quux[0] = 105;

Output:
blah_blah quux[] = {105};
</code>```

You may take your input and output in any reasonable format, such as STDIN/STDOUT, function arguments and return value, reading and writing files etc. Standard loopholes apply. The shortest answer in bytes wins!

¹This is passive-aggressive and a terrible idea. You did not get this idea from me.

Body:
Python 112 111

Very straightforward to me, please suggest any improvement that comes to mind.

def f(l):
 a,*b=l.split('\n')
 return a[:a.index('[')]+'[] = {'+', '.join(r.split(' = ')[1][:-1]for r in b)+'};'

# TEST

lines = """spam eggs[10];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
eggs[4] = 3;
eggs[5] = 7;
eggs[6] = 888;
eggs[7] = 555;
eggs[8] = 0;
eggs[9] = -2;"""
print (f(lines))
assert f(lines) == 'spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};'


答:
Perl 6, 53 bytes

{max map ->$/ {$1 if !$0|!$2},(1,|@_,1).rotor(3=>-2)}
```

<h2>Expanded:</h2>

<pre class="lang-perl6 prettyprint-override"><code># bare block lambda with implicit signature of (*@_)
{
  max

    map

      -> $/ {           # pointy lambda with parameter ｢$/｣
                        # ( ｢$0｣ is the same as ｢$/[0]｣ )
        $1 if !$0 | !$2 # return the middle value if either of the others is false
      },

      ( 1, |@_, 1 )     # list of inputs, with added non-zero terminals
      .rotor( 3 => -2 ) # grab 3, back-up 2, repeat until less than 3 remain
}
</code>```

Body:
Perl 6, 53 bytes

{max map ->$/ {$1 if !$0|!$2},(1,|@_,1).rotor(3=>-2)}

Expanded:

# bare block lambda with implicit signature of (*@_)
{
  max

    map

      -> $/ {           # pointy lambda with parameter ｢$/｣
                        # ( ｢$0｣ is the same as ｢$/[0]｣ )
        $1 if !$0 | !$2 # return the middle value if either of the others is false
      },

      ( 1, |@_, 1 )     # list of inputs, with added non-zero terminals
      .rotor( 3 => -2 ) # grab 3, back-up 2, repeat until less than 3 remain
}


答:
JavaScript, 125 bytes

I know it's longer than others, but I really wanted to use eval. Just for fun.

```<code>f=function(s){m=/^(\w+ )(\w+).*?(;.*)/.exec(s)
eval("var "+m[2]+"=new Array()"+m[3]+'alert(m[1]+m[2]+"={"+eval(m[2])+"};")')}
</code>```

To run, paste the following into here:

```<code>s='int spam[6];\
spam[0] = 4;\
spam[1] = 8;\
spam[2] = 15;\
spam[3] = 16;\
spam[4] = 23;\
spam[5] = 42;'
f=function(s){m=/^(\w+ )(\w+).*?(;.*)/.exec(s)
eval("var "+m[2]+"=new Array()"+m[3]+'alert(m[1]+m[2]+"={"+eval(m[2])+"};")')}
f(s)
</code>```

Title: Jimmy these arrays down

Body:
JavaScript, 125 bytes

I know it's longer than others, but I really wanted to use eval. Just for fun.

f=function(s){m=/^(\w+ )(\w+).*?(;.*)/.exec(s)
eval("var "+m[2]+"=new Array()"+m[3]+'alert(m[1]+m[2]+"={"+eval(m[2])+"};")')}

To run, paste the following into here:

s='int spam[6];\
spam[0] = 4;\
spam[1] = 8;\
spam[2] = 15;\
spam[3] = 16;\
spam[4] = 23;\
spam[5] = 42;'
f=function(s){m=/^(\w+ )(\w+).*?(;.*)/.exec(s)
eval("var "+m[2]+"=new Array()"+m[3]+'alert(m[1]+m[2]+"={"+eval(m[2])+"};")')}
f(s)


问:
Crash your favorite compiler
Write a perfectly legal code in a decent language of your choice whose compiling will either crash the compiler or send it into an infinite loop (infinite compile time).

Restrictions:

Use a standard language that is used in real world.

Use a standard, well-developed compiler (no answers like "I wrote my C compiler that crashes on everything").

The code must be legal in the language (so most likely you'll have to exploit a compiler or a language bug).

Give your compiler version and options used so that others can replicate it.

Explain why the compiler crashed, if possible.

Have fun :)

答:
J

This segfaults the J interpreter (at least on Linux):

```<code>15!:1[3#2
</code>```

It tries to read from memory address 2. Interestingly, if you try it with 0 or 1, you get domain error.

Title: Crash your favorite compiler

Body:
J

This segfaults the J interpreter (at least on Linux):

15!:1[3#2

It tries to read from memory address 2. Interestingly, if you try it with 0 or 1, you get domain error.


答:
Mathematica, 35 bytes

```<code>a@0=a@1=1;a@2=2;a@b_:=a[b-2]+a[b-3]
</code>```

Defines a function a. Takes an integer as input and returns an integer as output. Simple recursive solution.

Title: Checkmate (aka the urinal problem)

Body:
My Precalc teacher has one of his favorite problems that he made up (or more likely <s>stole</s> inspired by xkcd) that involves a row of n urinals. "Checkmate" is a situation in which every urinal is already occupied OR has an occupied urinal next to them. For instance, if a person is an X, then

X-X--X

is considered checkmate. Note that a person cannot occupy a urinal next to an already occupied urinal.

Task

Your program will take a number through stdin, command line args, or a function argument. Your program will then print out or return the number of ways that checkmate can occur in with the inputted number of urinals.

Examples

0 -> 1 (the null case counts as checkmate)

1 -> 1 (X)

2 -> 2 (X- or -X)

3 -> 2 (X-X or -X-)

4 -> 3 (X-X-, -X-X, or X--X)

5 -> 4 (X-X-X, X--X-, -X-X-, or -X--X)

6 -> 5 (X-X-X-, X--X-X, X-X--X, -X--X- or -X-X-X)

7 -> 7 (X-X-X-X, X--X-X-, -X-X--X, -X--X-X, X-X--X-, X--X--X or -X-X-X-)

8 -> 9 (-X--X--X, -X--X-X-, -X-X--X-, -X-X-X-X, X--X--X-, X--X-X-X, X-X--X-X, X-X-X--X, X-X-X-X-)

...

Scoring

The smallest program in bytes wins.

Body:
Mathematica, 35 bytes

a@0=a@1=1;a@2=2;a@b_:=a[b-2]+a[b-3]

Defines a function a. Takes an integer as input and returns an integer as output. Simple recursive solution.


答:
Python, 33 bytes

f=lambda n:+(n<2)or f(n-2)+f(n-3)
```

Uses the shifted base cases f(-1) = f(0) = f(1) = 1. If True could be used for 1, we would not need 3 bytes for the +().

Title: Checkmate (aka the urinal problem)

Body:
Python, 33 bytes

f=lambda n:+(n<2)or f(n-2)+f(n-3)

Uses the shifted base cases f(-1) = f(0) = f(1) = 1. If True could be used for 1, we would not need 3 bytes for the +().


答:
///, <s>60</s> 57 bytes

```<code>/!/I hate //T/that //
/it.//00/!TI love T//Tit./it.//0/!/
</code>```

-3 bytes thanks to m-chrzan

Input in unary with trailing new line.

Try it online!

Title: Hate/love conundrum

Body:
Challenge description

In this challenge, we only consider love and hate as feelings. If we want to utter a feeling expression of order N, we alternate between these two (starting with hate):

```<code>order | expression

1       I hate it.
2       I hate that I love it.
3       I hate that I love that I hate it.
4       I hate that I love that I hate that I love it.
</code>```

The pattern follows for every positive integer N. Given N, output the correspoinding feeling expression of order N.

Notes

Full stop (.) at the end of the expression is mandatory,

Trailing and leading whitespaces (including newlines) are permitted,

Output for a non-positive or non-integer N is undefined,

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

Body:
///, <s>60</s> 57 bytes

/!/I hate //T/that //
/it.//00/!TI love T//Tit./it.//0/!/

-3 bytes thanks to m-chrzan

Input in unary with trailing new line.

Try it online!