答:
Julia, 40 bytes

!s=[print(c,isalpha(c)?c$' ':"")for c=s]
```

Try it online!

Title: Duplicate & switch case

Body:
Julia, 40 bytes

!s=[print(c,isalpha(c)?c$' ':"")for c=s]

Try it online!


问:
Generate a Stack Exchange Favicon
Do you recognize the PPCG logo?
it looks like this, when you do an ascii art of it.

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

Now, In this Code Golf, You will make a code, that makes logos for other sites, similar to the PPCG logo.

What You should do

The "Shortened" string will be the string, with all upper case letters and numbers in the input string.(Which would be PPCG when the input string is Programming Puzzles & Code Golf)

The "Box" (

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

)
should fit the Shortened string perfectly.(No bigger or smaller)

Also the v part should be exactly 1 down and 1 left to the down right +.

Then output the box which has the shortened string in it.

Example

Stack Overflow:

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

Area 51:

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

Rules

You may assume that the input contains at least one digit or upper case letter.

Standard code-golf rules apply.

ContentLicense: CC BY-SA 3.0

Title: Generate a Stack Exchange Favicon

Body:
Haskell, 161

import Data.List
r=replicate
l=length
f n=intersect n$['0'..'9']++['A'..'Z']
t n='+':(r(l$f n)'-')++"+\n"
o n=(t n)++"|"++(f n)++"|\n"++(t n)++(r(l$f n)' ')++"V"

Usage

o"Stack Overflow"
+--+
|SO|
+--+
  V

o"Area 51"
+---+
|A51|
+---+
   V


答:
C, 194 bytes

```<code>s[99999],*p;char*c;k(h){h=*c-h;return h*h<2?h:0;}main(d,i){c=1[p=i];for(p=s;*c;++c){(*p)-=k(44);p+=k(61);*c^46?*c^44?0:(*p=getchar()):putchar(*p);d=k(92);if(*p?~d:d-1)for(i=d;i;i+=k(92))c-=d;}}
</code>```

Expects the brainfuck program as the first command line argument.

ContentLicense: CC BY-SA 4.0

Title: Interpret brainfuck

Body:
Write the shortest program in your favourite language to interpret a brainfuck program. The program is read from a file. Input and output are standard input and standard output.

Cell size: 8bit unsigned. Overflow is undefined.

Array size: 30000 bytes (not circled)

Bad commands are not part of the input

Comments begin with # and extend to the end of line Comments are everything not in +-.,[]<>

no EOF symbol

A very good test can be found here. It reads a number and then prints the prime numbers up to that number. To prevent link rot, here is a copy of the code:

```<code>compute prime numbers
to use type the max number then push Alt 1 0
===================================================================
======================== OUTPUT STRING ============================
===================================================================
>++++++++[<++++++++>-]<++++++++++++++++.[-]
>++++++++++[<++++++++++>-]<++++++++++++++.[-]
>++++++++++[<++++++++++>-]<+++++.[-]
>++++++++++[<++++++++++>-]<+++++++++.[-]
>++++++++++[<++++++++++>-]<+.[-]
>++++++++++[<++++++++++>-]<+++++++++++++++.[-]
>+++++[<+++++>-]<+++++++.[-]
>++++++++++[<++++++++++>-]<+++++++++++++++++.[-]
>++++++++++[<++++++++++>-]<++++++++++++.[-]
>+++++[<+++++>-]<+++++++.[-]
>++++++++++[<++++++++++>-]<++++++++++++++++.[-]
>++++++++++[<++++++++++>-]<+++++++++++.[-]
>+++++++[<+++++++>-]<+++++++++.[-]
>+++++[<+++++>-]<+++++++.[-]

===================================================================
======================== INPUT NUMBER  ============================
===================================================================
+                          cont=1
[
 -                         cont=0
 >,
 ======SUB10======
 ----------

 [                         not 10
  <+>                      cont=1
  =====SUB38======
  ----------
  ----------
  ----------
  --------

  >
  =====MUL10=======
  [>+>+<<-]>>[<<+>>-]<     dup

  >>>+++++++++
  [
   <<<
   [>+>+<<-]>>[<<+>>-]<    dup
   [<<+>>-]
   >>-
  ]
  <<<[-]<
  ======RMOVE1======
  <
  [>+<-]
 ]
 <
]
>>[<<+>>-]<<

===================================================================
======================= PROCESS NUMBER  ===========================
===================================================================

==== ==== ==== ====
numd numu teid teiu
==== ==== ==== ====

>+<-
[
 >+
 ======DUP======
 [>+>+<<-]>>[<<+>>-]<

 >+<--

 >>>>>>>>+<<<<<<<<   isprime=1

 [
  >+

  <-

  =====DUP3=====
  <[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<<<

  =====DUP2=====
  >[>>+>+<<<-]>>>[<<<+>>>-]<<< <

  >>>

  ====DIVIDES=======
  [>+>+<<-]>>[<<+>>-]<   DUP i=div

  <<
  [
    >>>>>+               bool=1
    <<<
    [>+>+<<-]>>[<<+>>-]< DUP
    [>>[-]<<-]           IF i THEN bool=0
    >>
    [                    IF i=0
      <<<<
      [>+>+<<-]>>[<<+>>-]< i=div
      >>>
      -                  bool=0
    ]
    <<<
    -                    DEC i
    <<
    -
  ]

  +>>[<<[-]>>-]<<
  >[-]<                  CLR div
  =====END DIVIDES====

  [>>>>>>[-]<<<<<<-]     if divides then isprime=0

  <<

  >>[-]>[-]<<<
 ]

 >>>>>>>>
 [
  -
  <<<<<<<[-]<<

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

  >>

  ===================================================================
  ======================== OUTPUT NUMBER  ===========================
  ===================================================================
  [>+<-]>

  [
   ======DUP======
   [>+>+<<-]>>[<<+>>-]<

   ======MOD10====
   >+++++++++<
   [
    >>>+<<              bool= 1
    [>+>[-]<<-]         bool= ten==0
    >[<+>-]             ten = tmp
    >[<<++++++++++>>-]  if ten=0 ten=10
    <<-                 dec ten
    <-                  dec num
   ]
   +++++++++            num=9
   >[<->-]<             dec num by ten

   =======RROT======
      [>+<-]
   <  [>+<-]
   <  [>+<-]
   >>>[<<<+>>>-]
   <

   =======DIV10========
   >+++++++++<
   [
    >>>+<<                bool= 1
    [>+>[-]<<-]           bool= ten==0
    >[<+>-]               ten = tmp
    >[<<++++++++++>>>+<-] if ten=0 ten=10  inc div
    <<-                   dec ten
    <-                    dec num
   ]
   >>>>[<<<<+>>>>-]<<<<   copy div to num
   >[-]<                  clear ten

   =======INC1=========
   <+>
  ]

  <
  [
   =======MOVER=========
   [>+<-]

   =======ADD48========
   +++++++[<+++++++>-]<->

   =======PUTC=======
   <.[-]>

   ======MOVEL2========
   >[<<+>>-]<

   <-
  ]

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

  ===================================================================
  =========================== END FOR ===============================
  ===================================================================

  >>>>>>>
 ]
 <<<<<<<<

 >[-]<
  [-]
 <<-
]

======LF========

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

Example run:

```<code>$ python2 bf.py PRIME.BF
Primes up to: 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
</code>```

Body:
C, 194 bytes

s[99999],*p;char*c;k(h){h=*c-h;return h*h<2?h:0;}main(d,i){c=1[p=i];for(p=s;*c;++c){(*p)-=k(44);p+=k(61);*c^46?*c^44?0:(*p=getchar()):putchar(*p);d=k(92);if(*p?~d:d-1)for(i=d;i;i+=k(92))c-=d;}}

Expects the brainfuck program as the first command line argument.


问:
How to determine if a number is odd or even without mod -or- bitwise operations?
How to determine if a number is odd or even without mod -or- bitwise operations?

This challenge is grossly inefficient, but challenges your ability to think outside the box for a creative solution.

EDIT:

Please create a function. Also, while regex is a fun response, the function should accept any valid number.

BACKGROUND:
This question stems from my earliest programming days.  The homework for our first day of class was to write a simple program that printed 'odd' or 'even'.  Being the brat I was, I didn't read the book we had for the class where it simply showed us how to use % to determine that.  I spent about a half hour pacing back in forth in my room trying to think of a way to do this and had remembered from the lecture that numbers can lose and gain precision as they are cast from one primitive type to another.  Therefore, if you took the number, divided it by two and then multiplied it back didn't equal the original number, then you would know that the number was odd.

I was stunned the next day, while our instructor was evaluating our programs, that he thought that it was the most original, if inefficient, way of solving the problem.

答:
Q

Keep subtracting 2 until x<2 then convert to bool

```<code>{1b$-[;2]/[2<=;abs x]}
</code>```

Body:
Q

Keep subtracting 2 until x<2 then convert to bool

{1b$-[;2]/[2<=;abs x]}


问:
Is it a sum-free set?
A set is sum-free if no two (not necessarily distinct) elements when added together are part of the set itself.

For example, {1, 5, 7} is sum-free, because all members are odd, and two odd numbers when added together are always even. On the other hand, {2, 4, 9, 13} is not sum-free, as either 2 + 2 = 4 or 4 + 9 = 13 add together to a member of the set.

Write a program or function that takes a set as input, and outputs a Truthy value if the set is sum-free, and Falsy otherwise.

Examples:

```<code>Sum-free:
{}
{4}
{1, 5, 7}
{16, 1, 4, 9}

Not sum-free:
{0}
{1, 4, 5, 7}
{3, 0}
{16, 1, 4, 8}
</code>```

答:
Java, 67 bytes

s->!s.stream().anyMatch(p->s.stream().anyMatch(q->s.contains(p+q)))
```

<p>Input is a <code>Set<Integer></code>. Tests:</p>

<pre class="lang-java prettyprint-override"><code>import java.util.Arrays;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

public class SumFree {
    public static void main(String[] args) {
        sumFree(s->!s.stream()
            .anyMatch(p->s.stream()
                .anyMatch(q->s.contains(p+q)))); // formatted to avoid wrapping
    }

    public static void sumFree(Function<Set<Integer>, Boolean> func) {
        test(func);
        test(func, 4);
        test(func, 1, 5, 7);
        test(func, 16, 1, 4, 9);
        test(func, 1, 4, 5, 7);
        test(func, 0);
        test(func, 3, 0);
        test(func, 16, 1, 4, 8);
    }

    public static void test(Function<Set<Integer>, Boolean> func, Integer... vals) {
        Set<Integer> set = Arrays.stream(vals).collect(Collectors.toSet());
        System.out.format("%b %s%n", func.apply(set), set);
    }
}
</code>```

Output:

true []
true [4]
true [1, 5, 7]
true [16, 1, 4, 9]
false [0]
false [1, 4, 5, 7]
false [0, 3]
false [16, 1, 4, 8]
```

Title: Is it a sum-free set?

Body:
Java, 67 bytes

s->!s.stream().anyMatch(p->s.stream().anyMatch(q->s.contains(p+q)))

Input is a Set<Integer>. Tests:

import java.util.Arrays;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

public class SumFree {
    public static void main(String[] args) {
        sumFree(s->!s.stream()
            .anyMatch(p->s.stream()
                .anyMatch(q->s.contains(p+q)))); // formatted to avoid wrapping
    }

    public static void sumFree(Function<Set<Integer>, Boolean> func) {
        test(func);
        test(func, 4);
        test(func, 1, 5, 7);
        test(func, 16, 1, 4, 9);
        test(func, 1, 4, 5, 7);
        test(func, 0);
        test(func, 3, 0);
        test(func, 16, 1, 4, 8);
    }

    public static void test(Function<Set<Integer>, Boolean> func, Integer... vals) {
        Set<Integer> set = Arrays.stream(vals).collect(Collectors.toSet());
        System.out.format("%b %s%n", func.apply(set), set);
    }
}

Output:

true []
true [4]
true [1, 5, 7]
true [16, 1, 4, 9]
false [0]
false [1, 4, 5, 7]
false [0, 3]
false [16, 1, 4, 8]


问:
Solve the chromatic puzzle
Over at our friends at Puzzling.SE, the following puzzle was posted: Is this chromatic puzzle always solvable? by Edgar G. You can play it here.

Puzzle explanation

Given a m x n grid with tiles of three different colours, you may select any two adjacent tiles, if their colours are different. These two tiles are then converted to the third colour, i.e., the one colour not represented by these two tiles. The puzzle is solved if all tiles have the same colour. Apparently, one can prove that this puzzle is always solvable, if  neither m nor n are divisible by 3.

Of course, this begs for a solving algorithm. You will write a function or program that solves this puzzle. Note that functions with 'side effects' (i.e., the output is on stdout rather than in some awkward data type return value) are explicitly allowed.

Input & Output

The input will be an m x n matrix consisting of the integers 1, 2 and 3 (or 0, 1, 2 if convenient). You may take this input in any sane format. Both m and n are >1 and not divisible by 3. You may assume the puzzle is not solved

You will then solve the puzzle. This will involve a repeated selection of two adjacent tiles to be 'converted' (see above). You will output the two coordinates of these tiles for each step your solving algorithm took. This may also be in any sane output format. You are free to choose between 0-based and 1-based indexing of your coordinates, and whether rows or columns are indexed first. Please mention this in your answer, however.

Your algorithm should run within reasonable time on the original 8x8 case. Brute-forcing it completely is explicitly disallowed, i.e. your algorithm should run under O(k^[m*(n-1)+(m-1)*n]) with k the number of steps needed for the solution. The solution however is not required to be optimal. The proof given in the linked question may give you an idea as to how to do this (e.g., first do all columns using only vertically adjacent tiles, and then do all rows)

Test cases

In these test cases, the coordinates are 1-based and rows are indexed first (like MATLAB/Octave and probably many others).

```<code>Input:
[1 2]
Output: (result: all 3's)
[1 1],[1,2]

Input:
[ 1 2
  3 1 ]
Output: (result: all 1's)
[1 1],[2 1]        (turn left column into 2's)
[2 1],[2 2]        (turn right column into 3's)
[1 1],[1 2]        (turn top row into 1's)
[2 1],[2 2]        (turn bottom row into 1's)

Input:
[1 2 3 2
 3 2 1 1]

Output: (result: all 3's)
[1 1],[1 2]
[1 3],[1 4]
[1 2],[1 3]
[1 1],[1 2]
[1 2],[1 3]
[1 1],[1 2]
[1 3],[1 4]
[2 1],[2 2]
[1 1],[2 1]
[1 2],[2 2]
[1 3],[2 3]
[1 4],[2 4]
</code>```

If desired, I may post a pastebin of larger test cases, but I think this should be sufficient.

答:
C, 404 bytes

My first code golf, I'm pretty happy with how it turned out. Took way too long, though. It's not fully standard C, just whatever will compile under gcc with no special flags (and ignoring warnings). So there's a nested function in there. The function f takes the dimensions m and n as its first arguments, and as it's third argument takes takes an (int pointer) to an array of size m×n (indexed by rows first). The other arguments are dummy arguments, you don't need to pass them in, they're just there to save bytes on declaring variables.  It writes each changed pair to STDOUT in the format row1,col1:row1,col1;, with the semicolon separating the pairs. Uses 0-based indexing.

```<code>#define A a[i*o+p
#define B A*c
f(m,n,a,i,j,o,p,b,c,d)int*a;{
int t(x){printf("%d,%d:%d,%d;",b?i:c+x,b?c+x:i,b?i:c+1+x,b?c+1+x:i);}
o=n;p=b=1;for(;~b;b--){
for(i=0;i<m;i++){c=j=0;
for(;j<n;)c+=A*j++];d=c*n%3;
for(j=0;j<n-1;j++)
while(A*j]^d|A*j+p]^d){
for(c=j;B]==B+p];c++);
if(c<n-2&B]==d&2*(B+p]+A*(c+2)])%3==d)
B+p]=A*(c+2)]=d,t(1);else
B]=B+p]=2*(B]+B+p])%3,
t(0);}}o=m;p=m=n;n=o;o=1;}}
</code>```

I used a slightly different algorithm than OP for solving individual rows/columns. It goes something like this(pseudocode):

```<code>for j in range [0, rowlength):
    while row[j] != targetCol or row[j+1] != targetCol:
        e=j
        while row[e] == row[e+1]:
            e++             //e will never go out of bounds
        if e<=rowLength-3 and row[e] == targetCol
                and (row[e+1] != row[e+2] != targetCol):
            row.changeColor(e+1, e+2)
        else:
            row.changeColor(e, e+1)
</code>```

The for(;~b;b--) loop executes exactly twice, on the second pass it solves columns instead of rows. This is done by swapping n and m, and changing the values of o and p which are used in pointer arithmetic to address the array.

Here's a version that's ungolfed, with a test main, and prints the whole array after every move (press enter to step 1 turn):

```<code>#define s(x,y)b?x:y,b?y:x
#define A a[i*o+p
#define B A*e
f(m,n,a,i,j,o,p,b,c,d,e)int*a;{

    int t(x){
        printf("%d,%d:%d,%d;\n",s(i,e+x),s(i,e+1+x));
        getchar();
        printf("\n");
        for(int i2=0;i2<(b?m:n);i2++){
            for(int j2=0;j2<(b?n:m);j2++){
                printf("%d ",a[i2*(b?n:m)+j2]);
            }
            printf("\n");
        }
        printf("\n");
    }

    printf("\n");
    b=1;
    for(int i2=0;i2<(b?m:n);i2++){
        for(int j2=0;j2<(b?n:m);j2++){
            printf("%d ",a[i2*(b?n:m)+j2]);
        }
        printf("\n");
    }
    printf("\n");

    o=n;p=1;
    for(b=1;~b;b--){
        for(i=0;i<m;i++){
            c=0;
            for(j=0;j<n;j++) c+= a[i*o+p*j];
            d=0;
            d = (c*n)%3;
            for(j=0;j<n-1;j++) {
                while(a[i*o+p*j]!=d||a[i*o+p*j+p]!=d){
                    for(e=j;a[i*o+p*e]==a[i*o+p*e+p];e++);
                    if(e<=n-3 && a[i*o+p*e]==d
                            && 2*(a[i*o+p*e+p]+a[i*o+p*(e+2)])%3==d){
                        a[i*o+p*e+p]=a[i*o+p*(e+2)]=d;
                        t(1);
                    }else{
                        a[i*o+p*e]=a[i*o+p*e+p] = 2*(a[i*o+p*e]+a[i*o+p*e+p])%3;
                        t(0);
                    }
                }
            }
        }
        o=m;p=m=n;n=o;o=1;
    }
}

main(){
    int g[11][11] =
    {
        {0,2,1,2,2,1,0,1,1,0,2},
        {2,1,1,0,1,1,2,0,2,1,0},
        {1,0,2,1,0,1,0,2,1,2,0},
        {0,0,2,1,2,0,1,2,0,0,1},
        {0,2,1,2,2,1,0,0,0,2,1},
        {2,1,1,0,1,1,2,1,0,0,2},
        {1,0,2,1,0,1,0,2,2,1,2},
        {0,0,2,1,2,0,1,0,1,2,0},
        {1,2,0,1,2,0,0,2,1,2,0},
        {2,1,1,0,1,1,2,1,0,0,2},
        {0,2,1,0,1,0,2,1,0,0,2},
    };
    #define M 4
    #define N 7
    int grid[M][N];
    for(int i=0;i<M;i++) {
        for(int j=0;j<N;j++) {
            grid[i][j] = g[i][j];
        }
    }
    f(M,N,grid[0],0,0,0,0,0,0,0,0);
};
</code>```

Title: Solve the chromatic puzzle

Body:
C, 404 bytes

My first code golf, I'm pretty happy with how it turned out. Took way too long, though. It's not fully standard C, just whatever will compile under gcc with no special flags (and ignoring warnings). So there's a nested function in there. The function f takes the dimensions m and n as its first arguments, and as it's third argument takes takes an (int pointer) to an array of size m×n (indexed by rows first). The other arguments are dummy arguments, you don't need to pass them in, they're just there to save bytes on declaring variables.  It writes each changed pair to STDOUT in the format row1,col1:row1,col1;, with the semicolon separating the pairs. Uses 0-based indexing.

#define A a[i*o+p
#define B A*c
f(m,n,a,i,j,o,p,b,c,d)int*a;{
int t(x){printf("%d,%d:%d,%d;",b?i:c+x,b?c+x:i,b?i:c+1+x,b?c+1+x:i);}
o=n;p=b=1;for(;~b;b--){
for(i=0;i<m;i++){c=j=0;
for(;j<n;)c+=A*j++];d=c*n%3;
for(j=0;j<n-1;j++)
while(A*j]^d|A*j+p]^d){
for(c=j;B]==B+p];c++);
if(c<n-2&B]==d&2*(B+p]+A*(c+2)])%3==d)
B+p]=A*(c+2)]=d,t(1);else
B]=B+p]=2*(B]+B+p])%3,
t(0);}}o=m;p=m=n;n=o;o=1;}}

I used a slightly different algorithm than OP for solving individual rows/columns. It goes something like this(pseudocode):

for j in range [0, rowlength):
    while row[j] != targetCol or row[j+1] != targetCol:
        e=j
        while row[e] == row[e+1]:
            e++             //e will never go out of bounds
        if e<=rowLength-3 and row[e] == targetCol
                and (row[e+1] != row[e+2] != targetCol):
            row.changeColor(e+1, e+2)
        else:
            row.changeColor(e, e+1)

The for(;~b;b--) loop executes exactly twice, on the second pass it solves columns instead of rows. This is done by swapping n and m, and changing the values of o and p which are used in pointer arithmetic to address the array.

Here's a version that's ungolfed, with a test main, and prints the whole array after every move (press enter to step 1 turn):

#define s(x,y)b?x:y,b?y:x
#define A a[i*o+p
#define B A*e
f(m,n,a,i,j,o,p,b,c,d,e)int*a;{

    int t(x){
        printf("%d,%d:%d,%d;\n",s(i,e+x),s(i,e+1+x));
        getchar();
        printf("\n");
        for(int i2=0;i2<(b?m:n);i2++){
            for(int j2=0;j2<(b?n:m);j2++){
                printf("%d ",a[i2*(b?n:m)+j2]);
            }
            printf("\n");
        }
        printf("\n");
    }

    printf("\n");
    b=1;
    for(int i2=0;i2<(b?m:n);i2++){
        for(int j2=0;j2<(b?n:m);j2++){
            printf("%d ",a[i2*(b?n:m)+j2]);
        }
        printf("\n");
    }
    printf("\n");

    o=n;p=1;
    for(b=1;~b;b--){
        for(i=0;i<m;i++){
            c=0;
            for(j=0;j<n;j++) c+= a[i*o+p*j];
            d=0;
            d = (c*n)%3;
            for(j=0;j<n-1;j++) {
                while(a[i*o+p*j]!=d||a[i*o+p*j+p]!=d){
                    for(e=j;a[i*o+p*e]==a[i*o+p*e+p];e++);
                    if(e<=n-3 && a[i*o+p*e]==d
                            && 2*(a[i*o+p*e+p]+a[i*o+p*(e+2)])%3==d){
                        a[i*o+p*e+p]=a[i*o+p*(e+2)]=d;
                        t(1);
                    }else{
                        a[i*o+p*e]=a[i*o+p*e+p] = 2*(a[i*o+p*e]+a[i*o+p*e+p])%3;
                        t(0);
                    }
                }
            }
        }
        o=m;p=m=n;n=o;o=1;
    }
}

main(){
    int g[11][11] =
    {
        {0,2,1,2,2,1,0,1,1,0,2},
        {2,1,1,0,1,1,2,0,2,1,0},
        {1,0,2,1,0,1,0,2,1,2,0},
        {0,0,2,1,2,0,1,2,0,0,1},
        {0,2,1,2,2,1,0,0,0,2,1},
        {2,1,1,0,1,1,2,1,0,0,2},
        {1,0,2,1,0,1,0,2,2,1,2},
        {0,0,2,1,2,0,1,0,1,2,0},
        {1,2,0,1,2,0,0,2,1,2,0},
        {2,1,1,0,1,1,2,1,0,0,2},
        {0,2,1,0,1,0,2,1,0,0,2},
    };
    #define M 4
    #define N 7
    int grid[M][N];
    for(int i=0;i<M;i++) {
        for(int j=0;j<N;j++) {
            grid[i][j] = g[i][j];
        }
    }
    f(M,N,grid[0],0,0,0,0,0,0,0,0);
};


问:
Directory Structure Graphical Treefication
Convert a classical directory structure like this:

```<code>config.yml
drafts
    begin-with-the-crazy-ideas.textile
    on-simplicity-in-technology.markdown
includes
    footer.html
    header.html
</code>```

Into this

```<code>.
├── config.yml
├── drafts
|   ├── begin-with-the-crazy-ideas.textile
|   └── on-simplicity-in-technology.markdown
└── includes
    ├── footer.html
    └── header.html
</code>```

Four spaces specify a nested folder or file of the above dir.

Nested categories levels allowed can vary.

Update

filenames: valid Linux filenames without spaces and linefeeds: any byte except NUL, / and spaces, linefeeds

drawing characters:

| vertical line (U+007C)

─ box drawings light horizontal (U+2500)

├ box drawings light vertical and right (U+251C)

Winner: Shortest Code in Bytes wins!

答:
Retina, 88 bytes

```<code>m`^ *
$&├──
 {4}
|
T+`|├` └`(?<=(.)*).(?!.+¶(?>(?<-1>.)*)[|├└])
^
.¶
</code>```

Try it online!

I suppose I could technically count this as one byte per character by swapping out some characters, reading the source as ISO 8859-1 and then finding a single-byte encoding for the output which contains ├ and └, but I can't be bothered to work out the details right now. (For the record, that would be 72 bytes.)

Explanation

Stage 1: Substitution

```<code>m`^ *
$&├──
</code>```

We start by matching the indentation on each line and inserting ├──.

Stage 2: Substitution

```<code> {4}
|
</code>```

Next, we match every group of 4 spaces and replace the first with a |. Now all that needs fixing is | that go to the bottom of the output and ├ that should be └. Both of those cases can be recognised by looking at the character directly below the one we potentially want to change.

Stage 3: Transliteration

```<code>T+`|├` └`(?<=(.)*).(?!.+¶(?>(?<-1>.)*)[|├└])
</code>```

The (?<=(.)*) counts how many characters precede the match on the current line to measure it's horizontal position. Then the lookahead skips to the next line with .+¶, matches as many characters as we've captured in group 1 with (?>(?<-1>.)*) (to advance to the same horizontal position) and then checks whether the next character (i.e. the one below the actual match) is one of |├└. If that's the case, the match fails, and in all other cases it succeeds and the stage substitutes spaces for | and └ for ├.

This won't fix all characters in a single run, so we apply this stage repeatedly with the + option until the output stops changing.

Stage 4: Substitution

```<code>^
.¶
</code>```

All that's left is the first line, so we simply match the beginning of the string and prepend a . and a linefeed.

Body:
Retina, 88 bytes

m`^ *
$&├──
 {4}
|
T+`|├` └`(?<=(.)*).(?!.+¶(?>(?<-1>.)*)[|├└])
^
.¶

Try it online!

I suppose I could technically count this as one byte per character by swapping out some characters, reading the source as ISO 8859-1 and then finding a single-byte encoding for the output which contains ├ and └, but I can't be bothered to work out the details right now. (For the record, that would be 72 bytes.)

Explanation

Stage 1: Substitution

m`^ *
$&├──

We start by matching the indentation on each line and inserting ├──.

Stage 2: Substitution

 {4}
|

Next, we match every group of 4 spaces and replace the first with a |. Now all that needs fixing is | that go to the bottom of the output and ├ that should be └. Both of those cases can be recognised by looking at the character directly below the one we potentially want to change.

Stage 3: Transliteration

T+`|├` └`(?<=(.)*).(?!.+¶(?>(?<-1>.)*)[|├└])

The (?<=(.)*) counts how many characters precede the match on the current line to measure it's horizontal position. Then the lookahead skips to the next line with .+¶, matches as many characters as we've captured in group 1 with (?>(?<-1>.)*) (to advance to the same horizontal position) and then checks whether the next character (i.e. the one below the actual match) is one of |├└. If that's the case, the match fails, and in all other cases it succeeds and the stage substitutes spaces for | and └ for ├.

This won't fix all characters in a single run, so we apply this stage repeatedly with the + option until the output stops changing.

Stage 4: Substitution

^
.¶

All that's left is the first line, so we simply match the beginning of the string and prepend a . and a linefeed.


问:
Duplicate & switch case
The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa).

Example inputs & outputs:

```<code>Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!
</code>```

The input consists of printable ASCII symbols.

You shouldn't duplicate non-latin letters, numbers, special chars.

答:
Perl, 36 bytes (35 + -n flag)

```<code>s/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige
</code>```

(-p tag needed)

(-2 bytes thanks to @Dom Hasting)

Short explanation:

ord returns the numeric value of a char. ord(any lower case) >= 97, and ord(any upper case) <= 90).

Run with :

```<code>perl -pe 's/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige'
</code>```

Title: Duplicate & switch case

Body:
Perl, 36 bytes (35 + -n flag)

s/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige

(-p tag needed)

(-2 bytes thanks to @Dom Hasting)

Short explanation:

ord returns the numeric value of a char. ord(any lower case) >= 97, and ord(any upper case) <= 90).

Run with :

perl -pe 's/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige'


问:
The Camouflage Color Changing Chameleon Challenge
Chameleon challenges are a bad thing, apparently. Too bad, chameleons are beautiful creatures. Time for a change!

As we all know, many chameleons posses a remarkable ability to blend in with their surroundings by changing the color of their skin. Which is also the objective of this challenge.

Challenge

Imagine a square of nine pixels. Eight pixels are the surroundings. At the center is the chameleon.

Like this:

The chameleon naturally tries to blend in with its surroundings. It does so by changing its color to the average of that of the surrounding pixels. So, in this case, the chameleon would change its color to .

Objective

Given the colors of the surrounding pixels, output the color of the chameleon.

The color of the chameleon is defined as the total of all red, green and blue in the pixels ÷ 8.

Input

An array of color values for the eight surrounding pixels, starting at the top left and continuing clockwise, like this:

```<code>[[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>]]
</code>```

You may choose to receive input in a different form, as long as it consists of eight triples of decimal numbers 0-255.

If you receive input in a different form, numbers must either be of a consistent length or have a non-numeric separator between them. Triples must have a separating character unless they are 0-padded to 9 digits. (E.g. 044200255044200255044200255044200255044200255044200255044200255044200255 is valid, so are 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 and 44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255, but 4420025544200255442002554420025544200255442002554420025544200255 is not.)

Output

An array / string / etc. containing the colors of the center pixel (in decimal), like this:

```<code>[<red>,<green>,<blue>]
</code>```

In case you output something other than an array: Numbers must either be of a consistent length or have a non-numeric separator between them. (E.g. 044200255 is valid, so is 44 200 255, but 44200255 is not.)

The numbers may not contain decimal points, so e.g. 44.0 200 255.0 is invalid.

Rounding

Output must be rounded to the nearest integer. (Halves must be rounded up.) E.g., if the sum of all red is 1620, you must output 203, not 202 or 202.5.

Examples

Pictures are for illustration only. The middle pixel is the output, the surrounding pixels are the input.

Input:

```<code>[[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200]]
</code>```

Output:

```<code>[200,200,200]
</code>```

Input:

```<code>[[0,0,0],[255,255,255],[0,0,0],[255,255,255],[255,255,255],[0,0,0],[255,255,255],[0,0,0]]
</code>```

Output:

```<code>[128,128,128]
</code>```

Input:

```<code>[[0,200,200],[200,0,200],[200,200,0],[60,200,0],[200,0,200],[0,200,220],[2,200,0],[0,0,0]]
</code>```

Output:

```<code>[83,125,103]
</code>```

Input:

```<code>[[0,56,58],[65,0,200],[33,200,0],[60,33,0],[98,0,200],[0,28,220],[2,200,0],[99,0,5]]
</code>```

Output:

```<code>[45,65,85]
</code>```

Submissions can be a full program or a function. Standard I/O and loophole rules apply.

答:
J, 11 bytes

```<code>0.5<.@++/%#
</code>```

Takes the input as an 8x3 array where each row is an RGB value

Explanation

```<code>0.5<.@++/%#  Input: a
          #  Count the number of rows
       +/    Sum along the columns
         %   Divide each sum by the count to get the averages
0.5   +      Add 0.5 to each average
   <.@       Floor each value and return
</code>```

Body:
J, 11 bytes

0.5<.@++/%#

Takes the input as an 8x3 array where each row is an RGB value

Explanation

0.5<.@++/%#  Input: a
          #  Count the number of rows
       +/    Sum along the columns
         %   Divide each sum by the count to get the averages
0.5   +      Add 0.5 to each average
   <.@       Floor each value and return


答:
Haskell, 73 bytes

```<code>l=['a'..'z']
u=['A'..]
(>>= \c->c:maybe""pure(lookup c$zip l u++zip u l))
</code>```

Title: Duplicate & switch case

Body:
The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa).

Example inputs & outputs:

```<code>Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!
</code>```

The input consists of printable ASCII symbols.

You shouldn't duplicate non-latin letters, numbers, special chars.

Body:
Haskell, 73 bytes

l=['a'..'z']
u=['A'..]
(>>= \c->c:maybe""pure(lookup c$zip l u++zip u l))


答:
MATL, <s>11</s> 9 bytes

```<code>tYov"@uv!
</code>```

Try it Online

Explanation

```<code>        % Implicitly grab input as string
t       % Duplicate the input
Yo      % Swap case of all characters
v       % Vertically concatenate the original and swap-cased versions
"       % For each column (letter in the original)
  @u    % Compute the unique values (without sorting)
  v!    % Vertically concatenate with the existing output and transpose
        % Implicit end of for loop and implicit display
</code>```

Title: Duplicate & switch case

Body:
MATL, <s>11</s> 9 bytes

tYov"@uv!

Try it Online

Explanation

        % Implicitly grab input as string
t       % Duplicate the input
Yo      % Swap case of all characters
v       % Vertically concatenate the original and swap-cased versions
"       % For each column (letter in the original)
  @u    % Compute the unique values (without sorting)
  v!    % Vertically concatenate with the existing output and transpose
        % Implicit end of for loop and implicit display


问:
Holiday Gift Exchange
Another problem from our internal golfing...this one around the holidays last year.

PROBLEM

Andy, Barb, Carl, Didi, Earl, and Fran are buying gifts for each other. Draw names for a gift exchange.

Each person buys one gift and receives one gift.

Nobody buys their own gift.

Running the solution multiple times should produce different results (giver-receiver pair should not be predictable or identical from run to run).

INPUT

None.

OUTPUT

Formatted as in this example:

Andy buys for Barb

  Barb buys for Carl

  Carl buys for Didi

  Didi buys for Earl

  Earl buys for Fran

  Fran buys for Andy

答:
Golfscript: <s>72 64</s> 57 chars

```<code>"AndyBarbCarlDidiEarlFran"4/{;9rand}${.n+\' buys for '}%(
</code>```

Tests

```<code>$ golfscript codegolf-838.gs
Fran buys for Carl
Carl buys for Andy
Andy buys for Barb
Barb buys for Didi
Didi buys for Earl
Earl buys for Fran

$ golfscript codegolf-838.gs
Didi buys for Earl
Earl buys for Andy
Andy buys for Barb
Barb buys for Carl
Carl buys for Fran
Fran buys for Didi
</code>```

Thanks gnibbler for "AndyBarbCarlDidiEarlFran"4/, updated and got 7 chars less

57 chars solution is basically by Nabb :D, and also noticed that ;9rand is more random than my 6rand*

ContentLicense: CC BY-SA 2.5

Title: Holiday Gift Exchange

Body:
Golfscript: <s>72 64</s> 57 chars

"AndyBarbCarlDidiEarlFran"4/{;9rand}${.n+\' buys for '}%(

Tests

$ golfscript codegolf-838.gs
Fran buys for Carl
Carl buys for Andy
Andy buys for Barb
Barb buys for Didi
Didi buys for Earl
Earl buys for Fran

$ golfscript codegolf-838.gs
Didi buys for Earl
Earl buys for Andy
Andy buys for Barb
Barb buys for Carl
Carl buys for Fran
Fran buys for Didi

Thanks gnibbler for "AndyBarbCarlDidiEarlFran"4/, updated and got 7 chars less

57 chars solution is basically by Nabb :D, and also noticed that ;9rand is more random than my 6rand*


问:
Calculate golden ratio
Write the shortest code, in number of bytes, to display, return, or evaluate to the golden ratio (that is, the positive root of the quadratic equation: \$x^2-x-1=0\$, approximately
1.618033988749895), to at least 15 significant figures. No input will be given to your program.

Sample in Stutsk programming language:

```<code>1 100 { 1 + 1 swp / } repeat print
</code>```

答:
Mathematica 11

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

This is the irrational number itself, not an approximation of it.

Examples (first 2 examples from Mathematica documentation)

```<code>FullSimplify[GoldenRatio^4 - GoldenRatio]
FullSimplify[GoldenRatio^20 + 1/GoldenRatio^20]
FullSimplify[GoldenRatio^2 - GoldenRatio - 1]
</code>```

3 + Sqrt[5]

15127

0

Title: Calculate golden ratio

Body:
Mathematica 11

GoldenRatio

This is the irrational number itself, not an approximation of it.

Examples (first 2 examples from Mathematica documentation)

FullSimplify[GoldenRatio^4 - GoldenRatio]
FullSimplify[GoldenRatio^20 + 1/GoldenRatio^20]
FullSimplify[GoldenRatio^2 - GoldenRatio - 1]

3 + Sqrt[5]

15127

0


答:
C#, <s>82</s> 71 bytes

```<code>s=>string.Concat(s.Select(c=>c+(char.IsLetter(c)?(char)(c^32)+"":"")));
</code>```

C# lambda where the input and the output are string. Try it online.

11 bytes thanks to @Lynn trick.

Title: Duplicate & switch case

Body:
C#, <s>82</s> 71 bytes

s=>string.Concat(s.Select(c=>c+(char.IsLetter(c)?(char)(c^32)+"":"")));

C# lambda where the input and the output are string. Try it online.

11 bytes thanks to @Lynn trick.


答:
PHP 4.1, 57 bytes

This code assumes access through a web server (Apache, for example), using the default configuration.

You can pass the string by sending the key S by any means (POST, GET, COOKIE, SESSION...).

```<code><?for($i=0;$c=$S[$i++];)echo$c,ctype_alpha($c)?$c^' ':'';
</code>```

Title: Duplicate & switch case

Body:
PHP 4.1, 57 bytes

This code assumes access through a web server (Apache, for example), using the default configuration.

You can pass the string by sending the key S by any means (POST, GET, COOKIE, SESSION...).

<?for($i=0;$c=$S[$i++];)echo$c,ctype_alpha($c)?$c^' ':'';


答:
PHP, 112 bytes

```<code><?$s=str_replace('-',' ',$m=ereg_replace('.','-',$n=ereg_replace('[^A-Z0-9]','',$x)));echo"+$m+
|$n|
+$m+
$s",v;
</code>```

PHP<5.4 with register_globals=1, call php-cgi -f <filename> x="<name>";echo""

add ``` after echo" for call in web browser

Title: Generate a Stack Exchange Favicon

Body:
Do you recognize the PPCG logo?
it looks like this, when you do an ascii art of it.

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

Now, In this Code Golf, You will make a code, that makes logos for other sites, similar to the PPCG logo.

What You should do

The "Shortened" string will be the string, with all upper case letters and numbers in the input string.(Which would be PPCG when the input string is Programming Puzzles & Code Golf)

The "Box" (

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

)
should fit the Shortened string perfectly.(No bigger or smaller)

Also the v part should be exactly 1 down and 1 left to the down right +.

Then output the box which has the shortened string in it.

Example

Stack Overflow:

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

Area 51:

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

Rules

You may assume that the input contains at least one digit or upper case letter.

Standard code-golf rules apply.

Body:
PHP, 112 bytes

<?$s=str_replace('-',' ',$m=ereg_replace('.','-',$n=ereg_replace('[^A-Z0-9]','',$x)));echo"+$m+
|$n|
+$m+
$s",v;

PHP<5.4 with register_globals=1, call php-cgi -f <filename> x="<name>";echo""

add <pre> after echo" for call in web browser <scriptpath>?x=<name>;

for PHP>=5.4: replace $x with $_GET[x] (+6)

or with $argv[1] to call php <filename> "<name>";echo"" (+6)

you may want to add -d error_reporting=0 to cli options

There are times when I love that PHP accepts newlines in constant strings.

str_repeat looked like a buddy here, but costs 3 bytes

<?=(<assignments>)?"<output>".v:0 costs 1 byte

<?=(<assignments>),"
<output>",v; does neither cost nor save, but adds a leading blank line to the output


答:
Lisp - 180 179 bytes

EDIT: Formatted for further golfing.

```<code>(defun a(l)(/(apply #'+ l)(length l)))(defun r(a)(if(integerp(* a 2))(ceiling a)(round a)))(defun c(s)(mapcar(lambda(i)(r(sqrt(a(mapcar(lambda(x)(expt(nth i x)2))s)))))'(0 1 2)))
</code>```

Does it the correct way, I guess. Untested.

a is just average

r is this challenge's proper rounding, since Lisp round rounds to the nearest even integer

c does the real work, taking in input in the format
    '((R G B) (R G B) (R G B) (R G B) (R G B) (R G B) (R G B) (R G B)), and returning a '(R G B) list containg the answer.

Title: The Camouflage Color Changing Chameleon Challenge

Body:
Chameleon challenges are a bad thing, apparently. Too bad, chameleons are beautiful creatures. Time for a change!

As we all know, many chameleons posses a remarkable ability to blend in with their surroundings by changing the color of their skin. Which is also the objective of this challenge.

Challenge

Imagine a square of nine pixels. Eight pixels are the surroundings. At the center is the chameleon.

Like this:

The chameleon naturally tries to blend in with its surroundings. It does so by changing its color to the average of that of the surrounding pixels. So, in this case, the chameleon would change its color to .

Objective

Given the colors of the surrounding pixels, output the color of the chameleon.

The color of the chameleon is defined as the total of all red, green and blue in the pixels ÷ 8.

Input

An array of color values for the eight surrounding pixels, starting at the top left and continuing clockwise, like this:

```<code>[[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>],[<red>,<green>,<blue>]]
</code>```

You may choose to receive input in a different form, as long as it consists of eight triples of decimal numbers 0-255.

If you receive input in a different form, numbers must either be of a consistent length or have a non-numeric separator between them. Triples must have a separating character unless they are 0-padded to 9 digits. (E.g. 044200255044200255044200255044200255044200255044200255044200255044200255 is valid, so are 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 44 200 255 and 44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255$44?200?255, but 4420025544200255442002554420025544200255442002554420025544200255 is not.)

Output

An array / string / etc. containing the colors of the center pixel (in decimal), like this:

```<code>[<red>,<green>,<blue>]
</code>```

In case you output something other than an array: Numbers must either be of a consistent length or have a non-numeric separator between them. (E.g. 044200255 is valid, so is 44 200 255, but 44200255 is not.)

The numbers may not contain decimal points, so e.g. 44.0 200 255.0 is invalid.

Rounding

Output must be rounded to the nearest integer. (Halves must be rounded up.) E.g., if the sum of all red is 1620, you must output 203, not 202 or 202.5.

Examples

Pictures are for illustration only. The middle pixel is the output, the surrounding pixels are the input.

Input:

```<code>[[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200],[200,200,200]]
</code>```

Output:

```<code>[200,200,200]
</code>```

Input:

```<code>[[0,0,0],[255,255,255],[0,0,0],[255,255,255],[255,255,255],[0,0,0],[255,255,255],[0,0,0]]
</code>```

Output:

```<code>[128,128,128]
</code>```

Input:

```<code>[[0,200,200],[200,0,200],[200,200,0],[60,200,0],[200,0,200],[0,200,220],[2,200,0],[0,0,0]]
</code>```

Output:

```<code>[83,125,103]
</code>```

Input:

```<code>[[0,56,58],[65,0,200],[33,200,0],[60,33,0],[98,0,200],[0,28,220],[2,200,0],[99,0,5]]
</code>```

Output:

```<code>[45,65,85]
</code>```

Submissions can be a full program or a function. Standard I/O and loophole rules apply.

Body:
Lisp - 180 179 bytes

EDIT: Formatted for further golfing.

(defun a(l)(/(apply #'+ l)(length l)))(defun r(a)(if(integerp(* a 2))(ceiling a)(round a)))(defun c(s)(mapcar(lambda(i)(r(sqrt(a(mapcar(lambda(x)(expt(nth i x)2))s)))))'(0 1 2)))

Does it the correct way, I guess. Untested.

a is just average

r is this challenge's proper rounding, since Lisp round rounds to the nearest even integer

c does the real work, taking in input in the format
    '((R G B) (R G B) (R G B) (R G B) (R G B) (R G B) (R G B) (R G B)), and returning a '(R G B) list containg the answer.


问:
Do not repeat yourself
Inspired by this challenge

Given a number m, output a program that prints out the string Do not repeat yourself.

Now for the challenging part: Each program the original code prints out has to have the byte at place m*n be the same as m*n + 1 and the same as m*n + 2 .... all the way down to m*n + m - 1.

(In case you can't tell, that means it has to be blocks of identical bytes m long)

Example (that only demonstrates the repetition rule, not the output):

```<code>2

aassdd

3

mmmyyy   nnnaaammmeee   iiisssfffrrreeeddd

27

111111111111111111111111111
</code>```

##Scoring:

Your program's score is the x / (min(y, 10)^3), where y is the number of correct programs it outputs, and x is the sum of the lengths of all of the correct programs it outputs and y > 1.  Lowest score wins.

##Other notes:

Your code doesn't have to fulfill any such restrictions on letters repeating.

Your programs (that you output) cannot take input of any sort.

The input will always be a positive integer greater than 1.

Your code needs to work for at least one integer greater than 1.

答:
CJam, 3165 / 10³ = 3.165

```<code>{
"Do not repeat yourself"]sX/z_&
6)H7+G0+B8+H7+E8+G0+D8+9)C8+9)A7+E8+G0+B9+H7+K7+D8+J7+9)A8+I6+]{c}/
"Do not repeat yourself"]sZ/z_&

"Do not repeat yourself"]s3D&3D&3D&3D&3D&/z_&

"Do not repeat yourself"]s1F&1F&1F&1F&1F&1F&1F&/z_&

"Do not repeat yourself"]sB/z_&

"Do not repeat yourself"]sD/z_&

"Do not repeat yourself"]sF/z_&

"Do not repeat yourself"]sH/z_&

"Do not repeat yourself"]sJ/z_&
}`1>W<N/
e# Uncomment this line to count total length:
e# ee{~,*}%:+p [L]
ri\1$=f*
</code>```

Works for inputs 1, 2, 3, 5, 7, 11, 13, 15, 17, 19.

Total length is 3165.

The program for input 2 is from here, credits to Super Chafouin.

Example: output for 11

```<code>"""""""""""DDDDDDDDDDDooooooooooo           nnnnnnnnnnnooooooooooottttttttttt           rrrrrrrrrrreeeeeeeeeeepppppppppppeeeeeeeeeeeaaaaaaaaaaattttttttttt           yyyyyyyyyyyooooooooooouuuuuuuuuuurrrrrrrrrrrssssssssssseeeeeeeeeeelllllllllllfffffffffff"""""""""""]]]]]]]]]]]sssssssssssBBBBBBBBBBB///////////zzzzzzzzzzz___________&&&&&&&&&&&
</code>```

Explanation:

```<code>"""""""""""..."""""""""""    Push five empty strings, a long string,
                                and five more empty strings.
]]]]]]]]]]]sssssssssss       Collect them all in a list. Put that list in
                             10 more layers of list, for good measure.
                             Convert this to a string, to just get the long one.
BBBBBBBBBBB///////////       Split into chunks of size
                                11/(11/(.../(11/(11/11))))) = 11.
                             This gets us:
                                ["DDDDDDDDDDD" "ooooooooooo" ...]
zzzzzzzzzzz                  Transpose eleven times, i.e. once. We now have:
                                ["Do not..." "Do not..." ... "Do not..."]
___________&&&&&&&&&&&       Push eleven more copies, and get the unique elements.
                             This gets us:
                                ["Do not..."]
</code>```

Title: Do not repeat yourself

Body:
CJam, 3165 / 10³ = 3.165

{
"Do not repeat yourself"]sX/z_&
6)H7+G0+B8+H7+E8+G0+D8+9)C8+9)A7+E8+G0+B9+H7+K7+D8+J7+9)A8+I6+]{c}/
"Do not repeat yourself"]sZ/z_&

"Do not repeat yourself"]s3D&3D&3D&3D&3D&/z_&

"Do not repeat yourself"]s1F&1F&1F&1F&1F&1F&1F&/z_&

"Do not repeat yourself"]sB/z_&

"Do not repeat yourself"]sD/z_&

"Do not repeat yourself"]sF/z_&

"Do not repeat yourself"]sH/z_&

"Do not repeat yourself"]sJ/z_&
}`1>W<N/
e# Uncomment this line to count total length:
e# ee{~,*}%:+p [L]
ri\1$=f*

Works for inputs 1, 2, 3, 5, 7, 11, 13, 15, 17, 19.

Total length is 3165.

The program for input 2 is from here, credits to Super Chafouin.

Example: output for 11

"""""""""""DDDDDDDDDDDooooooooooo           nnnnnnnnnnnooooooooooottttttttttt           rrrrrrrrrrreeeeeeeeeeepppppppppppeeeeeeeeeeeaaaaaaaaaaattttttttttt           yyyyyyyyyyyooooooooooouuuuuuuuuuurrrrrrrrrrrssssssssssseeeeeeeeeeelllllllllllfffffffffff"""""""""""]]]]]]]]]]]sssssssssssBBBBBBBBBBB///////////zzzzzzzzzzz___________&&&&&&&&&&&

Explanation:

"""""""""""..."""""""""""    Push five empty strings, a long string,
                                and five more empty strings.
]]]]]]]]]]]sssssssssss       Collect them all in a list. Put that list in
                             10 more layers of list, for good measure.
                             Convert this to a string, to just get the long one.
BBBBBBBBBBB///////////       Split into chunks of size
                                11/(11/(.../(11/(11/11))))) = 11.
                             This gets us:
                                ["DDDDDDDDDDD" "ooooooooooo" ...]
zzzzzzzzzzz                  Transpose eleven times, i.e. once. We now have:
                                ["Do not..." "Do not..." ... "Do not..."]
___________&&&&&&&&&&&       Push eleven more copies, and get the unique elements.
                             This gets us:
                                ["Do not..."]


答:
C, 62 bytes

Function that reads from stdin and writes to stdout:

```<code>f(c){while(c=getchar())printf(isalpha(c)?"%c%c":"%c",c,c^32);}
</code>```

Title: Duplicate & switch case

Body:
C, 62 bytes

Function that reads from stdin and writes to stdout:

f(c){while(c=getchar())printf(isalpha(c)?"%c%c":"%c",c,c^32);}


问:
Rearrange a number into alphabetical order
Given a non-negative integer (n), create a function that returns n in alphabetical order, according to the literal spelling of each digit in n.

Examples:

```<code>Input: 101
>> one, zero, one
>> one, one, zero
Output: 110

Input: 31948
>> three, one, nine, four, eight
>> eight, four, nine, one, three
Output: 84913

Input: 5544
>> five, five, four, four
>> five, five, four, four
Output: 5544

Input: 1234567890
Output: 8549176320
</code>```

Note: the operations in the example are illustrative only and do not need to be included in the output. Only the alphabetically-sorted number needs to be returned.

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

Edit: the input can be taken in any desired format that best suits your language, and the output can be produced similarly by returning from the function or printing. The input will always be a natural number (including 0) and will not contain leading 0's.

Relevant OEIS entry (A057846) found by @DomHastings

答:
Python 2.7.11, 67 bytes

lambda n:''.join(sorted(list(n),key=lambda s:"9487216503"[int(s)]))
```

Takes a string as input and outputs a string.

Body:
Python 2.7.11, 67 bytes

lambda n:''.join(sorted(list(n),key=lambda s:"9487216503"[int(s)]))

Takes a string as input and outputs a string.


答:
C, 80 bytes

Takes a string containing a number in base 10 and prints to stdio:

```<code>F(char*i){for(char*p,d,*o="8549176320";*o;++o)for(p=i;d=*p++;d-*o||putchar(d));}
</code>```

Title: Rearrange a number into alphabetical order

Body:
Given a non-negative integer (n), create a function that returns n in alphabetical order, according to the literal spelling of each digit in n.

Examples:

```<code>Input: 101
>> one, zero, one
>> one, one, zero
Output: 110

Input: 31948
>> three, one, nine, four, eight
>> eight, four, nine, one, three
Output: 84913

Input: 5544
>> five, five, four, four
>> five, five, four, four
Output: 5544

Input: 1234567890
Output: 8549176320
</code>```

Note: the operations in the example are illustrative only and do not need to be included in the output. Only the alphabetically-sorted number needs to be returned.

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

Edit: the input can be taken in any desired format that best suits your language, and the output can be produced similarly by returning from the function or printing. The input will always be a natural number (including 0) and will not contain leading 0's.

Relevant OEIS entry (A057846) found by @DomHastings

Body:
C, 80 bytes

Takes a string containing a number in base 10 and prints to stdio:

F(char*i){for(char*p,d,*o="8549176320";*o;++o)for(p=i;d=*p++;d-*o||putchar(d));}


问:
Truncate consecutive character runs to n length

The challenge

Given an input string, and an integer n - truncate any runs of consecutive characters to a maximum of n length. The characters can be anything, including special characters. The function should be case sensitive, and n can range from 0 to infinity.

Example inputs/outputs:

```<code>f("aaaaaaabbbccCCCcc", 2) //"aabbccCCcc"
f("aaabbbc", 1) //"abc"
f("abcdefg", 0) //""
f("aaaaaaabccccccccCCCCCC@", 4) //"aaaabccccCCCC@"
</code>```

Scoring

The scoring is based on the number of bytes used.
Thus

```<code>function f(s,n){return s.replace(new RegExp("(.)\\1{"+n+",}","g"),function(x){return x.substr(0, n);});}
</code>```

would be 104 points.

Happy golfing!

Edit: removed language restriction, but I still would love to see javascript answers

答:
Perl 5, 50 bytes

46 bytes code + 3 for -i and 1 for -p

Takes the number to truncate to via -i.

s!(.)\1+!$&=~s/(.{$^I}).+/$1/r!ge
```

<h3>Usage</h3>

<pre class="lang-sh prettyprint-override"><code>perl -i4 -pe 's!(.)\1+!$&=~s/(.{$^I}).+/$1/r!ge' <<< 'aaaaaaabccccccccCCCCCC@'
aaaabccccCCCC@
</code>```

Body:
Perl 5, 50 bytes

46 bytes code + 3 for -i and 1 for -p

Takes the number to truncate to via -i.

s!(.)\1+!$&=~s/(.{$^I}).+/$1/r!ge

Usage

perl -i4 -pe 's!(.)\1+!$&=~s/(.{$^I}).+/$1/r!ge' <<< 'aaaaaaabccccccccCCCCCC@'
aaaabccccCCCC@


问:
Decompose string into blocks
Your program's input is a string containing whitespaces, parentheses, and other characters. The string is assumed to be parenthesed correctly, i.e. each right parenthesis matches a unique left parenthesis and vice versa : so the program is allowed to do anything on incorrectly parenthesed strings, such as )abc, (abc or )abc(.
The character interval between a left parenthesis and the corresponding right parenthesis (including the parentheses) is called a parenthesed interval.
Your program's job is to decompose the string into blocks according to the rules below, and output the result as a "vertical list", with one block per line.

Now, two characters in the string are in the same block if either

(a) there is no whitespace character strictly between them

or

(b) there is a parenthesed interval containing them both.

Also,

(c) Whitespaces not in any parenthesed interval  are mere separators
and to be discarded in the decomposition. All the other characters (including whitespaces) are retained.

For example, if the input is

```<code>I guess     () if(you say ( so)), I'll have((  ))to pack my (((things))) and go
</code>```

The output should be

```<code>I
guess
()
if(you say ( so)),
I'll
have((  ))to
pack
my
(((things)))
and
go
</code>```

Another useful test (thanks to NinjaBearMonkey) :

```<code>Hit the ( Road (Jack Don't) come ) back (no (more ) ) no more
</code>```

The output should be

```<code>Hit
the
( Road (Jack Don't) come )
back
(no (more ) )
no
more
</code>```

The shortest code in bytes wins.

答:
MATL, 22 bytes

```<code>j0G40=G41=-YsG32=*g(Yb
</code>```

Try it online!

Explanation

This uses a builtin function for splitting a string at spaces. To avoid splitting at spaces between matching parentheses, these are first detected and replaced by character 0. This is not detected as a space by the string-splitting function, but is treated as a space by the implicit display function.

```<code>j        % Take input as a string.
0        % Push 0
G40=     % True for occurrences of '('
G41=     % True for occurrences of ')'
-Ys      % Subtract and cumulative sum. Positive values correspond to characters
         % between matching parentheses
G32=     % True for occurrences of space
*g       % Multiply, convert to logical. Gives true for spaces between matching
         % parentheses
(        % Assign 0 to those positions. This replaces spaces between matching
         % parentheses by character 0
Yb       % Split at spaces, treating consecutive spaces as a single space.
         % Character 0 does not cause splitting, but is displayed as a space
</code>```

Title: Decompose string into blocks

Body:
MATL, 22 bytes

j0G40=G41=-YsG32=*g(Yb

Try it online!

Explanation

This uses a builtin function for splitting a string at spaces. To avoid splitting at spaces between matching parentheses, these are first detected and replaced by character 0. This is not detected as a space by the string-splitting function, but is treated as a space by the implicit display function.

j        % Take input as a string.
0        % Push 0
G40=     % True for occurrences of '('
G41=     % True for occurrences of ')'
-Ys      % Subtract and cumulative sum. Positive values correspond to characters
         % between matching parentheses
G32=     % True for occurrences of space
*g       % Multiply, convert to logical. Gives true for spaces between matching
         % parentheses
(        % Assign 0 to those positions. This replaces spaces between matching
         % parentheses by character 0
Yb       % Split at spaces, treating consecutive spaces as a single space.
         % Character 0 does not cause splitting, but is displayed as a space


问:
Determine the "Luck" of a string
Given a string, return that string's "luck".

A string's luck, as I completely just made up for the purpose of this challenge, is an integer, determined as so:

The base luck for a string is 1.

For each consecutive letter it shares with the word "lucky" (case insensitive), multiply the luck by 2. For instance, if your string was "lumberjack" or "smack" you'd multiply by 4. (More specifically, 2^number of consecutive characters shared.)

The shared letters have to be in the same consecutive order it appears in "lucky" but can start anywhere in the word for the same value ("luc" has the same 8* multiplier as "cky").

If the word has multiple occurrences where it shares consecutive characters with lucky, use the longest consecutive string of the characters.

For ANY letter it shares with the word "omen" subtract 2 from the luck.

It can match a character any amount of times, in any order. For instance the string "nnnnnomemenn" loses 24 luck (12 matching letters)

Example:

```<code>luck("lucky")
>>32
</code>```

2^5 (5 consecutive letters) = 32

```<code>luck("firetruck")
>>6
</code>```

2^3 - 2 (3 consecutive letters from uck, e shared with omen)

```<code>luck("memes")
>>-7
</code>```

1 - 8 (base amount, 4 shared with "omen")

This is code golf, so the answer with the fewest bytes wins.

You can input and output any way you'd like - write a function, use standard input, etc.

For functions, assume whatever data type would make sense for that language. (For example, in JavaScript, you'd be passed a String and return a Number)

Edit: You can assume any input is lowercase.

答:
Ruby, 57 bytes

```<code>b=gets.count'omen'
$.+=1while/[lucky]{#$.}/
p 2**$./2-2*b
</code>```

gets sets $. to 1 as a side effect, then we increment it until the regular expression matching $. consecutive lucky characters no longer matches.

Title: Determine the "Luck" of a string

Body:
Ruby, 57 bytes

b=gets.count'omen'
$.+=1while/[lucky]{#$.}/
p 2**$./2-2*b

gets sets $. to 1 as a side effect, then we increment it until the regular expression matching $. consecutive lucky characters no longer matches.


答:
Perl, 80 bytes (79 + -n flag)

```<code>$r=qr/[^\(\)]*(\((??{$r})\))?[^\(\)]*/;/((([^ \(]*(\($r\))?)+ *)(?{say$^N}))+/
</code>```

Run with :

```<code>perl -M5.010 -ne '$r=qr/[^\(\)]*(\((??{$r})\))?[^\(\)]*/;/((([^ \(]*(\($r\))?)+ *)(?{say$^N}))+/'
</code>```

It might not be easy to read, so here are the explanations :

```<code># The first regex ($r) is meant to match anything between two matching parenthesis
$r = qr/ [^\(\)]*         # match anything but parenthesis
         (\(               # match an opening parenthesis
           (??{$r})        # reccursive call to the same regex
          \)               # match a closing parenthesis
         )?               # the 3 previous lines are optionnal
         [^\(\)]*         # match anything but parenthesis
       /x;

# The second regex kinda split the input according to the rules
/(
    (
     ([^ \(]*           # match anything but spaces and parenthesis
      (\($r\))?          # optionnal : match an opening parenthesis, then let the
                         #   first regex match anything until the matching closing parenthesis.
     )+                 # repeat (no spaces out of parenthesis has been found yet)
     \ *               # match the space(s) that delimite the outputed lines.
    )
    (?{say$^N})       # execute the code 'say $^N' which prints the content
                      #   of the last closed group (which is the line above)
 )+                 # repeat as many times as possible
/x
</code>```

Title: Decompose string into blocks

Body:
Your program's input is a string containing whitespaces, parentheses, and other characters. The string is assumed to be parenthesed correctly, i.e. each right parenthesis matches a unique left parenthesis and vice versa : so the program is allowed to do anything on incorrectly parenthesed strings, such as )abc, (abc or )abc(.
The character interval between a left parenthesis and the corresponding right parenthesis (including the parentheses) is called a parenthesed interval.
Your program's job is to decompose the string into blocks according to the rules below, and output the result as a "vertical list", with one block per line.

Now, two characters in the string are in the same block if either

(a) there is no whitespace character strictly between them

or

(b) there is a parenthesed interval containing them both.

Also,

(c) Whitespaces not in any parenthesed interval  are mere separators
and to be discarded in the decomposition. All the other characters (including whitespaces) are retained.

For example, if the input is

```<code>I guess     () if(you say ( so)), I'll have((  ))to pack my (((things))) and go
</code>```

The output should be

```<code>I
guess
()
if(you say ( so)),
I'll
have((  ))to
pack
my
(((things)))
and
go
</code>```

Another useful test (thanks to NinjaBearMonkey) :

```<code>Hit the ( Road (Jack Don't) come ) back (no (more ) ) no more
</code>```

The output should be

```<code>Hit
the
( Road (Jack Don't) come )
back
(no (more ) )
no
more
</code>```

The shortest code in bytes wins.

Body:
Perl, 80 bytes (79 + -n flag)

$r=qr/[^\(\)]*(\((??{$r})\))?[^\(\)]*/;/((([^ \(]*(\($r\))?)+ *)(?{say$^N}))+/

Run with :

perl -M5.010 -ne '$r=qr/[^\(\)]*(\((??{$r})\))?[^\(\)]*/;/((([^ \(]*(\($r\))?)+ *)(?{say$^N}))+/'

It might not be easy to read, so here are the explanations :

# The first regex ($r) is meant to match anything between two matching parenthesis
$r = qr/ [^\(\)]*         # match anything but parenthesis
         (\(               # match an opening parenthesis
           (??{$r})        # reccursive call to the same regex
          \)               # match a closing parenthesis
         )?               # the 3 previous lines are optionnal
         [^\(\)]*         # match anything but parenthesis
       /x;

# The second regex kinda split the input according to the rules
/(
    (
     ([^ \(]*           # match anything but spaces and parenthesis
      (\($r\))?          # optionnal : match an opening parenthesis, then let the
                         #   first regex match anything until the matching closing parenthesis.
     )+                 # repeat (no spaces out of parenthesis has been found yet)
     \ *               # match the space(s) that delimite the outputed lines.
    )
    (?{say$^N})       # execute the code 'say $^N' which prints the content
                      #   of the last closed group (which is the line above)
 )+                 # repeat as many times as possible
/x


答:
JavaScript (ES6), 61 bytes

```<code>s=>s.replace(/[()]| +/g,c=>(c<`(`?n:c<`)`?++n:n--)?c:`
`,n=0)
</code>```

Works by matching all parentheses and runs of spaces, maintaining a count of the nesting depth and replacing the run with a newline if the nesting depth is zero.

Title: Decompose string into blocks

Body:
JavaScript (ES6), 61 bytes

s=>s.replace(/[()]| +/g,c=>(c<`(`?n:c<`)`?++n:n--)?c:`
`,n=0)

Works by matching all parentheses and runs of spaces, maintaining a count of the nesting depth and replacing the run with a newline if the nesting depth is zero.


答:
Retina, 31 bytes

```<code>S-_` (?=([^)]|(\()|(?<-2>.))+$)
</code>```

Try it online!

This is a standard exercise in balancing groups. We simply match all spaces from which we can reach the end of the string while passing only correctly matched parentheses (since the ones we don't want to remove are followed by an unmatched closing parenthesis), and split the input around those matches. The _ option removes empty segments in case there are several spaces in a row and the - suppresses the default behaviour to include captured substrings in the result.

Title: Decompose string into blocks

Body:
Retina, 31 bytes

S-_` (?=([^)]|(\()|(?<-2>.))+$)

Try it online!

This is a standard exercise in balancing groups. We simply match all spaces from which we can reach the end of the string while passing only correctly matched parentheses (since the ones we don't want to remove are followed by an unmatched closing parenthesis), and split the input around those matches. The _ option removes empty segments in case there are several spaces in a row and the - suppresses the default behaviour to include captured substrings in the result.


答:
Bash, <s>99</s> 74 bytes

```<code>s=$(sed s/[^A-Z0-9]//g);a=${s//?/-};echo -e "+$a+\n|$s|\n+$a+\n${s//?/ }v"
</code>```

Usage: Run the above command, type the site name, press enter and then Ctrl + D (send 'end of file').

Title: Generate a Stack Exchange Favicon

Body:
Bash, <s>99</s> 74 bytes

s=$(sed s/[^A-Z0-9]//g);a=${s//?/-};echo -e "+$a+\n|$s|\n+$a+\n${s//?/ }v"

Usage: Run the above command, type the site name, press enter and then Ctrl + D (send 'end of file').


答:
C (32-bit), 115 113 bytes

```<code>s,*P;main(q,c){char*p=P=1[P=c],*o=p;for(;c=*p++;c^=32,s+=c^9?c==8:-1,*o=s|c?c^32:10,o+=s|c||q,q=c);*o=0;puts(P);}
</code>```

Compile as 32-bit C, and pass input string as command-line argument. E.g.:

```<code>~/golf/ λ gcc -m32 -w golf.c && ./a.out "Hit the ( Road (Jack Don't) come ) back (no (more ) ) no more"
Hit
the
( Road (Jack Don't) come )
back
(no (more ) )
no
more
</code>```

Title: Decompose string into blocks

Body:
C (32-bit), 115 113 bytes

s,*P;main(q,c){char*p=P=1[P=c],*o=p;for(;c=*p++;c^=32,s+=c^9?c==8:-1,*o=s|c?c^32:10,o+=s|c||q,q=c);*o=0;puts(P);}

Compile as 32-bit C, and pass input string as command-line argument. E.g.:

~/golf/ λ gcc -m32 -w golf.c && ./a.out "Hit the ( Road (Jack Don't) come ) back (no (more ) ) no more"
Hit
the
( Road (Jack Don't) come )
back
(no (more ) )
no
more


问:
Cannonball Conundrum
Your task is to, with an input number p, find the smallest positive cannonball number of order p that is NOT 1.

Definition

A cannonball number (of order p) is a number which is both:

An p-gonal number (See this page).

and an p-gonal pyramid number.

The nth p-gonal pyramid number is the sum of the 1st to nth p-gonal numbers.

(e.g. 4th square pyramid number = 1 + 4 + 9 + 16 = 30)

The picture below represents the 4th square pyramid number, as a square pyramid.

For more info, visit this link.

The cannonball number of order 3, for example, is 10, because it is:

The fourth triangle number (1 + 2 + 3 + 4 = 10)

and the third triangular pyramid number. (1 + 3 + 6 = 10)

Formulas

NOTE: If you can find (or make) more useful formulae than my ones here, please post it here (or message me on the question chat thing).

If you're interested, the formula for the nth p-gonal number is:

And the nth p-gonal pyramid number is:

Specs

p is guaranteed to be larger than 2.

The program must check values for a solution for p up to (and including) 2^16. Your program may do anything if no solutions are found for p.

Only positive indices for n.

Test cases

3 outputs 10 (4th triangle number, 3rd triangle pyramid number)

4 outputs 4900 (70th square number, 24th square pyramid number)

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

Note: If you do post a solution, please include a description of how the code works.

Should I start a bounty for a solution which is better and doesn't use my formulae?

答:
Python 3, <s>129</s> 127 bytes

```<code>def f(p):
 x=2
 while 1:
  for i in range(x*x):
   if i//x*((p-2)*i//x+4-p)/2==i%x*(i%x+1)*((p-2)*i%x+5-p)/6==x:return x
  x+=1
</code>```

A function that takes input via argument and returns the output.

This is an extremely naïve brute force, and takes a very long time for even moderately large p; the execution time will be ridiculous for anything approaching the given maximum for p of 2^16, but there is no reason why the program would not work, given sufficient time.

There are probably far shorter and faster ways of doing this, but I thought it would be good to post something to get this started off.

How it works

The return value x is initialised to 2, and then the program simply loops over all the p-gonal and p-gonal pyramidal numbers up to order x. If the current p-gonal and p-gonal pyramidal numbers, calculated using the formulas, are equal to each other and to x, then x must be the relevant cannonball number and this is returned. Else, x is incremented, and the program tries again for the new value of x.

In terms of golfing, a Cartesian product is used to collapse the two for-loops for the p-gonal and p-gonal pyramidal numbers into a single loop, and the formulas were factorised further to save a few bytes.

Title: Cannonball Conundrum

Body:
Python 3, <s>129</s> 127 bytes

def f(p):
 x=2
 while 1:
  for i in range(x*x):
   if i//x*((p-2)*i//x+4-p)/2==i%x*(i%x+1)*((p-2)*i%x+5-p)/6==x:return x
  x+=1

A function that takes input via argument and returns the output.

This is an extremely naïve brute force, and takes a very long time for even moderately large p; the execution time will be ridiculous for anything approaching the given maximum for p of 2^16, but there is no reason why the program would not work, given sufficient time.

There are probably far shorter and faster ways of doing this, but I thought it would be good to post something to get this started off.

How it works

The return value x is initialised to 2, and then the program simply loops over all the p-gonal and p-gonal pyramidal numbers up to order x. If the current p-gonal and p-gonal pyramidal numbers, calculated using the formulas, are equal to each other and to x, then x must be the relevant cannonball number and this is returned. Else, x is incremented, and the program tries again for the new value of x.

In terms of golfing, a Cartesian product is used to collapse the two for-loops for the p-gonal and p-gonal pyramidal numbers into a single loop, and the formulas were factorised further to save a few bytes.


问:
Guess the language

Introduction

This site is rapidly building up a huge dataset of code snippets, so let's do something with it!

Here's a data file. It contains 9,066 unique language+snippet pairs for 113 languages, all taken from this site. The format is tab-separated (language-TAB-snippet), with all newlines in the snippets replaced with <LF>, and all tabs replaced with 4 spaces. There are at least 5 snippets for each language.

[update: I've made a minor change to the data file to merge some Python & RegExp versions I missed before - the link above has been updated]

Challenge

Write a program or function which takes a code snippet and outputs the language it is written in (see below for details). The total size of your source + any data you require must be 300 bytes or less, and your program must output the correct language when given its own source code. Highest accuracy (most correct answers on the dataset above) wins.

Rules

The total size of your source code, resources, and any required compilation / runtime flags must not exceed 300 bytes.

Your answer will be tested against the dataset above; it will be given one of the "Snippet" values as input and its output will be compared against the "correct" output according to the dataset. This will be repeated for all entries in the dataset and the final number of correct answers is your score.

You can choose the input encoding - I'll assume UTF-8, so if you need another encoding specify it in your answer.

You don't need to use the <LF> replacement for newlines; if your entry expects to receive newlines as literal newlines (char 10), specify it in your answer.

Your entry must output the language it thinks the input snippet is written in. To avoid the need to compress lots of language strings, I'll allow mappings (If you want to output 3 for "Java", that's fine); just note the mappings in your answer.

You can only have 1 output mapping for each language (i.e. if 3 means "Java", you can't also have 4 meaning "Java").

When given its own source code, your program must produce the correct answer (must output the language it is written in).

You don't need to support all languages in the dataset, and you can support extra languages if you want to (e.g. if your entry isn't in one of the languages in the dataset).

Your program must be deterministic (providing the same input twice must produce the same output).

Tie-Breaking

Ties will be decided by reducing the dataset until one entry wins. The dataset will be reduced by removing all snippets for the most popular language (i.e. ties are broken by accuracy on rarer languages). For example, if A and B score 70% on the full dataset, all Python snippets will be removed. If A and B now both score 60%, CJam will be removed. If A now scores 50% but B scores 55%, B is the winner.

If 100% accuracy is achieved, ties will be decided using a second (blind) dataset containing more samples for the same languages.

Example 1

The Python script:

```<code>print("python")
</code>```

This script successfully produces "python" when given its own source code, so it is valid. On the dataset, it scores 1008/9066 = 11.1%

Example 2

The JavaScript function:

```<code>function f(s){return /function/.test(s)?1:2}
</code>```

With the mappings 1 → javascript, 2 → python. Again it successfully produces 1 ("javascript") for its own source, and on the dataset it scores 1092/9066 = 12.0%

Where did the data come from?

I created an SEDE query to pull samples from [code-golf] challenges on this site. From the resulting 10,000 answers, I used a hacked-together python script to find the code & language name for each, then filtered out any language with less than 5 examples. The data isn't 100% clean (I know there are some non-code snippets it pulled), but should be good enough.

Inspired by this challenge from earlier in the year: Who said that? 2016 Presidential election

Also partly related to What's the Language?

答:
Python 3, 271 278 bytes, 25.049636% matched (v2, unverified)

```<code>def f(c):
 try:compile(c,'','exec');return 5
 except:
  for j in range(9):
   if any(l in c for l in [['echo'],['require'],['Main','string'],['document','alert','var ','function'],['String'],['def ','lambda','print '],['main','int','char'],['+++','<<<'],[]][j]):break
 return j
</code>```

map:

```<code>0 = bash
1 = ruby
2 = c#
3 = javascript
4 = java
5 = python
6 = c
7 = brainf*
8 = cjam
</code>```

much better golfed (probably still not great), finally broke the 25% barrier! Inputs have <LF> replaced with newline (\n)

Title: Guess the language

Body:
Python 3, 271 278 bytes, 25.049636% matched (v2, unverified)

def f(c):
 try:compile(c,'','exec');return 5
 except:
  for j in range(9):
   if any(l in c for l in [['echo'],['require'],['Main','string'],['document','alert','var ','function'],['String'],['def ','lambda','print '],['main','int','char'],['+++','<<<'],[]][j]):break
 return j

map:

0 = bash
1 = ruby
2 = c#
3 = javascript
4 = java
5 = python
6 = c
7 = brainf*
8 = cjam

much better golfed (probably still not great), finally broke the 25% barrier! Inputs have <LF> replaced with newline (\n)


问:
Code golf for the lazy
Your goal in this code golf is to take two strings, language and code (if the golfed code you wrote for this is multiline, then this variable would be multiline.), and one integer, bytes. They represent the variables for a programming language, number of bytes it takes, and the code itself.

After that, you are going to format it like a code golfer does it.

The output variable is a multiline string called answer.

You can use multiline strings on:

C++

Python

Perl

JavaScript

If you search Stack Overflow, you should be able to find more programming languages that support it.

Here is a template of the output markdown. The code variable is in a code block, and there is a second-level header.

```<code>## {language}, {bytes} bytes

     {code}
</code>```

Here is what the output would look like when pasted into a Markdown parser.

{language}, {bytes} bytes

```<code>    {code}
</code>```

Variables are assumed to be filled out already as the language you coded your code golf entry in, the number of bytes it takes, and the actual code for it.

Here is another example of the output as code, this time with variables filled out:

```<code>## JavaScript, 1337 bytes

document.getElementById("foo").innerHTML = bar;
</code>```

Here is the version as a blockquote:

JavaScript, 1337 bytes

```<code>    document.getElementById("foo").innerHTML = bar;
</code>```

Bytes can be taken off from your code if you use a way to set the text of a
 element in HTML by the id result, like the following JavaScript code:

```<code>document.getElementById("result").innerHTML = answer;
</code>```

Make sure to also include the

 in the HTML section of JSFiddle for this to work.

Scoring

Like all code-golf questions, the code that uses the least amount of bytes is the best.

答:
Java, 70 bytes

```<code>String A(String[]b){return"## "+b[0]+", "+b[1]+" bytes\n\n    "+b[2];}
</code>```

Assumes b[0] is the language name, b[1] is the byte count, and b[2] is the code.

Making it compilable costs 9 bytes, resulting in a 79-byte non-standalone program:

```<code>class a{String A(String[]b){return"## "+b[0]+", "+b[1]+" bytes\n\n    "+b[2];}}
</code>```

The equivalent monolithic program is 103 bytes long:

```<code>interface a{static void main(String[]A){System.out.print("## "+A[0]+", "+A[1]+" bytes\n\n    "+A[2]);}}
</code>```

The monolithic one works with command line arguments, assuming these just like the non-standalone program:

First argument is the language name

Second argument is the byte count

Third argument is the code

Java (lambda expression), 56 48 bytes

```<code>(b)->"## "+b[0]+", "+b[1]+" bytes\n\n    "+b[2];
</code>```

This is a java.util.function.Function<String[], String>.

None of these programs/functions handle multiline strings. To do so, simply replace b[2] and A[2] with b[2].replace("\n","\n    ") and A[2].replace("\n","\n    ") - doing so adds 23 bytes.

Title: Code golf for the lazy

Body:
Java, 70 bytes

String A(String[]b){return"## "+b[0]+", "+b[1]+" bytes\n\n    "+b[2];}

Assumes b[0] is the language name, b[1] is the byte count, and b[2] is the code.

Making it compilable costs 9 bytes, resulting in a 79-byte non-standalone program:

class a{String A(String[]b){return"## "+b[0]+", "+b[1]+" bytes\n\n    "+b[2];}}

The equivalent monolithic program is 103 bytes long:

interface a{static void main(String[]A){System.out.print("## "+A[0]+", "+A[1]+" bytes\n\n    "+A[2]);}}

The monolithic one works with command line arguments, assuming these just like the non-standalone program:

First argument is the language name

Second argument is the byte count

Third argument is the code

Java (lambda expression), 56 48 bytes

(b)->"## "+b[0]+", "+b[1]+" bytes\n\n    "+b[2];

This is a java.util.function.Function<String[], String>.

None of these programs/functions handle multiline strings. To do so, simply replace b[2] and A[2] with b[2].replace("\n","\n    ") and A[2].replace("\n","\n    ") - doing so adds 23 bytes.


答:
JavaScript (ES6), 56 bytes

```<code>(l,b,c)=>`## ${l}, ${b} bytes

`+c.replace(/^/gm,`    `)
</code>```

Also, for laughs, here is an answer that formats itself for me:

JavaScript (ES6), 68 bytes

```<code>f=_=>`## JavaScript (ES6), ${`${f}`.length+3} bytes\n\n    f=${f};`;
</code>```

Print the result of f().

Title: Code golf for the lazy

Body:
Your goal in this code golf is to take two strings, language and code (if the golfed code you wrote for this is multiline, then this variable would be multiline.), and one integer, bytes. They represent the variables for a programming language, number of bytes it takes, and the code itself.

After that, you are going to format it like a code golfer does it.

The output variable is a multiline string called answer.

You can use multiline strings on:

C++

Python

Perl

JavaScript

If you search Stack Overflow, you should be able to find more programming languages that support it.

Here is a template of the output markdown. The code variable is in a code block, and there is a second-level header.

```<code>## {language}, {bytes} bytes

     {code}
</code>```

Here is what the output would look like when pasted into a Markdown parser.

{language}, {bytes} bytes

```<code>    {code}
</code>```

Variables are assumed to be filled out already as the language you coded your code golf entry in, the number of bytes it takes, and the actual code for it.

Here is another example of the output as code, this time with variables filled out:

```<code>## JavaScript, 1337 bytes

document.getElementById("foo").innerHTML = bar;
</code>```

Here is the version as a blockquote:

JavaScript, 1337 bytes

```<code>    document.getElementById("foo").innerHTML = bar;
</code>```

Bytes can be taken off from your code if you use a way to set the text of a
 element in HTML by the id result, like the following JavaScript code:

```<code>document.getElementById("result").innerHTML = answer;
</code>```

Make sure to also include the

 in the HTML section of JSFiddle for this to work.

Scoring

Like all code-golf questions, the code that uses the least amount of bytes is the best.

Body:
JavaScript (ES6), 56 bytes

(l,b,c)=>`## ${l}, ${b} bytes

`+c.replace(/^/gm,`    `)

Also, for laughs, here is an answer that formats itself for me:

JavaScript (ES6), 68 bytes

f=_=>`## JavaScript (ES6), ${`${f}`.length+3} bytes\n\n    f=${f};`;

Print the result of f().


答:
V, 24  bytes

Note that there is a trailing space at the end.

<s>This program makes the assumption that {code} will not be on multiple lines.</s>

Op has clarified, "code" may be a multiline string. This 24 byte version works:

```<code>2é#á $á,JA bytes
vGî4é
</code>```

Since this contains an unprintable character, here is the readable version:

```<code>2é#á $á,JA bytes
<esc>vGî4é<space>
</code>```

Where <esc> is the literal escape character, e.g. 0x1B.

Title: Code golf for the lazy

Body:
V, 24  bytes

Note that there is a trailing space at the end.

<s>This program makes the assumption that {code} will not be on multiple lines.</s>

Op has clarified, "code" may be a multiline string. This 24 byte version works:

2é#á $á,JA bytes
vGî4é

Since this contains an unprintable character, here is the readable version:

2é#á $á,JA bytes
<esc>vGî4é<space>

Where <esc> is the literal escape character, e.g. 0x1B.


答:
C#, <s>40</s> 38 bytes

```<code>(a,b,c)=>$"## {a}, {b} bytes\n\n\t"+c;
</code>```

C# lambda where inputs and output are strings.

C#, 59 bytes

```<code>(a,b,c)=>$"## {a}, {b} bytes\n\n\t"+c.Replace("\n","\n\t");
</code>```

With handling of a multiline answer.

C#, 71 bytes

The 38 bytes solution which print itself

```<code>()=>$"## C#, 38 bytes\n\n\t"+@"(a,b,c)=>$""## {a}, {b} bytes

\t""+c;";
</code>```

Try them online

Title: Code golf for the lazy

Body:
C#, <s>40</s> 38 bytes

(a,b,c)=>$"## {a}, {b} bytes\n\n\t"+c;

C# lambda where inputs and output are strings.

C#, 59 bytes

(a,b,c)=>$"## {a}, {b} bytes\n\n\t"+c.Replace("\n","\n\t");

With handling of a multiline answer.

C#, 71 bytes

The 38 bytes solution which print itself

()=>$"## C#, 38 bytes\n\n\t"+@"(a,b,c)=>$""## {a}, {b} bytes

\t""+c;";

Try them online


问:
Code Golf Bingo!
You are given a Bingo board and a list of calls.  You must print BINGO! as soon as your board wins the game.

Bingo boards look like this:

They will be specified like this:

```<code>14 29 38 52 74
4 18 33 46 62
7 16 * 60 71
9 27 44 51 67
12 23 35 47 73
</code>```

Immediately following the board will be calls, like this:

```<code>B7
I29
G60
G51
O71
I23
I16
N38
</code>```

You must echo the calls out to standard output until just after the call that makes you win (get a row, column, or 5-long diagonal all filled), then print BINGO!.

For the above example, print:

```<code>B7
I29
G60
G51
O71
I23
I16
BINGO!
</code>```

Rules

Standard code-golf rules, shortest code wins.

Details

There will always be enough calls to guarantee you a Bingo.  There will be no duplicate numbers on the board, and no duplicate calls.  Boards will always have correctly matched numbers and letters (the B column contains only 1-15, the I column contains only 16-30, and so on), as will calls.  The one and only free space will always be in the middle, marked with * instead of a number.  Consuming and discarding calls from standard input after the winning call is allowed, but not required.

Make your own test cases!

答:
Ruby 1.9 (194, 130)

This probably isn't the most sensible way to check for empty columns, but it was the first thing I thought to try!  In particular, that #transpose costs a lot.

Either a blank line between the board and the numbers or fixed width fields when declaring the board would save a lot of characters.  I couldn't think of a really nice way to read exactly 5 lines.

b=(R=0..4).map{gets}.join.scan /\d+|\*/
loop{gets
puts$_
~/\d+/
(e=b.index$&)&&b[e]=?*
R.map{|y|$><<:BINGO!&&exit if R.map{|x|[b[5*x+y],b[5*y+x],b[y<1?x*6:4*x+4]]}.transpose.any?{|a|a==[?*]*5}}}
```

<p><strong>EDIT:</strong> 130 character solution using the regular expression technique from mob's perl answer:</p>

```b=(0..4).map{gets}*'~ ~ '
loop{gets
puts$_
~/\d+/
b[/\b#$&\b/]=?*
7.times{|i|$><<:BINGO!&&exit if b=~/(\*\s(\S+\s){#{i}}){4}\*/m}}
```

Title: Code Golf Bingo!

Body:
Ruby 1.9 (194, 130)

This probably isn't the most sensible way to check for empty columns, but it was the first thing I thought to try!  In particular, that #transpose costs a lot.

Either a blank line between the board and the numbers or fixed width fields when declaring the board would save a lot of characters.  I couldn't think of a really nice way to read exactly 5 lines.

b=(R=0..4).map{gets}.join.scan /\d+|\*/
loop{gets
puts$_
~/\d+/
(e=b.index$&)&&b[e]=?*
R.map{|y|$><<:BINGO!&&exit if R.map{|x|[b[5*x+y],b[5*y+x],b[y<1?x*6:4*x+4]]}.transpose.any?{|a|a==[?*]*5}}}

EDIT: 130 character solution using the regular expression technique from mob's perl answer:

b=(0..4).map{gets}*'~ ~ '
loop{gets
puts$_
~/\d+/
b[/\b#$&\b/]=?*
7.times{|i|$><<:BINGO!&&exit if b=~/(\*\s(\S+\s){#{i}}){4}\*/m}}


问:
Lithp Tranthlator
My friend made a lisp translator the other day, that is to say it took a string and converted s=>th and S=>Th. It was quite long and I thought that it could be golfed.

So the task is to make a program/function that takes an input string, translates it in to lisp and outputs the string

Test case

```<code>Sam and Sally like Sheep        Tham and Thally like Thheep
Sally likes sausages            Thally liketh thauthageth
Sally sells seashells           Thally thellth theathhellth
</code>```

Note that it doesn't matter that h gets repeated all the time

This is code golf so shortest answer wins

答:
Javathcript, 27 Byteth

```<code>b=a=>a.replace(/s/gi,'th');
</code>```

Although it is case insensitive it is the smallest JS version so far :)

Title: Lithp Tranthlator

Body:
Javathcript, 27 Byteth

b=a=>a.replace(/s/gi,'th');

Although it is case insensitive it is the smallest JS version so far :)


答:
Python 3.5, <s>40</s> 33 bytes:

(-7 bytes thanks to some clarification from Mego)

```<code>lambda*f:'## %s, %s bytes\n\n\t%s'%f
</code>```

An anonymous lambda function that takes inputs as positional arguments in the format <function name>(String, Number, String) and outputs a multiline string.

Try It Online! (Ideone)

Title: Code golf for the lazy

Body:
Python 3.5, <s>40</s> 33 bytes:

(-7 bytes thanks to some clarification from Mego)

lambda*f:'## %s, %s bytes\n\n\t%s'%f

An anonymous lambda function that takes inputs as positional arguments in the format <function name>(String, Number, String) and outputs a multiline string.

Try It Online! (Ideone)


答:
Mathematica, 40 bytes

```<code>Print["## ",#,", ",#2,"bytes

    ",#3]&
</code>```

Anonymous function. Takes the language, byte count, and program as input and prints the body to STDOUT.

Title: Code golf for the lazy

Body:
Mathematica, 40 bytes

Print["## ",#,", ",#2,"bytes

    ",#3]&

Anonymous function. Takes the language, byte count, and program as input and prints the body to STDOUT.


答:
Jolf, <s>24</s> 22 bytes

```<code>"## ¦i, ¦j Ξ/u3

    ¦
</code>```

Not much to explain here. ¦ means interpolated input.

Try it here! Output for the input in the link is:

```<code>## Jolf, 24 bytes

    some filler code I think
</code>```

Input is as:

```<code>name

number

"code"
</code>```

Title: Code golf for the lazy

Body:
Jolf, <s>24</s> 22 bytes

"## ¦i, ¦j Ξ/u3

    ¦

Not much to explain here. ¦ means interpolated input.

Try it here! Output for the input in the link is:

## Jolf, 24 bytes

    some filler code I think

Input is as:

name

number

"code"


答:
Gammaplex, 2080 / 10³ = 2.08

```<code>X"Y#gmftsvp"2v
Ev2"!sfqfbu!z<
R>upo!pE#YYs"v
>1-swSs>swrsvS
?  v +=^?w-1<"
^ws<J0s11X"0F<
</code>```

Note that it firstly displays a 0 when it is run. That's just the Gammaplex way of echoing the number you are going to input. And it prints the newline as ◙, which shares the same code point with a newline in CP437.

Gammaplex renders the string in a window which couldn't be copied. So here is an equivalent CJam program to make testing easier:

```<code>"/
ERrXX\"Do not repeat yourself\"X"qie*
</code>```

Example for m=3:

```<code>///

EEERRRrrrXXXXXX"""DDDooo   nnnooottt   rrreeepppeeeaaattt   yyyooouuurrrssseeelllfff"""XXX
</code>```

In Gammaplex, only the position of the first newline is used to determine the line length. So it is the same as the following:

```<code>///
EEE
RRR
rrr
XXX
XXX
"""
DDD
ooo

nnn
ooo
ttt

rrr
eee
ppp
eee
aaa
ttt

yyy
ooo
uuu
rrr
sss
eee
lll
fff
"""
XXX
</code>```

Then it works in the obvious way as a 2D language.

Title: Do not repeat yourself

Body:
Inspired by this challenge

Given a number m, output a program that prints out the string Do not repeat yourself.

Now for the challenging part: Each program the original code prints out has to have the byte at place m*n be the same as m*n + 1 and the same as m*n + 2 .... all the way down to m*n + m - 1.

(In case you can't tell, that means it has to be blocks of identical bytes m long)

Example (that only demonstrates the repetition rule, not the output):

```<code>2

aassdd

3

mmmyyy   nnnaaammmeee   iiisssfffrrreeeddd

27

111111111111111111111111111
</code>```

##Scoring:

Your program's score is the x / (min(y, 10)^3), where y is the number of correct programs it outputs, and x is the sum of the lengths of all of the correct programs it outputs and y > 1.  Lowest score wins.

##Other notes:

Your code doesn't have to fulfill any such restrictions on letters repeating.

Your programs (that you output) cannot take input of any sort.

The input will always be a positive integer greater than 1.

Your code needs to work for at least one integer greater than 1.

Body:
Gammaplex, 2080 / 10³ = 2.08

X"Y#gmftsvp"2v
Ev2"!sfqfbu!z<
R>upo!pE#YYs"v
>1-swSs>swrsvS
?  v +=^?w-1<"
^ws<J0s11X"0F<

Note that it firstly displays a 0 when it is run. That's just the Gammaplex way of echoing the number you are going to input. And it prints the newline as ◙, which shares the same code point with a newline in CP437.

Gammaplex renders the string in a window which couldn't be copied. So here is an equivalent CJam program to make testing easier:

"/
ERrXX\"Do not repeat yourself\"X"qie*

Example for m=3:

///

EEERRRrrrXXXXXX"""DDDooo   nnnooottt   rrreeepppeeeaaattt   yyyooouuurrrssseeelllfff"""XXX

In Gammaplex, only the position of the first newline is used to determine the line length. So it is the same as the following:

///
EEE
RRR
rrr
XXX
XXX
"""
DDD
ooo

nnn
ooo
ttt

rrr
eee
ppp
eee
aaa
ttt

yyy
ooo
uuu
rrr
sss
eee
lll
fff
"""
XXX

Then it works in the obvious way as a 2D language.


答:
Common Lisp, 57 bytes

```<code>(lambda(L b c)(format()"## ~A, ~A bytes~%~%    ~A"L b c))
</code>```

Also, for fun, here below is a snippet of code which prints a header for itself.

Common Lisp, 146 bytes

```<code>#1=(PROGN
(SETF *PRINT-CIRCLE* T)
(LET ((S (FORMAT NIL "~S" '#1#)))
  (FORMAT NIL "## Common Lisp, ~A bytes~%~%    ~A" (LENGTH S) S)))
</code>```

Title: Code golf for the lazy

Body:
Common Lisp, 57 bytes

(lambda(L b c)(format()"## ~A, ~A bytes~%~%    ~A"L b c))

Also, for fun, here below is a snippet of code which prints a header for itself.

Common Lisp, 146 bytes

#1=(PROGN
(SETF *PRINT-CIRCLE* T)
(LET ((S (FORMAT NIL "~S" '#1#)))
  (FORMAT NIL "## Common Lisp, ~A bytes~%~%    ~A" (LENGTH S) S)))


Title: Decompose string into blocks

Body:
Your program's input is a string containing whitespaces, parentheses, and other characters. The string is assumed to be parenthesed correctly, i.e. each right parenthesis matches a unique left parenthesis and vice versa : so the program is allowed to do anything on incorrectly parenthesed strings, such as )abc, (abc or )abc(.
The character interval between a left parenthesis and the corresponding right parenthesis (including the parentheses) is called a parenthesed interval.
Your program's job is to decompose the string into blocks according to the rules below, and output the result as a "vertical list", with one block per line.

Now, two characters in the string are in the same block if either

(a) there is no whitespace character strictly between them

or

(b) there is a parenthesed interval containing them both.

Also,

(c) Whitespaces not in any parenthesed interval  are mere separators
and to be discarded in the decomposition. All the other characters (including whitespaces) are retained.

For example, if the input is

```<code>I guess     () if(you say ( so)), I'll have((  ))to pack my (((things))) and go
</code>```

The output should be

```<code>I
guess
()
if(you say ( so)),
I'll
have((  ))to
pack
my
(((things)))
and
go
</code>```

Another useful test (thanks to NinjaBearMonkey) :

```<code>Hit the ( Road (Jack Don't) come ) back (no (more ) ) no more
</code>```

The output should be

```<code>Hit
the
( Road (Jack Don't) come )
back
(no (more ) )
no
more
</code>```

The shortest code in bytes wins.

Body:
Retina, 30 bytes

!`(\(()|(?<-2>)\)|(?(2).|\S))+

1 byte shorter...

Try it here.