问:
1P5: Nested boxes
This task is part of the First Periodic Premier Programming Puzzle Push.

You get a hierarchy of items in the following format:

```<code>2
Hat
1
Gloves
</code>```

which need to be put in boxes, like so:

```<code>.------------.
| Hat        |
| .--------. |
| | Gloves | |
| '--------' |
'------------'
</code>```

In the input format the numbers start a box with as many items as the number specifies. The first box has two items in it (the Hat and the box that contains the Gloves), the second one only contains a single item – the gloves.

As can be seen, boxes can live inside boxes, too. And they are always rounded ... sort of (pointy corners are a wound hazard and we wouldn't want that).

Below there are the nasty details for those that want to utilize every tiny bit of leeway the specification gives. Mind you, not reading the spec is no excuse for submitting wrong solutions. There is a test script and a few test cases at the very end.

Specification

Boxes are constructed from the following characters:

| (U+007C) is used to construct the vertical edges.

- (U+002D) is used to construct the horizontal edges.

' (U+0027) are the round lower corners.

. (U+002E) are the round upper corners.

A box therefore looks like this:

```<code>.--.
|  |
'--'
</code>```

Note that while Unicode also has round corners and proper box-drawing characters, this task is in ASCII only. As much as I love Unicode I realize that there are languages and environments out there that didn't quite arrive in the second to last decade.

Boxes can contain a sequence of items that are either text or other items. Individual items in a box are rendered from top to bottom. The sequence A, B, C thus renders as follows:

```<code>.---.
| A |
| B |
| C |
'---'
</code>```

This of course applies to nested boxes too, which are an item just like text. So the sequence A, B, Box(C, Box(D, E)), F would render as follows:

```<code>.-----------.
| A         |
| B         |
| .-------. |
| | C     | |
| | .---. | |
| | | D | | |
| | | E | | |
| | '---' | |
| '-------' |
| F         |
'-----------'
</code>```

Boxes adjust their size to the content and nested boxes always extend to the size of their parent. There is always a space before and after the content, so that neither text nor nested boxes are too close to the outer box' edge. In short, the following is wrong:

```<code>.---.
|Box|
'---'
</code>```

And the following is correct:

```<code>.-----.
| Box |
'-----'
</code>```

Looks much nicer, too :-)

Text items (see Input below) have to be reproduced exactly.

There is always a single top-level box (cf. XML). However, one box can contain several other boxes.

Input

Input is given on standard input; for easier testing likely redirected from a file.

The input is given line-wise, with each line representing either a text item to put in the current box or opening a new box.

Every line is terminated by a line break.

Text items are marked by a line that does not consist of a number (see below). Text uses alphabetic characters, the space and punctuation (.,-'"?!()). Text will not start or end with a space and it will always have at least one character.

A box starts with a single line with a number in it. The number tells the size of the box, i.e. the number of following items that are put into it:

```<code>2
A
B
</code>```

yields a box with two text items:

```<code>.---.
| A |
| B |
'---'
</code>```

A box will always contain at least one item.

The end of boxes is not explicitly marked with a line; instead boxes are implicitly closed after the specified number of items are put into them.

A box is always just a single item, regardless how many items are in it. E.g.

```<code>3
A
4
a
b
c
d
B
</code>```

will yield a box with three items, the second of which is another box with four items.

Nesting also does not affect the fact that a box is just a single item.

Limits

The maximum nesting level is five. I.e. there are at most five boxes inside of each other. This includes the outermost one.

There is a maximum of ten items per box.

Text items have a maximum length of 100 characters.

Output

Output is the rendered box including all containing and nested items according to the rules outlined above.

Output should be given on standard output and it has to match exactly. No leading or trailing whitespace is allowed.

Each line must be terminated with a line break, including the last.

Winning condition

Shortest code wins (i.e. gets the accepted answer).

Sample input 1

```<code>.------------.
| Hat        |
| .--------. |
| | Gloves | |
| '--------' |
'------------'
</code>```0

Sample output 1

```<code>.------------.
| Hat        |
| .--------. |
| | Gloves | |
| '--------' |
'------------'
</code>```1

Sample input 2

```<code>.------------.
| Hat        |
| .--------. |
| | Gloves | |
| '--------' |
'------------'
</code>```2

Sample output 2

```<code>.--------------------------.
| Extreme                  |
| nesting                  |
| .----------------------. |
| | of                   | |
| | boxes                | |
| | .------------------. | |
| | | might            | | |
| | | lead             | | |
| | | to               | | |
| | | .--------------. | | |
| | | | interesting  | | | |
| | | | .----------. | | | |
| | | | | visuals. | | | | |
| | | | '----------' | | | |
| | | '--------------' | | |
| | '------------------' | |
| '----------------------' |
| Indeed!                  |
'--------------------------'
</code>```

Sample input 3

```<code>1
1
1
1
1
Extreme nesting Part Two
</code>```

Sample output 3

```<code>.------------------------------------------.
| .--------------------------------------. |
| | .----------------------------------. | |
| | | .------------------------------. | | |
| | | | .--------------------------. | | | |
| | | | | Extreme nesting Part Two | | | | |
| | | | '--------------------------' | | | |
| | | '------------------------------' | | |
| | '----------------------------------' | |
| '--------------------------------------' |
'------------------------------------------'
</code>```

Sample input 4

```<code>3
Foo
2
Bar
Baz
2
Gak
1
Another foo?
</code>```

Sample output 4

```<code>.----------------------.
| Foo                  |
| .------------------. |
| | Bar              | |
| | Baz              | |
| '------------------' |
| .------------------. |
| | Gak              | |
| | .--------------. | |
| | | Another foo? | | |
| | '--------------' | |
| '------------------' |
'----------------------'
</code>```

Test Script

Since getting details right can be difficult at times we (Ventero and me) have prepared a test script you can run your solution with to check whether it's correct. It's available as both a PowerShell script and a bash script. Invocation is: <test-script> <program invocation>.

UPDATE: The test scripts have been updated; there were a number of test cases that did not honor the limits I defined. The PowerShell test script did not use case-sensitive comparison for checking the result. I hope everything is fine now. The number of test cases was reduced to 156, although the last one now is quite ... large.

UPDATE 2: I uploaded my test-case generator. Written in C#, targeting the .NET 2 runtime. It runs on Mono. It may help people to test their implementation. As a definitive worst-case given the limits in the task you can try:

```<code>nb.exe 1 10 10 5 100 100 | my invocation
</code>```

which will generate only boxes up to the innermost level and utilize both the maximum number of items per box and the maximum length of text items. I didn't include this test case into the test script, though, since it's quite large and the output even larger.

UPDATE 3: I updated the PowerShell test script which was prone to throw errors depending on how the line endings were in the script and what line endings the solution printed. Now it should be agnostic to both. Sorry again for the confusion.

答:
Pip, 89 bytes (non-competing)

(The language is newer than the challenge. Also, I couldn't quite outgolf APL.)

Code is 87 bytes, +2 for -rn flags.

```<code>(z:{I+YPOi{Y{Vz}M,ym:MX#*Y$ALyY'|.s._.sX++m-#_.'|MyY".."J'-X++mALyAL"''"J'-Xm}yALl}i:g)
</code>```

Try it online!

The function z processes the first item of the input list (g, copied into global variable i so as to be available inside function calls). If this is a number n, it calls itself recursively n times, pads the resulting list of lines to a full rectangle, wraps each line in "| " " |", and adds .---. and '---' lines before returning the new list. If it is a string, it simply converts it to a one-item list and returns it. The final result is printed newline-separated (-n flag). More detail available on request.

Title: 1P5: Nested boxes

Body:
Pip, 89 bytes (non-competing)

(The language is newer than the challenge. Also, I couldn't quite outgolf APL.)

Code is 87 bytes, +2 for -rn flags.

(z:{I+YPOi{Y{Vz}M,ym:MX#*Y$ALyY'|.s._.sX++m-#_.'|MyY".."J'-X++mALyAL"''"J'-Xm}yALl}i:g)

Try it online!

The function z processes the first item of the input list (g, copied into global variable i so as to be available inside function calls). If this is a number n, it calls itself recursively n times, pads the resulting list of lines to a full rectangle, wraps each line in "| " " |", and adds .---. and '---' lines before returning the new list. If it is a string, it simply converts it to a one-item list and returns it. The final result is printed newline-separated (-n flag). More detail available on request.


问:
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.

答:
Retina, <s>30</s> 28 bytes

Byte count assumes ISO 8859-1 encoding.

```<code>\d+];¶.+
] = {
;¶.+=
,
;
};
</code>```

Try it online!

Explanation

We'll use the following input as an example:

```<code>spam eggs[4];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
</code>```

Stage 1

```<code>\d+];¶.+
] = {
</code>```

Note that there's a trailing space on the first line.

We start by matching a number following by ]; and a linefeed, and then everything up to the last space on the next line. This match can only be found at the end of the first line (due to the ];). All of this is replaced with ] = {. That is, it transforms our example input to:

```<code>spam eggs[] = {0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
</code>```

Stage 2

```<code>;¶.+=
,
</code>```

Now we match everything from a ; up to the = on the next line and replace with a ,. This transforms the string to:

```<code>spam eggs[] = {0, 4, 8, -3;
</code>```

Stage 3

```<code>;
};
</code>```

All that's left is fixing the end and we do this by replacing the only remaining ; with };:

```<code>spam eggs[] = {0, 4, 8, -3};
</code>```

ContentLicense: CC BY-SA 3.0

Title: Jimmy these arrays down

Body:
Retina, <s>30</s> 28 bytes

Byte count assumes ISO 8859-1 encoding.

\d+];¶.+
] = {
;¶.+=
,
;
};

Try it online!

Explanation

We'll use the following input as an example:

spam eggs[4];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;

Stage 1

\d+];¶.+
] = {

Note that there's a trailing space on the first line.

We start by matching a number following by ]; and a linefeed, and then everything up to the last space on the next line. This match can only be found at the end of the first line (due to the ];). All of this is replaced with ] = {. That is, it transforms our example input to:

spam eggs[] = {0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;

Stage 2

;¶.+=
,

Now we match everything from a ; up to the = on the next line and replace with a ,. This transforms the string to:

spam eggs[] = {0, 4, 8, -3;

Stage 3

;
};

All that's left is fixing the end and we do this by replacing the only remaining ; with };:

spam eggs[] = {0, 4, 8, -3};


问:
Rand5() to Rand7()
You are provided with a function Rand5(). This function returns perfectly random (equal distribution) integers between 1 and 5.

Provide the function Rand7(), which uses Rand5() to produce perfectly random integers between 1 and 7.

答:
In Common Lisp 70 characters:

```<code>(defun rand7()(let((n(-(+(rand5)(* 5(rand5)))5)))(if(> n 7)(rand7)n)))
</code>```

The parenthesis take up more space than I would like.

ContentLicense: CC BY-SA 2.5

Title: Rand5() to Rand7()

Body:
In Common Lisp 70 characters:

(defun rand7()(let((n(-(+(rand5)(* 5(rand5)))5)))(if(> n 7)(rand7)n)))

The parenthesis take up more space than I would like.


问:
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.

答:
Scheme, 18 instructions

I take an instruction to be an opening paren.

```<code>(define (even-numbers-from-169-algo n)
    (+
        (if (odd? n) 0 1)
        (if (equal? n (num-reverse n))
            0
            (even-numbers-from-169-algo
                (+ n (num-reverse n))))))
(define (num-reverse n)
    (string->number (list->string (reverse (string->list (number->string n))))))
</code>```

Title: Count even steps of 196 algorithm

Body:
Scheme, 18 instructions

I take an instruction to be an opening paren.

(define (even-numbers-from-169-algo n)
    (+
        (if (odd? n) 0 1)
        (if (equal? n (num-reverse n))
            0
            (even-numbers-from-169-algo
                (+ n (num-reverse n))))))
(define (num-reverse n)
    (string->number (list->string (reverse (string->list (number->string n))))))


问:
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 :)

答:
This is easy in any dependently-typed language. Type-checking general dependent types is undecidable since it may require arbitrarily complex computations (Turing-complete). You can simply encode in a dependent type a too-large value. Then the type-checker will use all available memory and crash. For instance, in Coq, ReyCharles gives the example of Compute 70000., which causes the type-checker to construct a giant Peano numeral and crash.

In more common languages that support some sort of macro expansion or metaprogramming, you can do something similar. For example, you can use all available memory in C:

```<code>#include <stdio.h>
#define a printf("%s", "Hello, world!\n");
#define b a a a a a a a a a a a a a a a a
#define c b b b b b b b b b b b b b b b b
#define d c c c c c c c c c c c c c c c c
#define e d d d d d d d d d d d d d d d d
#define f e e e e e e e e e e e e e e e e
// ...
#define z y y y y y y y y y y y y y y y y
int main() { z }
</code>```

The D programming language allows compile-time function execution. This can be used to compute something at compile time that is too large to fit in memory. Something similar can be achieved using C++ template metaprogramming.

In XML (not a compiled programming language, but an XML processor is analogous to a compiler), expanding entities can make the processor run out of memory:

```<code><?xml version="1.0"?>
<!DOCTYPE lolz [
 <!ENTITY lol "lol">
 <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
 <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
 <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
...
]>
<lolz>&lol999;</lolz>
</code>```

This is called the billion laughs attack.

Title: Crash your favorite compiler

Body:
This is easy in any dependently-typed language. Type-checking general dependent types is undecidable since it may require arbitrarily complex computations (Turing-complete). You can simply encode in a dependent type a too-large value. Then the type-checker will use all available memory and crash. For instance, in Coq, ReyCharles gives the example of Compute 70000., which causes the type-checker to construct a giant Peano numeral and crash.

In more common languages that support some sort of macro expansion or metaprogramming, you can do something similar. For example, you can use all available memory in C:

#include <stdio.h>
#define a printf("%s", "Hello, world!\n");
#define b a a a a a a a a a a a a a a a a
#define c b b b b b b b b b b b b b b b b
#define d c c c c c c c c c c c c c c c c
#define e d d d d d d d d d d d d d d d d
#define f e e e e e e e e e e e e e e e e
// ...
#define z y y y y y y y y y y y y y y y y
int main() { z }

The D programming language allows compile-time function execution. This can be used to compute something at compile time that is too large to fit in memory. Something similar can be achieved using C++ template metaprogramming.

In XML (not a compiled programming language, but an XML processor is analogous to a compiler), expanding entities can make the processor run out of memory:

<?xml version="1.0"?>
<!DOCTYPE lolz [
 <!ENTITY lol "lol">
 <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
 <!ENTITY lol2 "&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;">
 <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
...
]>
<lolz>&lol999;</lolz>

This is called the billion laughs attack.


问:
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.

答:
C, 42 bytes

f(char*s){return*s&&2130466>>*s&1^f(s+1);}
```

<p>This works with GCC 4.x on a x86-64 CPU. Results may vary with different setups.</p>

<p>Test it on repl.it.</p>

<p>At the cost of 5 more bytes, undefined behavior can be avoided, so the code should work as long as <em>int</em>s are at least 32 bits wide.</p>

<pre class="lang-c prettyprint-override"><code>f(char*s){return*s&&2130466>>(*s&31)&1^f(s+1);}
</code>```

How it works

Modulo 32, the character codes of all odd letters are 1, 5, 9, 15, and 21. 2130466 is the 32-bit integer that has set bits at these positions and unset bits at all others.

When f is called on a string, it first checks if the first character of the string is a null byte (string terminator). If it is, *s yields 0 and f returns 0. Otherwise, *s yield the character code of a letter  and the right argument of the logical AND (&&) is executed.

For >>, GCC generates a shift instruction. On a x86-64 CPU, the corresponding instruction for a 32-bit integer ignores all but the lower 5 bits of the right argument, which avoids reducing *s modulo 32. The right shift and the following bitwise AND with 1 extracts the bit of 2130466 that corresponds to the letter, which will be 1 if and only if the letter is odd.

Afterwards, we increment the pointer s (effectively discarding the first letter), call f recursively on the beheaded string, and take the bitwise XOR of the result from above and the result of the recursive call.

Title: Is it an Odd Word?

Body:
C, 42 bytes

f(char*s){return*s&&2130466>>*s&1^f(s+1);}

This works with GCC 4.x on a x86-64 CPU. Results may vary with different setups.

Test it on repl.it.

At the cost of 5 more bytes, undefined behavior can be avoided, so the code should work as long as ints are at least 32 bits wide.

f(char*s){return*s&&2130466>>(*s&31)&1^f(s+1);}

How it works

Modulo 32, the character codes of all odd letters are 1, 5, 9, 15, and 21. 2130466 is the 32-bit integer that has set bits at these positions and unset bits at all others.

When f is called on a string, it first checks if the first character of the string is a null byte (string terminator). If it is, *s yields 0 and f returns 0. Otherwise, *s yield the character code of a letter  and the right argument of the logical AND (&&) is executed.

For >>, GCC generates a shift instruction. On a x86-64 CPU, the corresponding instruction for a 32-bit integer ignores all but the lower 5 bits of the right argument, which avoids reducing *s modulo 32. The right shift and the following bitwise AND with 1 extracts the bit of 2130466 that corresponds to the letter, which will be 1 if and only if the letter is odd.

Afterwards, we increment the pointer s (effectively discarding the first letter), call f recursively on the beheaded string, and take the bitwise XOR of the result from above and the result of the recursive call.


答:
Jelly, 33 bytes

```<code>ỴḊḲ€Ṫ€K⁾;,yṖ“{“};”j
ỴḢḟØDṖ,⁾ =,ÇK
</code>```

TryItOnline

How?

```<code>ỴḊḲ€Ṫ€K⁾;,yṖ“{“};”j - Link 1, parse and reform the values, same input as the Main link
Ỵ                   - split on line feeds
 Ḋ                  - dequeue (remove the first line)
  Ḳ€                - split each on spaces
    Ṫ€              - tail each (get the numbers with trailing ';')
      K             - join on spaces
       ⁾;,          - ";,"
          y         - map (replace ';' with ',')
           Ṗ        - pop (remove the last ',')
            “{“};”  - list of strings ["{","};"]
                  j - join (making "{" + "n0, n1, ,n2, ..." + "};")

ỴḢḟØDṖ,⁾ =,ÇK - Main link, takes one argument, the multiline string
Ỵ             - split on line feeds
 Ḣ            - head (just the first line)
   ØD         - digits yield "0123456789"
  ḟ           - filter out
     Ṗ        - pop (remove the trailing ';')
      ,   ,   - pair
       ⁾ =    - the string " ="
           Ç  - call the previous Link (1)
            K - join on spaces (add the space after the '=')
</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:
Jelly, 33 bytes

ỴḊḲ€Ṫ€K⁾;,yṖ“{“};”j
ỴḢḟØDṖ,⁾ =,ÇK

TryItOnline

How?

ỴḊḲ€Ṫ€K⁾;,yṖ“{“};”j - Link 1, parse and reform the values, same input as the Main link
Ỵ                   - split on line feeds
 Ḋ                  - dequeue (remove the first line)
  Ḳ€                - split each on spaces
    Ṫ€              - tail each (get the numbers with trailing ';')
      K             - join on spaces
       ⁾;,          - ";,"
          y         - map (replace ';' with ',')
           Ṗ        - pop (remove the last ',')
            “{“};”  - list of strings ["{","};"]
                  j - join (making "{" + "n0, n1, ,n2, ..." + "};")

ỴḢḟØDṖ,⁾ =,ÇK - Main link, takes one argument, the multiline string
Ỵ             - split on line feeds
 Ḣ            - head (just the first line)
   ØD         - digits yield "0123456789"
  ḟ           - filter out
     Ṗ        - pop (remove the trailing ';')
      ,   ,   - pair
       ⁾ =    - the string " ="
           Ç  - call the previous Link (1)
            K - join on spaces (add the space after the '=')


答:
Go, 93 bytes

```<code>func(s string)int{n:=0;for _,c:=range s{for _,d:=range"aeiouAEIOU"{if c==d{n++}}};return n%2}
</code>```

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:
Go, 93 bytes

func(s string)int{n:=0;for _,c:=range s{for _,d:=range"aeiouAEIOU"{if c==d{n++}}};return n%2}


问:
String Concatenation
The Challenge

Given two strings containing only lowercase letters and no spaces, the result should be the shorter string, followed by an underscore, followed by the longer string with the first instance of a character removed for each character it contains that is in the shorter string.

You can assume the strings will always be different lengths.

Test Cases:

```<code>sale
salinewater
Result: sale_inwater (only the first 'a' in salinewater is removed)

jostling
juggle
Result: juggle_ostin (juggle is the shorter string)

juggle
juggler
Result: juggle_r (a 'g' is removed for every 'g' in the shorter string)
</code>```

Rules

This is code-golf, so shortest answer in bytes wins!

答:
JavaScript (ES6), <s>78</s> <s>75</s> 69 Bytes

const
     g=(x,y)=>x[y.length]?g(y,x):[...x].map(c=>y=y.replace(c,''))&&x+'_'+y
;

console.log(g.toString().length + 2);   // 69
console.log(g('sale', 'salinewater'))   // sale_inwater
console.log(g('juggle', 'juggler'))     // juggle_r
console.log(g('jostling','juggle'))     // juggle_ostin```
</div>
</div>
</p>
<h3>Breakdown</h3>
```x[y.length]?g(y,x):        \\ Make sure that x is the shorter string
[...x]                     \\ Spread string in array of characters
.map(c=>y=y.replace(c,'')) \\ For each character remove its first occurence in y
&&x+'_'+y                  \\ Concat x and changed y
```

Title: String Concatenation

Body:
JavaScript (ES6), <s>78</s> <s>75</s> 69 Bytes

const
     g=(x,y)=>x[y.length]?g(y,x):[...x].map(c=>y=y.replace(c,''))&&x+'_'+y
;

console.log(g.toString().length + 2);   // 69
console.log(g('sale', 'salinewater'))   // sale_inwater
console.log(g('juggle', 'juggler'))     // juggle_r
console.log(g('jostling','juggle'))     // juggle_ostin

Breakdown

x[y.length]?g(y,x):        \\ Make sure that x is the shorter string
[...x]                     \\ Spread string in array of characters
.map(c=>y=y.replace(c,'')) \\ For each character remove its first occurence in y
&&x+'_'+y                  \\ Concat x and changed y


答:
Julia, <s>112</s> <s>108</s> 105 Bytes

```<code>f(s)=string(split(s,'[')[1],"[] = {",join([m[1] for m in [eachmatch(r"= *(-?\d+)",s)...]],", "),"};")
</code>```

Explanation

```<code>string(                                                         # build output string
split(s,'[')[1],                                                # get declaration (e.g. spam eggs)
"[] = {",                                                       # add [] = {
join(                                                           # collect numbers
    [m[1] for m in [eachmatch(r"= *(-?\d+)",s)...]],            # regex out (signed) numbers
    ", "),                                                      # and join comma separated
"};"                                                            # add };
)                                                               # close string(
</code>```

Saved bytes by replacing collect(eachmatch()) with [eachmatch()...] and with a shorter regex

Title: Jimmy these arrays down

Body:
Julia, <s>112</s> <s>108</s> 105 Bytes

f(s)=string(split(s,'[')[1],"[] = {",join([m[1] for m in [eachmatch(r"= *(-?\d+)",s)...]],", "),"};")

Explanation

string(                                                         # build output string
split(s,'[')[1],                                                # get declaration (e.g. spam eggs)
"[] = {",                                                       # add [] = {
join(                                                           # collect numbers
    [m[1] for m in [eachmatch(r"= *(-?\d+)",s)...]],            # regex out (signed) numbers
    ", "),                                                      # and join comma separated
"};"                                                            # add };
)                                                               # close string(

Saved bytes by replacing collect(eachmatch()) with [eachmatch()...] and with a shorter regex


答:
Pyth, 13 bytes

```<code>++hAlDQ\_.-HG
</code>```

Try it online.

Title: String Concatenation

Body:
The Challenge

Given two strings containing only lowercase letters and no spaces, the result should be the shorter string, followed by an underscore, followed by the longer string with the first instance of a character removed for each character it contains that is in the shorter string.

You can assume the strings will always be different lengths.

Test Cases:

```<code>sale
salinewater
Result: sale_inwater (only the first 'a' in salinewater is removed)

jostling
juggle
Result: juggle_ostin (juggle is the shorter string)

juggle
juggler
Result: juggle_r (a 'g' is removed for every 'g' in the shorter string)
</code>```

Rules

This is code-golf, so shortest answer in bytes wins!

Body:
Pyth, 13 bytes

++hAlDQ\_.-HG

Try it online.


问:
Is this number a prime?
Believe it or not, we do not yet have a code golf challenge for a simple primality test. While it may not be the most interesting challenge, particularly for "usual" languages, it can be nontrivial in many languages.

Rosetta code features lists by language of idiomatic approaches to primality testing, one using the Miller-Rabin test specifically and another using trial division. However, "most idiomatic" often does not coincide with "shortest." In an effort to make Programming Puzzles and Code Golf the go-to site for code golf, this challenge seeks to compile a catalog of the shortest approach in every language, similar to "Hello, World!" and Golf you a quine for great good!.

Furthermore, the capability of implementing a primality test is part of our definition of programming language, so this challenge will also serve as a directory of proven programming languages.

Task

Write a full program that, given a strictly positive integer n as input, determines whether n is prime and prints a truthy or falsy value accordingly.

For the purpose of this challenge, an integer is prime if it has exactly two strictly positive divisors. Note that this excludes 1, who is its only strictly positive divisor.

Your algorithm must be deterministic (i.e., produce the correct output with probability 1) and should, in theory, work for arbitrarily large integers. In practice, you may assume that the input can be stored in your data type, as long as the program works for integers from 1 to 255.

Input

If your language is able to read from STDIN, accept command-line arguments or any other alternative form of user input, you can read the integer as its decimal representation, unary representation (using a character of your choice), byte array (big or little endian) or single byte (if this is your languages largest data type).

If (and only if) your language is unable to accept any kind of user input, you may hardcode the input in your program.

In this case, the hardcoded integer must be easily exchangeable. In particular, it may appear only in a single place in the entire program.

For scoring purposes, submit the program that corresponds to the input 1.

Output

Output has to be written to STDOUT or closest alternative.

If possible, output should consist solely of a truthy or falsy value (or a string representation thereof), optionally followed by a single newline.

The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation.

Additional rules

This is not about finding the language with the shortest approach for prime testing, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted.

Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

The language Piet, for example, will be scored in codels, which is the natural choice for this language.

Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program performs a primality test, then congrats for paving the way for a very boring answer.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

Built-in functions for testing primality are allowed. This challenge is meant to catalog the shortest possible solution in each language, so if it's shorter to use a built-in in your language, go for it.

Unless they have been overruled earlier, all standard code-golf rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalog as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Logicode, <s>601</s> <s>511</s> 467 bytes

```<code>circ o(n)->cond n<->0+n/o(n>)
circ p(n)->[
cond n->var c=~((~(o(n)))>)/var c=0
cond (~n)<->var d=p(c)+0/var d=c+1
d
]
circ q(n)->[
cond n->var e=~((~(o(n)))>)/var e=0
cond (~n)<->var f=e+0/var f=q(e)+1
f
]
circ r(a,b)->cond *a&*b->r(q(a),q(b))/a
circ s(a,b)->!(*(r(b,a)))
circ t(a,b)->cond b->t(q(a),q(b))/a
circ u(a,b)->cond s(a,b)->u(t(a,b),b)/!(*a)
circ v(a)->[
var j=p(j)
cond s(a,j)->[
var k=k+u(a,j)
var l=v(a)
]/[
var k=k
]
*((~k)>)
]
var j=1
var k
out v(binp)
</code>```

Oh my, that is a lot of code.

Here's a rundown of what each circuit does:

o is a trimmer, and it strips the extra 0's at the start (this is used for p and q.

p is a successor, and q is a decrement.

r is a preliminary bit to s (lessthan).

s is the lessthan (which uses the remainder checker).

t is a subtractor, which calculates a - b for any two positive integers a and b (in binary).

u is a mod checker, which returns 1 if a%b is not 0, and 0 if it is 0.

v is the actual prime checker, which returns 1 if the number is not prime, and 0 if the number is.

The j and k at the bottom are the divisor (b in the mod checker) and the un-bool'd output respectively.

The final line is the "input" bit, which asks for user input in binary (any other character that is not 0 or 1 in the input will be ignored), and returns 1 if the result is not prime, and 0 if the result is.

Edit 1: Saved a whopping 90 bytes (implemented circ/cond one-liners).

Edit 2: Saved another 44 bytes (implemented boolean operator, multi-line conds, and null variables).

Title: Is this number a prime?

Body:
Logicode, <s>601</s> <s>511</s> 467 bytes

circ o(n)->cond n<->0+n/o(n>)
circ p(n)->[
cond n->var c=~((~(o(n)))>)/var c=0
cond (~n)<->var d=p(c)+0/var d=c+1
d
]
circ q(n)->[
cond n->var e=~((~(o(n)))>)/var e=0
cond (~n)<->var f=e+0/var f=q(e)+1
f
]
circ r(a,b)->cond *a&*b->r(q(a),q(b))/a
circ s(a,b)->!(*(r(b,a)))
circ t(a,b)->cond b->t(q(a),q(b))/a
circ u(a,b)->cond s(a,b)->u(t(a,b),b)/!(*a)
circ v(a)->[
var j=p(j)
cond s(a,j)->[
var k=k+u(a,j)
var l=v(a)
]/[
var k=k
]
*((~k)>)
]
var j=1
var k
out v(binp)

Oh my, that is a lot of code.

Here's a rundown of what each circuit does:

o is a trimmer, and it strips the extra 0's at the start (this is used for p and q.

p is a successor, and q is a decrement.

r is a preliminary bit to s (lessthan).

s is the lessthan (which uses the remainder checker).

t is a subtractor, which calculates a - b for any two positive integers a and b (in binary).

u is a mod checker, which returns 1 if a%b is not 0, and 0 if it is 0.

v is the actual prime checker, which returns 1 if the number is not prime, and 0 if the number is.

The j and k at the bottom are the divisor (b in the mod checker) and the un-bool'd output respectively.

The final line is the "input" bit, which asks for user input in binary (any other character that is not 0 or 1 in the input will be ignored), and returns 1 if the result is not prime, and 0 if the result is.

Edit 1: Saved a whopping 90 bytes (implemented circ/cond one-liners).

Edit 2: Saved another 44 bytes (implemented boolean operator, multi-line conds, and null variables).


答:
Common Lisp

Macros make it easy:

```<code>(defmacro loop-forever ()
  (loop for x from 0 collecting x))

(defun compile-me ()
  (loop-forever))
</code>```

Compiling compile-me calls loop-forever, which exhausts heap memory during its expansion and crashes the compiler. If you just want to make the compiler hang indefinitely, then this definition of loop-forever will do it:

```<code>(defmacro loop-forever ()
  (loop))
</code>```

This should work using any CL implementation, unless yours is extremely clever and can detect simple infinite loops, but I seriously doubt any do this. Full protection against this is impossible, of course.

Title: Crash your favorite compiler

Body:
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 :)

Body:
Common Lisp

Macros make it easy:

(defmacro loop-forever ()
  (loop for x from 0 collecting x))

(defun compile-me ()
  (loop-forever))

Compiling compile-me calls loop-forever, which exhausts heap memory during its expansion and crashes the compiler. If you just want to make the compiler hang indefinitely, then this definition of loop-forever will do it:

(defmacro loop-forever ()
  (loop))

This should work using any CL implementation, unless yours is extremely clever and can detect simple infinite loops, but I seriously doubt any do this. Full protection against this is impossible, of course.


Title: Jimmy these arrays down

Body:
Perl, 42 + 2 (-0p) = 44 bytes

s%\d+].*%] = {@{[join",",/(-?\d+);/g]}};%s

Needs -p and -0 flags to run. For instance :

perl -0pe 's%\d+].*%] = {@{[join",",/(-?\d+);/g]}};%s' <<< "blah_blah quux[1];
quux[0] = 105;"


答:
R, 78 bytes

Solution is based on counting the number of vowels:

```<code>s=strsplit;w=s(readline(),"")[[1]];v=s("aeiouAEIOU","")[[1]];sum(w%in%v)%%2!=0
</code>```

Explanation

Unfortunately most functions in R relating to strings work on vectors of characters rather than full strings, thus the solution converts input into a vector using strsplit and checks whether this contains any vowels => sum the number of vowels and check if odd/even.

Also I found that using v=s("aeiouAEIOU","")[[1]] was shorter than manually inputting a vector of vowels which would have worked if only lower or upper case letters were used.

Title: Is it an Odd Word?

Body:
R, 78 bytes

Solution is based on counting the number of vowels:

s=strsplit;w=s(readline(),"")[[1]];v=s("aeiouAEIOU","")[[1]];sum(w%in%v)%%2!=0

Explanation

Unfortunately most functions in R relating to strings work on vectors of characters rather than full strings, thus the solution converts input into a vector using strsplit and checks whether this contains any vowels => sum the number of vowels and check if odd/even.

Also I found that using v=s("aeiouAEIOU","")[[1]] was shorter than manually inputting a vector of vowels which would have worked if only lower or upper case letters were used.


答:
Java 7, 262 bytes

```<code>import java.util.*;String c(String z,String y){int i=0,l=y.length();if(z.length()>l)return c(y,z);List x=new ArrayList();for(;i<l;x.add(y.toCharArray()[i++]));for(Object q:z.toCharArray())x.remove(q);String r="";for(i=0;i<x.size();r+=x.get(i++));return z+"_"+r;}
</code>```

Can probably be golfed some more by just using arrays without the lists..

Ungolfed & test cases:

Try it here.

```<code>import java.util.*;
class M{
  static String c(String z, String y){
    int i = 0,
        l = y.length();
    if(z.length() > l){
      return c(y, z);
    }
    List x = new ArrayList();
    for(; i < l; x.add(y.toCharArray()[i++]));
    for(Object q : z.toCharArray()){
      x.remove(q);
    }
    String r = "";
    for(i = 0; i < (x.size()); r += x.get(i++));
    return z+"_"+r;
  }

  public static void main(String[] a){
    System.out.println(c("sale", "salinewater"));
    System.out.println(c("jostling", "juggle"));
    System.out.println(c("juggle", "juggler"));
  }
}
</code>```

Output:

```<code>sale_inwater
juggle_ostin
juggle_r
</code>```

Title: String Concatenation

Body:
Java 7, 262 bytes

import java.util.*;String c(String z,String y){int i=0,l=y.length();if(z.length()>l)return c(y,z);List x=new ArrayList();for(;i<l;x.add(y.toCharArray()[i++]));for(Object q:z.toCharArray())x.remove(q);String r="";for(i=0;i<x.size();r+=x.get(i++));return z+"_"+r;}

Can probably be golfed some more by just using arrays without the lists..

Ungolfed & test cases:

Try it here.

import java.util.*;
class M{
  static String c(String z, String y){
    int i = 0,
        l = y.length();
    if(z.length() > l){
      return c(y, z);
    }
    List x = new ArrayList();
    for(; i < l; x.add(y.toCharArray()[i++]));
    for(Object q : z.toCharArray()){
      x.remove(q);
    }
    String r = "";
    for(i = 0; i < (x.size()); r += x.get(i++));
    return z+"_"+r;
  }

  public static void main(String[] a){
    System.out.println(c("sale", "salinewater"));
    System.out.println(c("jostling", "juggle"));
    System.out.println(c("juggle", "juggler"));
  }
}

Output:

sale_inwater
juggle_ostin
juggle_r


答:
Retina, <s>24</s> 21 bytes

```<code>i`[aeiou]
1
T`Ll`
11
</code>```

(there's a mandatory additional empty line, but formatting ignores it)

Returns 1 for odd words, and void for even ones.

Try it online!

Title: Is it an Odd Word?

Body:
Retina, <s>24</s> 21 bytes

i`[aeiou]
1
T`Ll`
11

(there's a mandatory additional empty line, but formatting ignores it)

Returns 1 for odd words, and void for even ones.

Try it online!


问:
Close-Knit Words

Introduction

According to Rand Al'Thor's post in the Puzzling SE, a close-knit word is any word that contains three alphabetically consecutive letters (in any order).

Words like education, foghorn and cabaret are all considered close-knit words whereas words like learning, klaxon and perform are not close-knit words.

Challenge

The challenge is to code-golf a program capable of taking a single word as input (assumed lower case, for all intents and purposes) and to return output that (if available) lists all consecutive letter sets (also in lower case) if it is a close-knit word, and empty output if it is not a close-knit word.

Examples

```<code>Input: education
Output: cde

Input: foghorn
Output: fgh

Input: cabaret
Output: abc

Input: hijacking
Output: ghi, hij, ijk

Input: pneumonia
Output: mno, nop

Input: klaxon
Output: <<no output>>

Input: perform
Output: <<no output>>

Input: learning
Output: <<no output>>
</code>```

Rules

Whereas input is to be assumed to be a single lower-case word and output must be lower-case, the nature of the output will vary according to the choice of your coding language. Please select a form of output that will best suit the nature of the challenge, whether it be STDOUT, file output, array, etc.

Because this is code-golf, it will be a case of lowest number of bytes being the clear winner.

No silly loopholes.

I will not accept answers that have the consecutive letters in non-alphabetical order... So cab will not be deemed a suitable output for cabaret, for example.

Special note, while the "triplets" don't necessarily have to be in alphabetical order, but the characters within the triplets must be... so in the case of the word "performance", for example, the output mno,nop will be accepted, as will nop,mno. In the case of the word "hijacking", there are six ways that the triplets of ghi, hij and ijk could be arranged in a list, and all six permutations are acceptable as output.

Other than that, on your marks, get set, golf!

答:
T-SQL, 153 bytes

Had to react on the comment from WallyWest, about it being long time since last TSQL answer. Answer was partly inspired by Brian J's answer

Golfed:

```<code>USE MASTER
DECLARE @ varchar(max)='hijacking'

;WITH C as(SELECT distinct ascii(substring(@,number,1))z FROM spt_values)SELECT CHAR(C.z)+CHAR(D.z)+CHAR(E.z)FROM C,C D,C E WHERE c.z+1=d.z and d.z=e.z-1
</code>```

Fiddle

Ungolfed:

```<code>USE MASTER -- can be left out if the master database is already being used
DECLARE @ varchar(max)='hijacking'

;WITH C as
(
  SELECT distinct ascii(substring(@,number,1))z
  FROM spt_values
)
SELECT CHAR(C.z)+CHAR(D.z)+CHAR(E.z)
FROM C,C D,C E
WHERE c.z+1=d.z and d.z=e.z-1
</code>```

Title: Close-Knit Words

Body:
T-SQL, 153 bytes

Had to react on the comment from WallyWest, about it being long time since last TSQL answer. Answer was partly inspired by Brian J's answer

Golfed:

USE MASTER
DECLARE @ varchar(max)='hijacking'

;WITH C as(SELECT distinct ascii(substring(@,number,1))z FROM spt_values)SELECT CHAR(C.z)+CHAR(D.z)+CHAR(E.z)FROM C,C D,C E WHERE c.z+1=d.z and d.z=e.z-1

Fiddle

Ungolfed:

USE MASTER -- can be left out if the master database is already being used
DECLARE @ varchar(max)='hijacking'

;WITH C as
(
  SELECT distinct ascii(substring(@,number,1))z
  FROM spt_values
)
SELECT CHAR(C.z)+CHAR(D.z)+CHAR(E.z)
FROM C,C D,C E
WHERE c.z+1=d.z and d.z=e.z-1


Title: Jimmy these arrays down

Body:
Java 7, <s>159</s> <s>158</s> <s>149</s> 154 bytes

String c(String[]a){a[0]=a[0].split("\\d")[0]+"] = {\b";for(String i:a)a[0]+=i.split("= [{]*")[1];return a[0].replace(";",", ").replaceFirst("..$","};");}

Multiple bytes saved thanks to @cliffroot.

Ungolfed & test code:

Try it here.

class M{
  static String c(String[] a){
    a[0] = a[0].split("\\d")[0] + "] = {\b";
    for(String i : a){
      a[0] += i.split("= [{]*")[1];
    }
    return a[0].replace(";", ", ").replaceFirst("..$", "};");
  }

  public static void main(String[] a){
    System.out.println(c(new String[]{ "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;" }));
    System.out.println(c(new String[]{ "char ans[2]", "ans[0] = 52;", "ans[1] = 50;" }));
    System.out.println(c(new String[]{ "blah_blah quux[1];", "quux[0] = 105;" }));
  }
}

Output:

spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};
char ans[] = {52, 50};
blah_blah quux[] = {105};


答:
Java, 59 bytes

```<code>s->s.chars().map(c->"aeiouAEIOU".indexOf(c)<0?0:1).sum()%2;
</code>```

Ungolfed test program

```<code>public static void main( String[] args )
{
    Function<String, Integer> func = s -> s.chars().map( c -> "aeiouAEIOU".indexOf( c ) < 0 ? 0 : 1 ).sum() % 2;

    System.out.println( func.apply( "cat" ) );
}
</code>```

Title: Is it an Odd Word?

Body:
Java, 59 bytes

s->s.chars().map(c->"aeiouAEIOU".indexOf(c)<0?0:1).sum()%2;

Ungolfed test program

public static void main( String[] args )
{
    Function<String, Integer> func = s -> s.chars().map( c -> "aeiouAEIOU".indexOf( c ) < 0 ? 0 : 1 ).sum() % 2;

    System.out.println( func.apply( "cat" ) );
}


问:
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!

答:
Batch, 74 bytes

```<code>@set/ps=
@for %%i in (%*)do @call echo %%s:~0,%%i%%&call set s=%%s:~%%i%%
</code>```

I'm beating C? This can't be right! Takes the string on STDIN and the array as command-line arguments.

Title: Substring Chainification

Body:
Batch, 74 bytes

@set/ps=
@for %%i in (%*)do @call echo %%s:~0,%%i%%&call set s=%%s:~%%i%%

I'm beating C? This can't be right! Takes the string on STDIN and the array as command-line arguments.


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:
C, 121 bytes

n=2;main(i){for(;putchar(getchar())^91;);for(printf("] = {");~scanf("%*[^=]%*c%d",&i);n=0)printf(", %d"+n,i);puts("};");}


问:
Bake a slice of Pi
Write a program or function that prints or outputs this exact text (consisting of 142 characters):

```<code>()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|
</code>```

Your program must take no input (except in languages where this is impossible, such as sed), and produce the above text (and only the above text) as output. A trailing newline is acceptable.

This is code-golf, so the shortest answer (in bytes) wins.

Title: Bake a slice of Pi

Body:
JavaScript (ES6), <s>170 bytes</s> 165 bytes<s>

is a bit "cheated", since if run on the console, the return value would be displayed

v=0;("()()()()()()\n|9|:87654321".replace(/\d/g,(o)=>"\\"+(Math.PI+'2384626433832795028841971693').substr(v,o,v-=-o)+"|\n"+(o<9?" ".repeat(8-o)+(o>1?"\\::":"\\__\\|"):""))

</s>

After some teaking, the function looks like this(function must be called with parameter with the value 0):

v=>`()()()()()()
 |9 |:87654321\\__\\|`.replace(/\d/g,o=>`\\${(Math.PI+"2384626433832795028841971693").substr(v,o,v-=-o)}|
${" ".repeat(9-o)+(o<9&o>1?"\\::":"")}`)

If you want to call the function 167 bytes:

z=v=>`()()()()()()
 |9 |:87654321\\__\\|`.replace(/\d/g,o=>`\\${(Math.PI+"2384626433832795028841971693").substr(v,o,v-=-o)}|
${" ".repeat(9-o)+(o<9&o>1?"\\::":"")}`)

/*could be run like this or directly in the console*/
console.info("\n"+z(0));


答:
Perl (15)

```<code>BEGIN{1while 1}
</code>```

This creates an infinite loop at compile time:

A BEGIN code block is executed as soon as possible, that is, the moment it is completely defined, even before the rest of the containing file (or string) is parsed.

(from perlmod)

And that's why Perl isn't able to complete parsing the code. This doesn't terminate:

```<code>$ perl -MO=Deparse -e 'BEGIN{1while 1}'
</code>```

Title: Crash your favorite compiler

Body:
Perl (15)

BEGIN{1while 1}

This creates an infinite loop at compile time:

A BEGIN code block is executed as soon as possible, that is, the moment it is completely defined, even before the rest of the containing file (or string) is parsed.

(from perlmod)

And that's why Perl isn't able to complete parsing the code. This doesn't terminate:

$ perl -MO=Deparse -e 'BEGIN{1while 1}'


答:
Batch, 160 bytes

```<code>@echo off
set/ps=
set s=%s:[=[] = {&rem %
set r=
:l
set t=
set/pt=
if "%t%"=="" echo %r%};&exit/b
set t=%t:* =%
set r=%r%%s%%t:~2,-1%
set s=,
goto l
</code>```

Note: The line set s=, ends with a space. Takes input on STDIN. That weird line 3 takes the input (e.g. int spam[6]; and changes the [ into [] = {&rem resulting in set s=int spam[] = {&rem 6]; which then gets interpreted as two statements, set s=int spam[] = { and rem 6];, the latter of which is a comment. Then for each line we delete the text up to the first space (because you can't use = in a pattern and the matching is non-greedy) and extract the value.

Title: Jimmy these arrays down

Body:
Batch, 160 bytes

@echo off
set/ps=
set s=%s:[=[] = {&rem %
set r=
:l
set t=
set/pt=
if "%t%"=="" echo %r%};&exit/b
set t=%t:* =%
set r=%r%%s%%t:~2,-1%
set s=,
goto l

Note: The line set s=, ends with a space. Takes input on STDIN. That weird line 3 takes the input (e.g. int spam[6]; and changes the [ into [] = {&rem resulting in set s=int spam[] = {&rem 6]; which then gets interpreted as two statements, set s=int spam[] = { and rem 6];, the latter of which is a comment. Then for each line we delete the text up to the first space (because you can't use = in a pattern and the matching is non-greedy) and extract the value.


问:
The shortest code to invert bit-wise a binary string
Me thinks there aren't enough easy questions on here that beginners can attempt!

The challenge: Given a random input string of 1's and 0's such as:

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

Write the shortest code that outputs the bit-wise inverse like so:

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

答:
brainfuck, 24 bytes or 19 bytes

```<code>,[>++[->++[<]>-]>-.>>>,]
</code>```

Try it online!

or

```<code>,[+[<[-->>]<--]<.,]
</code>```

(this one requires an interpreter which will noop on < if the data-index is 0)

Both programs use 8-bit wrapping cells. The main part of the programs are the >++[->++[<]>-]>- and +[<[-->>]<--]< which do some rather convoluted things to flip the last bit of the number.

I'm happy I managed to beat some more 'real' languages like C and Python, not something that happens every day with bf ;)

ContentLicense: CC BY-SA 4.0

Body:
brainfuck, 24 bytes or 19 bytes

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

Try it online!

or

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

(this one requires an interpreter which will noop on < if the data-index is 0)

Both programs use 8-bit wrapping cells. The main part of the programs are the >++[->++[<]>-]>- and +[<[-->>]<--]< which do some rather convoluted things to flip the last bit of the number.

I'm happy I managed to beat some more 'real' languages like C and Python, not something that happens every day with bf ;)


答:
Awk, 36 characters

{FIELDWIDTHS=$0;OFS=RS;getline}$1=$1
```

<p>Sample run:</p>

```bash-4.3$ awk '{FIELDWIDTHS=$0;OFS=RS;getline}$1=$1' <<< $'3 2 3\nHello, World!'
Hel
lo
, W
```

<p>In real life I would use it like this, just no idea how to calculate its score:</p>

```bash-4.3$ awk -vFIELDWIDTHS='3 2 3' -vOFS='\n' '$1=$1' <<< 'Hello, World!'
Hel
lo
, W
```

Title: Substring Chainification

Body:
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!

Body:
Awk, 36 characters

{FIELDWIDTHS=$0;OFS=RS;getline}$1=$1

Sample run:

bash-4.3$ awk '{FIELDWIDTHS=$0;OFS=RS;getline}$1=$1' <<< $'3 2 3\nHello, World!'
Hel
lo
, W

In real life I would use it like this, just no idea how to calculate its score:

bash-4.3$ awk -vFIELDWIDTHS='3 2 3' -vOFS='\n' '$1=$1' <<< 'Hello, World!'
Hel
lo
, W


问:
Decipher Neurotic Frogs

Decipher Neurotic Frogs

Now that Puzzling.SE has finally cracked my amphibian-obsessed cipher, let's write a program or function to decrypt it!

(If you want to look at the puzzle before having it spoiled for you, click the above link now.)

How the cipher works

In Neurotic Frogs Ought To Relax In Mud Baths ("Neurotic Frogs" for short), every letter is encrypted as one or two words:

The length of a non-italicized word represents a letter.

neurotic => 8 letters => H

frogs => 5 letters => E

perpendicular => 13 letters = M

A word that contains italics modifies the following word, adding 10 if the italicized word was odd in length or 20 if the italicized word was even in length. Any or all of the word may be italicized. An italicized word is always followed by a non-italicized word.

*o*ught to => odd, 2 => 12 => L

lo*u*nging calms => even, 5 => 25 => Y

Every word of plaintext corresponds to a sentence of ciphertext, and every sentence of plaintext corresponds to a paragraph of ciphertext.

Input format

Your program or function shall input a message in Neurotic Frogs, formatted in Markdown. The input will consist only of printable ASCII and newlines.

Words are runs of characters that match the regex [A-Za-z0-9'].

Numbers and letters both count toward the length of a word. QB64 represents D.

NOTE: Apostrophes do not count toward the length of a word. Isn't represents D, not E.

Italicized letters are wrapped in a pair of asterisks (*letters*).

One or more consecutive letters may be italicized, up to an entire word (masseus*es*, *all*); multiple non-consecutive letters in a word may also be italicized (g*e*n*e*rates).

Italics never span multiple words, never include punctuation, and never include apostrophes.

Unpaired asterisks and multiple adjacent asterisks will never occur.

Punctuation is any of the following characters: .,?!:;-()".

Words within a sentence are separated by one or more punctuation characters and/or a single space. Examples: *all* welcomed, toad*s*, newts, Ever*y*one--frogs, cap... bliss, they're (I

Sentences end with one or more punctuation characters and are separated by a double space: Th*e* Montgomery A*m*phibian Salon!  Come luxuriate today!

Paragraphs are separated by a single newline. (The last sentence of a paragraph still has one or more punctuation characters at the end.)

Other characters will not appear in input and do not need to be handled.

Your code may, at your discretion, expect input to have a single trailing newline.

Output format

The result of decrypting the input will be one or more sentences. Letters of plaintext may be any combination of upper- and lowercase. Words within a sentence must be separated by single spaces. Sentences must end with a period (.) and be separated by a single space. You may output a trailing space after the last sentence. Your output will all be on one line, but you may output a trailing newline.

Miscellaneous details

Your code may use any of the standard input and output methods. It must receive input as a multiline string, not a list or other data structure, and it must output a string.

The shortest code in bytes wins!

Test cases

```<code>-->
Neurotic Frogs *O*ught To Rel*a*x In *M*ud Baths!
<--
HELLO.

-->
Business standards all*o*w only *adult* amphibians.
<--
HINT.

-->
Rejoice, *a*ll frogs an*d* toads also!  Montgomery Sal*o*n opens up!  Ha*pp*y throng fill*s* street ecstatically!
<--
GOOD JOB PPL.

-->
I like 3.1415926535897.
IM*O*, it's a *b*la*st*, yeah!
<--
ADAM. MAN.

-->
*I*, happily, *th*anks 2 u *e*ditin*g* specific wor*ding*--clarifying a *bit*--betterment :D!
<--
QUARTATA.

-->
Perpendicular l*ou*nging calms.  *A* frog, a m*u*d cap... bliss!  Wallowing g*e*n*e*rates happiness.  Amphibian sp*a* isn't expensive--seventy d*o*llars--cheap!  That'*s* not *a* large e*x*pens*e* from an*y* discerning fr*o*g's money, unlik*e* Super 8.
Ever*y*one--frogs, toad*s*, newts, *a*nd salamanders!  G*e*t a wonderful shiat*s*u, or recei*v*e an other kind.  Masseus*es* are her*e* today!  Invite a fianc*e*e, supervisor, roommate, niece: *all* welcomed!
Y*o*u simply ne*v*er believed these p*o*ssibilitie*s*; they're (I *swear*) absolute truth!  Th*e* Montgomery A*m*phibian Salon!  Come luxuriate today!
<--
MY NAME IS INIGO MONTOYA. YOU KILLED MY FATHER. PREPARE TO DIE.
</code>```

Title: Decipher Neurotic Frogs

Body:
PHP, 196 Bytes

<?preg_match_all("#[\w*']+|  |$#m",$_GET[s],$m);foreach($m[0]as$s){if(!$s||$s=="  ")echo!$s?". ":" ";else{$l=$p+64+strlen(str_replace("'","",$s));if(!$p=strstr($s,"*")?20-$l%2*10:0)echo chr($l);}}

If I could assume that there is only one Apostrophe in the middle of a word 194 Bytes

<?preg_match_all("#[\w*]+(<?=')[\w*]+|[\w*]+|  |$#m",$_GET[s],$m);foreach($m[0]as$s){if(!$s||$s=="  ")echo!$s?". ":" ";else{$l=$p+64+strlen($s);if(!$p=strstr($s,"*")?20-$l%2*10:0)echo chr($l);}}


答:
PHP, 98 Bytes

```<code><?php
$b=$argv[1];foreach(explode(',',$argv[2])as$a){echo(substr($b,0,$a).' ');$b=substr($b,$a);}
</code>```

Usage:

```<code>php chainification.php lexicographically 2,2,2,7,4
</code>```

Output:

```<code>le xi co graphic ally
</code>```

There's probably a better solution with PHP.

Title: Substring Chainification

Body:
PHP, 98 Bytes

<?php
$b=$argv[1];foreach(explode(',',$argv[2])as$a){echo(substr($b,0,$a).' ');$b=substr($b,$a);}

Usage:

php chainification.php lexicographically 2,2,2,7,4

Output:

le xi co graphic ally

There's probably a better solution with PHP.


问:
Words -> City Skyline

The challenge

Your program or function will accept a single string input from STDIN or a function parameter. You can assume the input will contain only alphabetic characters (a-zA-Z), spaces, and full stops. Input is case insensitive, so you should treat 'a' exactly the same as you would treat 'A'.

For each character in the string, you will output a representation of a building as per the following specification.

Each building must have a roof, designated by an underscore on the top line then a slash, space, backslash on the second line.

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

You will then have a number of floors, matching the letter number (a=1, b=2, c=3 etc.) which are represented by a wall (|) on each side and a space in the middle. The bottom floor (and only the bottom floor) should have a foundation, which is an underscore between the walls. Like this...

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

So for example, 'b' would look like this

```<code> _
/ \
| |
|_|
</code>```

Now, we know that very tall, narrow buildings cannot stand and must get wider at the base, so no building can stand more than three storeys high without some additional support. So every three levels (no less) you should add a 'widening layer'. The widening layer consists of a slash and backslash directly above the walls of the section below it, and the section below should be two spaces wider than the section above. The extra layer does not count towards the height of the building.

Buildings should not overlap but should not have any unnecessary spaces between them, and the ground is always flat so all buildings should have their base on the same level.

For example, 'abcdefga' will look like this.

```<code>                           _
                          / \
                     _    | |
                _   / \   | |
           _   / \  | |   | |
          / \  | |  | |  /   \
       _  | |  | |  | |  |   |
    _ / \ | |  | | /   \ |   |
 _ / \| | | | /   \|   | |   |  _
/ \| || |/   \|   ||   |/     \/ \
|_||_||_||___||___||___||_____||_|
</code>```

Spaces in the string input should be represented by a double space.

Full stops in the string input should be represented by rubble like this.

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

Further examples

Input = Hello world.

Output =

```<code>                                                   _
                                                  / \
                                                  | |
                                                  | |
                                                  | |
                                                 /   \
                                                 |   |
                                                 |   |                       _
                                                 |   |                      / \
                                                /     \                     | |
                                                |     |                     | |
                                   _            |     |          _          | |
                                  / \           |     |         / \        /   \
                                  | |          /       \        | |        |   |
                                  | |          |       |        | |        |   |
                _        _        | |          |       |        | |        |   |        _
               / \      / \      /   \         |       |       /   \      /     \      / \
               | |      | |      |   |        /         \      |   |      |     |      | |
               | |      | |      |   |        |         |      |   |      |     |      | |
               | |      | |      |   |        |         |      |   |      |     |      | |
   _          /   \    /   \    /     \       |         |     /     \    /       \    /   \
  / \         |   |    |   |    |     |      /           \    |     |    |       |    |   |
  | |         |   |    |   |    |     |      |           |    |     |    |       |    |   |
  | |         |   |    |   |    |     |      |           |    |     |    |       |    |   |
  | |    _   /     \  /     \  /       \     |           |   /       \  /         \  /     \
 /   \  / \  |     |  |     |  |       |    /             \  |       |  |         |  |     |   _
 |   |  | |  |     |  |     |  |       |    |             |  |       |  |         |  |     |  / \
 |   |  | |  |     |  |     |  |       |    |             |  |       |  |         |  |     |  | |
 |   |  | | /       \/       \/         \   |             | /         \/           \/       \ | |
/     \/   \|       ||       ||         |  /               \|         ||           ||       | | |
|     ||   ||       ||       ||         |  |               ||         ||           ||       |/   \
|_____||___||_______||_______||_________|  |_______________||_________||___________||_______||___|/\/\
</code>```

Input = lorem ipsum

```<code>                                                                                _
                                                                                / \
                                                                              _             | |
                                                                             / \            | |
                          _                                                  | |            | |
                         / \                                                 | |           /   \
                         | |                                    _            | |           |   |
                         | |                                   / \          /   \          |   |
              _          | |                                   | |          |   |          |   |
             / \        /   \                                  | |          |   |         /     \
             | |        |   |              _                   | |          |   |         |     |         _
             | |        |   |             / \                 /   \        /     \        |     |        / \
    _        | |        |   |             | |                 |   |        |     |        |     |        | |
   / \      /   \      /     \            | |                 |   |        |     |       /       \       | |
   | |      |   |      |     |            | |                 |   |        |     |       |       |       | |
   | |      |   |      |     |           /   \               /     \      /       \      |       |      /   \
   | |      |   |      |     |           |   |        _      |     |      |       |      |       |      |   |
  /   \    /     \    /       \          |   |       / \     |     |      |       |     /         \     |   |
  |   |    |     |    |       |          |   |       | |     |     |      |       |     |         |     |   |
  |   |    |     |    |       |         /     \      | |    /       \    /         \    |         |    /     \
  |   |    |     |    |       |         |     |      | |    |       |    |         |    |         |    |     |
 /     \  /       \  /         \   _    |     |     /   \   |       |    |         |   /           \   |     |
 |     |  |       |  |         |  / \   |     |     |   |   |       |    |         |   |           |   |     |
 |     |  |       |  |         |  | |  /       \    |   |  /         \  /           \  |           |  /       \
 |     |  |       |  |         |  | |  |       |    |   |  |         |  |           |  |           |  |       |
/       \/         \/           \ | |  |       |   /     \ |         |  |           | /             \ |       |
|       ||         ||           |/   \ |       |   |     | |         |  |           | |             | |       |
|       ||         ||           ||   |/         \  |     |/           \/             \|             |/         \
|_______||_________||___________||___||_________|  |_____||___________||_____________||_____________||_________|
</code>```

Input = a.a.a.x.x.x.a.a.a

```<code>                             _                    _                    _
                            / \                  / \                  / \
                            | |                  | |                  | |
                            | |                  | |                  | |
                            | |                  | |                  | |
                           /   \                /   \                /   \
                           |   |                |   |                |   |
                           |   |                |   |                |   |
                           |   |                |   |                |   |
                          /     \              /     \              /     \
                          |     |              |     |              |     |
                          |     |              |     |              |     |
                          |     |              |     |              |     |
                         /       \            /       \            /       \
                         |       |            |       |            |       |
                         |       |            |       |            |       |
                         |       |            |       |            |       |
                        /         \          /         \          /         \
                        |         |          |         |          |         |
                        |         |          |         |          |         |
                        |         |          |         |          |         |
                       /           \        /           \        /           \
                       |           |        |           |        |           |
                       |           |        |           |        |           |
                       |           |        |           |        |           |
                      /             \      /             \      /             \
                      |             |      |             |      |             |
                      |             |      |             |      |             |
                      |             |      |             |      |             |
                     /               \    /               \    /               \
 _      _      _     |               |    |               |    |               |     _      _      _
/ \    / \    / \    |               |    |               |    |               |    / \    / \    / \
|_|/\/\|_|/\/\|_|/\/\|_______________|/\/\|_______________|/\/\|_______________|/\/\|_|/\/\|_|/\/\|_|
</code>```

Rules

Of course this is code golf, lowest score in bytes wins

Standard loophole rules apply

Any number of additional blank lines before or after the output are allowed

You can choose to output the entire result in one string or offer the output as an array where each element represents one line of output, or send to STDOUT

Note

This is my first post to PPCG, so please go easy on me. It's been through the sandbox. Any negative points or possible improvements please post as a comment and I'll do what I can

答:
Perl, <s>147</s> 146 bytes

Includes +1 for -p

Run with input on STDIN, e.g.

```<code>citysky.pl <<< " abcdefgxyz."
</code>```

citysky.pl:

```<code>#!/usr/bin/perl -p
s%.%@{[map chr~-ord(lc$&)*4/3-4*(abs||-9),-9..9]}%g;y/M\xa248
A|-\xc6\0-\xff/MA||
A}-\xc6A/d,$a=(lc$a).$_ for($_)x36;*_=a;s/\x9f.*?\K\x9f/\xa3/g;y%A\xc6\x9f-\xa3\x0b-\xff%__/|||\\ %
</code>```

Works as shown, but replace the \xhh escapes by their literal value to get the claimed score. You can do that using this commandline:

```<code>perl -0pi -e 's/\\x(..)/chr hex $1/eg;s/\n$//' citysky.pl
</code>```

I haven't really explored any other approaches, so this may be very beatable...

Title: Words -> City Skyline

Body:
Perl, <s>147</s> 146 bytes

Includes +1 for -p

Run with input on STDIN, e.g.

citysky.pl <<< " abcdefgxyz."

citysky.pl:

#!/usr/bin/perl -p
s%.%@{[map chr~-ord(lc$&)*4/3-4*(abs||-9),-9..9]}%g;y/M\xa248
A|-\xc6\0-\xff/MA||
A}-\xc6A/d,$a=(lc$a).$_ for($_)x36;*_=a;s/\x9f.*?\K\x9f/\xa3/g;y%A\xc6\x9f-\xa3\x0b-\xff%__/|||\\ %

Works as shown, but replace the \xhh escapes by their literal value to get the claimed score. You can do that using this commandline:

perl -0pi -e 's/\\x(..)/chr hex $1/eg;s/\n$//' citysky.pl

I haven't really explored any other approaches, so this may be very beatable...


问:
String Distance

Challenge

Given an input of an all-lowercase string [a-z], output the total distance between the letters.

Example

```<code>Input: golf

Distance from g to o : 8
Distance from o to l : 3
Distance from l to f : 6

Output: 17
</code>```

Rules

Standard loopholes forbidden

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

The alphabet can be traversed from either direction. You must always use the shortest path. (i.e the distance between x and c is 5).

Test cases

```<code>Input: aa
Output: 0

Input: stack
Output: 18

Input: zaza
Output: 3

Input: valleys
Output: 35
</code>```

答:
C#, 217 bytes

Golfed:

```<code>IEnumerable<int>g(string k){Func<Char,int>x=(c)=>int.Parse(""+Convert.ToByte(c))-97;for(int i=0;i<k.Length-1;i++){var f=x(k[i]);var s=x(k[i+1]);var d=Math.Abs(f-s);yield return d>13?26-Math.Max(f,s)+Math.Min(f,s):d;}}
</code>```

Ungolfed:

```<code>IEnumerable<int> g(string k)
{
  Func<Char, int> x = (c) => int.Parse("" + Convert.ToByte(c)) - 97;
  for (int i = 0; i < k.Length - 1; i++)
  {
    var f = x(k[i]);
    var s = x(k[i + 1]);
    var d = Math.Abs(f - s);
    yield return d > 13 ? 26 - Math.Max(f, s) + Math.Min(f, s) : d;
  }
}
</code>```

Output:

```<code>aa: 0
stack: 18
zaza: 3
valleys: 35
</code>```

'a' is 97 when converted to bytes, so 97 is subtracted from each one. If the difference is greater than 13 (ie, half of the alphabet), then subtract the differences between each character (byte value) from 26. A last minute addition of "yield return" saved me a few bytes!

Title: String Distance

Body:
C#, 217 bytes

Golfed:

IEnumerable<int>g(string k){Func<Char,int>x=(c)=>int.Parse(""+Convert.ToByte(c))-97;for(int i=0;i<k.Length-1;i++){var f=x(k[i]);var s=x(k[i+1]);var d=Math.Abs(f-s);yield return d>13?26-Math.Max(f,s)+Math.Min(f,s):d;}}

Ungolfed:

IEnumerable<int> g(string k)
{
  Func<Char, int> x = (c) => int.Parse("" + Convert.ToByte(c)) - 97;
  for (int i = 0; i < k.Length - 1; i++)
  {
    var f = x(k[i]);
    var s = x(k[i + 1]);
    var d = Math.Abs(f - s);
    yield return d > 13 ? 26 - Math.Max(f, s) + Math.Min(f, s) : d;
  }
}

Output:

aa: 0
stack: 18
zaza: 3
valleys: 35

'a' is 97 when converted to bytes, so 97 is subtracted from each one. If the difference is greater than 13 (ie, half of the alphabet), then subtract the differences between each character (byte value) from 26. A last minute addition of "yield return" saved me a few bytes!


Title: Bake a slice of Pi

Body:
Write a program or function that prints or outputs this exact text (consisting of 142 characters):

```<code>()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|
</code>```

Your program must take no input (except in languages where this is impossible, such as sed), and produce the above text (and only the above text) as output. A trailing newline is acceptable.

This is code-golf, so the shortest answer (in bytes) wins.

Body:
Javascript, 172 bytes

Paste into your console to run.

for(y=n=0,s=`()()()()()()
`;y<10;y++,s+=`|
`)for(x=-2;x++<9;)s+=x>y(Math.PI+'2384626433832795028841971693'[n++]:`\\${y>8?'__':x+1|y>1?'::':'||'}\\`[y-x]||' ';console.log(s)


问:
print 1 to 100 without using recursion and conditions
can we print 1 to 100 without using any if conditions and loops in c&c++?

Conditon:
main point is you must not use recursion...and doesnt hardcode code in it
for e.g

print(1 2 3..etc);

答:
Perl (65)

Here's a non-trivial Perl approach (not like say for 1 .. 100). The program uses perl's regular expression engine to count its own characters (two times), and that's the reason why I couldn't golfify the content of $k. It tries to find a (minimal, non-greedy) group of arbitrary single characters until (*FAIL).

```<code>$k='$k =~ /^(.+?)(?{print length($1) . "\n"})(*FAIL)/#'x2;eval$k;
</code>```

The output is a list of all integers from 0 to 100 with newlines.

Body:
Perl (65)

Here's a non-trivial Perl approach (not like say for 1 .. 100). The program uses perl's regular expression engine to count its own characters (two times), and that's the reason why I couldn't golfify the content of $k. It tries to find a (minimal, non-greedy) group of arbitrary single characters until (*FAIL).

$k='$k =~ /^(.+?)(?{print length($1) . "\n"})(*FAIL)/#'x2;eval$k;

The output is a list of all integers from 0 to 100 with newlines.


问:
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!

答:
Haskell, <s>63</s> 43 bytes

```<code>f x=maximum[a+b|(a,b)<-tail>>=zip$x,a*b==0]
</code>```

Thanks to @MartinEnder for 4 bytes!

Body:
Haskell, <s>63</s> 43 bytes

f x=maximum[a+b|(a,b)<-tail>>=zip$x,a*b==0]

Thanks to @MartinEnder for 4 bytes!


答:
CJam, 16 bytes

```<code>q~2ew{0&},::+:e>
</code>```

Try it online! (As a test suite.)

Explanation

```<code>q~    e# Read and eval input.
2ew   e# Get all (overlapping) pairs of adjacent values.
{0&}, e# Keep only those that contain a 0.
::+   e# Sum each pair to get the other (usually non-zero) value.
:e>   e# Find the maximum.
</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:
CJam, 16 bytes

q~2ew{0&},::+:e>

Try it online! (As a test suite.)

Explanation

q~    e# Read and eval input.
2ew   e# Get all (overlapping) pairs of adjacent values.
{0&}, e# Keep only those that contain a 0.
::+   e# Sum each pair to get the other (usually non-zero) value.
:e>   e# Find the maximum.


Body:
JavaScript (ES6), <s>59</s> <s>57</s> 56 bytes

let f =

l=>l.map((n,i)=>m=l[i-1]==0|l[i+1]==0&&n>m?n:m,m=-1/0)|m

console.log(f([1, 4, 3, 6, 0, 3, 7, 0]));       // 7
console.log(f([9, 4, 9, 0, 9, 0, 9, 15, -2]));  // 9
console.log(f([-4, -6, -2, 0, -9]));            // -2
console.log(f([-11, 0, 0, 0, 0, 0, -12, 10]));  // 0
console.log(f([3, 0, 5]));                      // 5
console.log(f([28, 0, 14, 0]));                 // 28

Edit: saved 2 bytes thanks to Huntro

Edit: saved 1 byte thanks to ETHproductions


答:
PHP, <s>77</s> <s>68</s> 71 bytes

<s>-3 bytes from anonymous,</s> -4 and -2 from MartinEnder

```<code>preg_match_all("#(?<=\b0 )\S+|\S+(?= 0)#",$argv[1],$m);echo max($m[0]);
</code>```

run with php -r '' '<space separated values>'

Body:
PHP, <s>77</s> <s>68</s> 71 bytes

<s>-3 bytes from anonymous,</s> -4 and -2 from MartinEnder

preg_match_all("#(?<=\b0 )\S+|\S+(?= 0)#",$argv[1],$m);echo max($m[0]);

run with php -r '<code>' '<space separated values>'


答:
Pyth, 12 11 10 bytes

```<code>eSsM/#0,Vt
</code>```

Forms pairs, filters by zero member, sorts by sum, returns largest.

Body:
Pyth, 12 11 10 bytes

eSsM/#0,Vt

Forms pairs, filters by zero member, sorts by sum, returns largest.


答:
05AB1E, 9 bytes

```<code>ü‚D€P_ÏOZ
</code>```

Explanation

```<code>ü‚         # pair up elements
  D        # duplicate
   €P      # product of each pair (0 if the pair contains a 0)
     _     # logical negate, turns 0 into 1 and everything else to 0
      Ï    # keep only the pairs containing at least 1 zero
       O   # sum the pairs
        Z  # take max
</code>```

Doesn't work in the online interpreter, but works offline.

Body:
05AB1E, 9 bytes

ü‚D€P_ÏOZ

Explanation

ü‚         # pair up elements
  D        # duplicate
   €P      # product of each pair (0 if the pair contains a 0)
     _     # logical negate, turns 0 into 1 and everything else to 0
      Ï    # keep only the pairs containing at least 1 zero
       O   # sum the pairs
        Z  # take max

Doesn't work in the online interpreter, but works offline.


答:
MATL, 10 bytes

```<code>t~5BZ+g)X>
</code>```

Try it online! Or verify all test cases.

Explanation

Let's take input [-4 -6 -2 0 -9] as an example.

```<code>t     % Input array. Duplicate
      %   STACK: [-4 -6 -2 0 -9],  [-4 -6 -2 0 -9]
~     % Logical negate. Replaces zeros by logical 1, and nonzeros by logical 0
      %   STACK: [-4 -6 -2 0 -9],  [0 0 0 1 0]
5B    % Push logical array [1 0 1] (5 in binary)
      %   STACK: [-4 -6 -2 0 -9], [0 0 0 1 0], [1 0 1]
Z+    % Convolution, maintaining size. Gives nonzero (1 or 2) for neighbours of
      % zeros in the original array, and zero for the rest
      %   STACK: [-4 -6 -2 0 -9], [0 0 1 0 1]
g     % Convert to logical
      %   STACK: [-4 -6 -2 0 -9], [0 0 1 0 1]
)     % Use as index into original array
      %   STACK: [-2 -9]
X>    % Maximum of array.
      %   STACK: -2
      % Implicitly display
</code>```

Body:
MATL, 10 bytes

t~5BZ+g)X>

Try it online! Or verify all test cases.

Explanation

Let's take input [-4 -6 -2 0 -9] as an example.

t     % Input array. Duplicate
      %   STACK: [-4 -6 -2 0 -9],  [-4 -6 -2 0 -9]
~     % Logical negate. Replaces zeros by logical 1, and nonzeros by logical 0
      %   STACK: [-4 -6 -2 0 -9],  [0 0 0 1 0]
5B    % Push logical array [1 0 1] (5 in binary)
      %   STACK: [-4 -6 -2 0 -9], [0 0 0 1 0], [1 0 1]
Z+    % Convolution, maintaining size. Gives nonzero (1 or 2) for neighbours of
      % zeros in the original array, and zero for the rest
      %   STACK: [-4 -6 -2 0 -9], [0 0 1 0 1]
g     % Convert to logical
      %   STACK: [-4 -6 -2 0 -9], [0 0 1 0 1]
)     % Use as index into original array
      %   STACK: [-2 -9]
X>    % Maximum of array.
      %   STACK: -2
      % Implicitly display


Title: Bake a slice of Pi

Body:
Ruby, <s>140</s> <s>138</s> 137 bytes

My solution to this problem in ruby, this is my first code golf answer :D

[0,2384626,433832,79502,8841,971,69,3,1].map{|n|puts n<1?"()"*6+"\n|\\3.1415926|\n|:\\53589793|":"\\#{n>1?"::\\#{n}":"__\\"}|".rjust(12)}

Readable version and explanation:

for n in [-1,2384626,433832,79502,8841,971,69,3,0]
  if n < 0 # n == -1
    puts "()"*6+"\n|\\3.1415926|\n|:\\53589793|"
  else
    if n > 0 # digits of pi
      puts "\\::\\#{n}|".rjust(12)
    else # edge of pie
      puts "\\__\\|".rjust(12)
    end
  end
end

Nothing really clever, just using some simple loops :)

Output:

()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|


答:
Julia, <s>56</s> 55 Bytes

```<code>f(l)=max(map(sum,filter(t->0 in t,zip(l,l[2:end])))...)
</code>```

Create tuples for neighboring values, take those tuples containing 0, sum tuple values and find maximum

Body:
Julia, <s>56</s> 55 Bytes

f(l)=max(map(sum,filter(t->0 in t,zip(l,l[2:end])))...)

Create tuples for neighboring values, take those tuples containing 0, sum tuple values and find maximum


答:
MATLAB with Image Processing Toolbox, 32 bytes

```<code>@(x)max(x(imdilate(~x,[1 0 1])))
</code>```

This is an anonymous function. Example use for the test cases:

```<code>>> f = @(x)max(x(imdilate(~x,[1 0 1])))
f =
  function_handle with value:
    @(x)max(x(imdilate(~x,[1,0,1])))

>> f([1 4 3 6 0 3 7 0])
ans =
     7

>> f([9 4 9 0 9 0 9 15 -2])
ans =
     9

>> f([-4 -6 -2 0 -9])
ans =
    -2

>> f([-11 0 0 0 0 0 -12 10])
ans =
     0

>> f([0 20])
ans =
    20
</code>```

Body:
MATLAB with Image Processing Toolbox, 32 bytes

@(x)max(x(imdilate(~x,[1 0 1])))

This is an anonymous function. Example use for the test cases:

>> f = @(x)max(x(imdilate(~x,[1 0 1])))
f =
  function_handle with value:
    @(x)max(x(imdilate(~x,[1,0,1])))

>> f([1 4 3 6 0 3 7 0])
ans =
     7

>> f([9 4 9 0 9 0 9 15 -2])
ans =
     9

>> f([-4 -6 -2 0 -9])
ans =
    -2

>> f([-11 0 0 0 0 0 -12 10])
ans =
     0

>> f([0 20])
ans =
    20