问:
No Quine Built In? No Problem!

Are you tired of languages with built in quining techniques?

Your challenge, should you choose to accept it, is to add a built-in quine feature to the language of your choice.

Task

Given some programming language X, you should define

A language X′ that is a subset of X.

A quine command string Q.  (This is a string of your choice; it need not literally be “Q”.)

Now you have a new language Y, consisting of programs that are in X′ except that they may also contain copies of Q as if Q were a new built-in statement or function.  Your job is to implement this language Y, by writing

A compiler, written in X′, producing an output program B in X for each input program A in Y.

When B is run, it should behave like A would if all its copies of Q had been replaced with a statement in X that prints the source code of B.

You’ve therefore created a language Y that contains a quining builtin Q.

Rules

Your chosen language subset X′ must still satisfy the definition of a programming language.

The output programs B of your compiler must be proper quines.  You may not use quining builtins that may already be in X.

This is code golf, so the shortest code in bytes (defined as your language's default native encoding) wins.

答:
Java "only" 498 Bytes

The following java program takes in input as command line arguments.

```<code>class Q{
public static void main(String[]a){
System.out.println(a[0]);System.out.print("static char[]s={");a[2]+="}static void q(){System.out.print(\""+a[0]+"\\n\");System.out.print(\"static char[]s={\");for(char c:s)System.out.print((int) c+\",\");System.out.print(\"\\b};\\n"+a[1]+"\\n\");for(char c:s)System.out.print(c);System.out.print(\"\\n}\");}";for(char c:a[2].toCharArray())System.out.print((int) c+",");System.out.println("\b};");System.out.println(a[1]);System.out.print(a[2]+"\n}");
}}
</code>```

In this case my language "X" is (a subset of) Java, and my Quine Command string "Q" is q();for each instance of q(); the output program will print its source. Input is restricted to only four lines, and any more or less results in undefined behavior. My golfed program technically follows these same restrictions. So my subset is programs that fit on four lines as shown and do not have a function called q or use any variable named s.

Sample Input

```<code>class sampleInput{//class def on this line
public static void main(String[]argument){//method header here and optional code although avoid putting code here
System.out.println("Hello World Of Quines");q();System.out.println("\n------------");q();/*Avoid comments on this line unless you use this format YOU MUST! put two braces on the next line*/
}}
</code>```

Sample Output

```<code>class sampleInput{//class def on this line
static char[]s={83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,108,110,40,34,72,101,108,108,111,32,87,111,114,108,100,32,79,102,32,81,117,105,110,101,115,34,41,59,113,40,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,108,110,40,34,92,110,45,45,45,45,45,45,45,45,45,45,45,45,34,41,59,113,40,41,59,47,42,65,118,111,105,100,32,99,111,109,109,101,110,116,115,32,111,110,32,116,104,105,115,32,108,105,110,101,32,117,110,108,101,115,115,32,121,111,117,32,117,115,101,32,116,104,105,115,32,102,111,114,109,97,116,32,112,117,116,32,116,119,111,32,98,114,97,99,101,115,32,111,110,32,116,104,101,32,110,101,120,116,32,108,105,110,101,42,47,125,115,116,97,116,105,99,32,118,111,105,100,32,113,40,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,99,108,97,115,115,32,115,97,109,112,108,101,73,110,112,117,116,123,47,47,99,108,97,115,115,32,100,101,102,32,111,110,32,116,104,105,115,32,108,105,110,101,92,110,34,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,115,116,97,116,105,99,32,99,104,97,114,91,93,115,61,123,34,41,59,102,111,114,40,99,104,97,114,32,99,58,115,41,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,40,105,110,116,41,32,99,43,34,44,34,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,92,98,125,59,92,110,112,117,98,108,105,99,32,115,116,97,116,105,99,32,118,111,105,100,32,109,97,105,110,40,83,116,114,105,110,103,91,93,97,114,103,117,109,101,110,116,41,123,47,47,109,101,116,104,111,100,32,104,101,97,100,101,114,32,104,101,114,101,32,97,110,100,32,111,112,116,105,111,110,97,108,32,99,111,100,101,32,97,108,116,104,111,117,103,104,32,97,118,111,105,100,32,112,117,116,116,105,110,103,32,99,111,100,101,32,104,101,114,101,92,110,34,41,59,102,111,114,40,99,104,97,114,32,99,58,115,41,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,99,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,92,110,125,34,41,59,125};
public static void main(String[]argument){//method header here and optional code although avoid putting code here
System.out.println("Hello World Of Quines");q();System.out.println("\n------------");q();/*Avoid comments on this line unless you use this format put two braces on the next line*/}static void q(){System.out.print("class sampleInput{//class def on this line\n");System.out.print("static char[]s={");for(char c:s)System.out.print((int) c+",");System.out.print("\b};\npublic static void main(String[]argument){//method header here and optional code although avoid putting code here\n");for(char c:s)System.out.print(c);System.out.print("\n}");}
}
</code>```

Title: No Quine Built In? No Problem!

Body:
Java "only" 498 Bytes

The following java program takes in input as command line arguments.

class Q{
public static void main(String[]a){
System.out.println(a[0]);System.out.print("static char[]s={");a[2]+="}static void q(){System.out.print(\""+a[0]+"\\n\");System.out.print(\"static char[]s={\");for(char c:s)System.out.print((int) c+\",\");System.out.print(\"\\b};\\n"+a[1]+"\\n\");for(char c:s)System.out.print(c);System.out.print(\"\\n}\");}";for(char c:a[2].toCharArray())System.out.print((int) c+",");System.out.println("\b};");System.out.println(a[1]);System.out.print(a[2]+"\n}");
}}

In this case my language "X" is (a subset of) Java, and my Quine Command string "Q" is q();for each instance of q(); the output program will print its source. Input is restricted to only four lines, and any more or less results in undefined behavior. My golfed program technically follows these same restrictions. So my subset is programs that fit on four lines as shown and do not have a function called q or use any variable named s.

Sample Input

class sampleInput{//class def on this line
public static void main(String[]argument){//method header here and optional code although avoid putting code here
System.out.println("Hello World Of Quines");q();System.out.println("\n------------");q();/*Avoid comments on this line unless you use this format YOU MUST! put two braces on the next line*/
}}

Sample Output

class sampleInput{//class def on this line
static char[]s={83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,108,110,40,34,72,101,108,108,111,32,87,111,114,108,100,32,79,102,32,81,117,105,110,101,115,34,41,59,113,40,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,108,110,40,34,92,110,45,45,45,45,45,45,45,45,45,45,45,45,34,41,59,113,40,41,59,47,42,65,118,111,105,100,32,99,111,109,109,101,110,116,115,32,111,110,32,116,104,105,115,32,108,105,110,101,32,117,110,108,101,115,115,32,121,111,117,32,117,115,101,32,116,104,105,115,32,102,111,114,109,97,116,32,112,117,116,32,116,119,111,32,98,114,97,99,101,115,32,111,110,32,116,104,101,32,110,101,120,116,32,108,105,110,101,42,47,125,115,116,97,116,105,99,32,118,111,105,100,32,113,40,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,99,108,97,115,115,32,115,97,109,112,108,101,73,110,112,117,116,123,47,47,99,108,97,115,115,32,100,101,102,32,111,110,32,116,104,105,115,32,108,105,110,101,92,110,34,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,115,116,97,116,105,99,32,99,104,97,114,91,93,115,61,123,34,41,59,102,111,114,40,99,104,97,114,32,99,58,115,41,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,40,105,110,116,41,32,99,43,34,44,34,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,92,98,125,59,92,110,112,117,98,108,105,99,32,115,116,97,116,105,99,32,118,111,105,100,32,109,97,105,110,40,83,116,114,105,110,103,91,93,97,114,103,117,109,101,110,116,41,123,47,47,109,101,116,104,111,100,32,104,101,97,100,101,114,32,104,101,114,101,32,97,110,100,32,111,112,116,105,111,110,97,108,32,99,111,100,101,32,97,108,116,104,111,117,103,104,32,97,118,111,105,100,32,112,117,116,116,105,110,103,32,99,111,100,101,32,104,101,114,101,92,110,34,41,59,102,111,114,40,99,104,97,114,32,99,58,115,41,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,99,41,59,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,34,92,110,125,34,41,59,125};
public static void main(String[]argument){//method header here and optional code although avoid putting code here
System.out.println("Hello World Of Quines");q();System.out.println("\n------------");q();/*Avoid comments on this line unless you use this format put two braces on the next line*/}static void q(){System.out.print("class sampleInput{//class def on this line\n");System.out.print("static char[]s={");for(char c:s)System.out.print((int) c+",");System.out.print("\b};\npublic static void main(String[]argument){//method header here and optional code although avoid putting code here\n");for(char c:s)System.out.print(c);System.out.print("\n}");}
}


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

答:
Python 2, 41 bytes

```<code>lambda s:s==s-{a+b for a in s for b in s}
</code>```

s should be a Python set.

Fun fact: sum-free is an anagram of my name.

ContentLicense: CC BY-SA 3.0

Title: Is it a sum-free set?

Body:
Python 2, 41 bytes

lambda s:s==s-{a+b for a in s for b in s}

s should be a Python set.

Fun fact: sum-free is an anagram of my name.


答:
MATL, 5 bytes

```<code>t&+m~
</code>```

This outputs an array which is truthy if all entries are 1 and falsey otherwise. Here is a demo to show various truthy/falsey values in MATL.

Try it Online

Explanation

```<code>        % Implicitly grab input
t       % Duplicate
&+      % Compute sum of each element with every other element (2D Matrix)
m       % Check which members of the input are present in this matrix of sums
~       % Negate the result to yield a truthy value for sum-free sets
        % Implicitly display truthy/falsey value
</code>```

Title: Is it a sum-free set?

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

Body:
MATL, 5 bytes

t&+m~

This outputs an array which is truthy if all entries are 1 and falsey otherwise. Here is a demo to show various truthy/falsey values in MATL.

Try it Online

Explanation

        % Implicitly grab input
t       % Duplicate
&+      % Compute sum of each element with every other element (2D Matrix)
m       % Check which members of the input are present in this matrix of sums
~       % Negate the result to yield a truthy value for sum-free sets
        % Implicitly display truthy/falsey value


答:
Jelly, 5 bytes

```<code>ṗ3ḅ-P
</code>```

Try it online!

How it works

```<code>ṗ3ḅ-P  Main link. Argument: A (array)

ṗ3     Take the third Cartesian power of A, i.e., generate all triplets that
       consist of elements of A.
  ḅ-   Convert each triplet from base -1 to integer.
       This maps [a, b, c] to a - b + c = (a + c) - b.
       If (a + c) belong to A, this will yield 0 for some b.
    P  Take the product of all resulting integers.
</code>```

Title: Is it a sum-free set?

Body:
Jelly, 5 bytes

ṗ3ḅ-P

Try it online!

How it works

ṗ3ḅ-P  Main link. Argument: A (array)

ṗ3     Take the third Cartesian power of A, i.e., generate all triplets that
       consist of elements of A.
  ḅ-   Convert each triplet from base -1 to integer.
       This maps [a, b, c] to a - b + c = (a + c) - b.
       If (a + c) belong to A, this will yield 0 for some b.
    P  Take the product of all resulting integers.


问:
Chris Pine's "Deaf Grandma"
I'm a mentor at RubyLearning and one of the exercises we give to our students is the "Deaf Grandma" exercise from Chris Pine's book "Learn to Program". Here's the description:

Write a Deaf Grandma program. Whatever you say to grandma (whatever
  you type in), she should respond with:
  "Huh?! Speak up, sonny!", unless you
  shout it (type in all capitals). If
  you shout, she can hear you (or at
  least she thinks so) and yells back:
  "No, not since 1938!"

To make your program really believable, have grandma shout a
  different year each time; maybe any
  year at random between 1930 and 1950.
  (This part is optional, and would be
  much easier if you read the section on
  Ruby's random number generator at the
  end of the methods chapter.) You can't
  stop talking to grandma until you
  shout "BYE".

After several course iterations I tried to see how small I can get this and now have it down to 112 characters:

```<code>puts (s||='').upcase==s ? "NO, NOT SINCE #{1930+rand(21)}!":"HUH?! SPEAK UP, SONNY!" until(s=gets.chomp)=="BYE"
</code>```

I'm curious to see in how few characters this can be achieved in the language of your choice, because I think Ruby is already doing really well here.

Edit: The Perl solution posted below led to

```<code>ruby -nle 'puts($_=="BYE"?exit: $_.upcase!? "HUH?! SEPAK UP, SONNY!":"NO, NOT SINCE #{1930+rand(21)}!")'
</code>```

which is 92 characters for the expression + 2 more for the n and l options.

答:
Javascript - 133 131 130 128 127 121 chars

golfed version of www0z0ks solution

```<code>g='';while((i=prompt(g))!='BYE'){/[a-z]/.test(i)?g='Huh?! Speak up, sonny!':g='No, not since '+Math.floor(Math.random()*21+1930)+'!'}
</code>```

```<code>g='';while((i=prompt(g))!='BYE'){g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+Math.floor(Math.random()*21+1930)+'!'}
</code>```

```<code>g='';while((i=prompt(g))!='BYE'){g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+Math.ceil(Math.random()*21+1929)+'!'}
</code>```

```<code>for(g='';(i=prompt(g))!='BYE';g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+Math.ceil(Math.random()*21+1929)+'!');
</code>```

```<code>for(g='';(i=prompt(g))!='BYE';g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+parseInt(Math.random()*21+1930)+'!');
</code>```

```<code>for(g='';(i=prompt(g))!='BYE';g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+(Math.random()*21+1930|0)+'!');
</code>```

Edit: Saved another six chars with this great tip

Title: Chris Pine's "Deaf Grandma"

Body:
Javascript - 133 131 130 128 127 121 chars

golfed version of www0z0ks solution

g='';while((i=prompt(g))!='BYE'){/[a-z]/.test(i)?g='Huh?! Speak up, sonny!':g='No, not since '+Math.floor(Math.random()*21+1930)+'!'}

g='';while((i=prompt(g))!='BYE'){g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+Math.floor(Math.random()*21+1930)+'!'}

g='';while((i=prompt(g))!='BYE'){g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+Math.ceil(Math.random()*21+1929)+'!'}

for(g='';(i=prompt(g))!='BYE';g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+Math.ceil(Math.random()*21+1929)+'!');

for(g='';(i=prompt(g))!='BYE';g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+parseInt(Math.random()*21+1930)+'!');

for(g='';(i=prompt(g))!='BYE';g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+(Math.random()*21+1930|0)+'!');

Edit: Saved another six chars with this great tip


答:
Ruby, 36 bytes

Constructs a cartesian product of the set against itself and finds the sum of all elements, then checks for intersection with the original set. Input is arrays, but in Ruby they have enough set operations to make it work out nicely anyways.

-1 byte over my original solution (used & instead of - and compared with []) because of inspiration from @feersum

Try it here!

```<code>->s{s-s.product(s).map{|x,y|x+y}==s}
</code>```

Title: Is it a sum-free set?

Body:
Ruby, 36 bytes

Constructs a cartesian product of the set against itself and finds the sum of all elements, then checks for intersection with the original set. Input is arrays, but in Ruby they have enough set operations to make it work out nicely anyways.

-1 byte over my original solution (used & instead of - and compared with []) because of inspiration from @feersum

Try it here!

->s{s-s.product(s).map{|x,y|x+y}==s}


答:
J, <s>18</s> <s>10</s> 8 bytes

8 bytes saved thanks to miles, and 2 thanks to FrownyFrog!

```<code>-:]-.+/~
</code>```

Matches the original list with the set difference of tabulated sums. This is equivalent to:

```<code>(-: (] -. +/~)) y
</code>```

for input y. This translates to:

```<code>y -: (] -. +/~) y
y -: (y -. +/~ y)
</code>```

+/~ returns a table of sums using y. For y =: 16 1 4 9, this gives:

```<code>   +/~ 16 1 4 9
32 17 20 25
17  2  5 10
20  5  8 13
25 10 13 18
</code>```

Then, we use -., which produces a list consisting of all elements in y not in this table. If the list is sum-free, this will produce the same list. Then, -: checks for equality of lists, which produces the desired output.

Old, 18 bytes

```<code>[:-.[:>./^:_+/~e.]
</code>```

+/~ creates a table of the values of the set added to itself, and e. checks if those members are in the original set. The rest of that is negating the maximal element.

Title: Is it a sum-free set?

Body:
J, <s>18</s> <s>10</s> 8 bytes

8 bytes saved thanks to miles, and 2 thanks to FrownyFrog!

-:]-.+/~

Matches the original list with the set difference of tabulated sums. This is equivalent to:

(-: (] -. +/~)) y

for input y. This translates to:

y -: (] -. +/~) y
y -: (y -. +/~ y)

+/~ returns a table of sums using y. For y =: 16 1 4 9, this gives:

   +/~ 16 1 4 9
32 17 20 25
17  2  5 10
20  5  8 13
25 10 13 18

Then, we use -., which produces a list consisting of all elements in y not in this table. If the list is sum-free, this will produce the same list. Then, -: checks for equality of lists, which produces the desired output.

Old, 18 bytes

[:-.[:>./^:_+/~e.]

+/~ creates a table of the values of the set added to itself, and e. checks if those members are in the original set. The rest of that is negating the maximal element.

ContentLicense: CC BY-SA 4.0


问:
Line numbering - implement nl
Your task is to implement a program similar to the nl command-line tool from the GNU core utilities.

Standard loopholes are banned.

You may not use any built-in or external function, program or utility for numbering the lines of a file or string, such as nl itself or the = command in GNU sed.

Specification

Input

The program accepts filenames as arguments. Your code does not have to be cross-platform; the filename format of the OS running the code should be used, i.e. if you happen to be on Windows, the directory separator can be \ or /.

You must be able to take 64 input files, including - if it is specified. If over 64 are given, only handle the first 64.

In the list of filenames, - represents standard input.

If filenames are given, read from the files in the order that they are given and concatenate their contents, inserting a new line between each one and at the end. If you cannot read from one or more of the filenames (because the file does not exist or you do not have read permissions for it), ignore them. If all filenames specified are invalid, output nothing.

If no filenames are given, read from standard input. Only read from standard input if no filenames are given or if - is given.

Output

The program will output, to standard output, the input with lines numbered thus (You may assume that the input has \n, \r\n or \r line endings; pick whichever is convenient for you, but specify which one):

```<code><5 spaces>1<tab><content of line 1 of input>
<5 spaces>2<tab><content of line 2 of input>
...
<4 spaces>10<tab><content of line 10 of input>
...
<3 spaces>100<tab><content of line 100 of input>
...
...
</code>```

6 characters of space are allocated for the line number, and it is inserted at the end of these characters; the rest become spaces (e.g. 1 will have 5 leading spaces, 22 will have 4 leading spaces, ...). If the input is sufficiently long, you will eventually run out of space for the line number, at line 999999. You must not output anything after line 999999.

If the input is empty, output nothing.

Exit status

The lower numbers take priority: if errors 1 and 2 were encountered, exit with status 1.

Exit with status 0 if the input was successfully received, and the lines successfully numbered and output.

Exit with status 1 if one or more of the files specified on the command line were not found or could not be read from.

Exit with status 2 if too many files (more than 64) were given.

Exit with status 3 if the input was too long (more than 999999 lines).\

Scoring

This is code-golf - shortest program wins!

I may add bonuses later for implementing certain options that nl has. There are no bonuses at the moment.

答:
C, <s>362</s> 359

Just for the fun of it. ;-) Works with LF or CR/LF linefeeds.

```<code>#include<stdio.h>
#define R return
#define P printf(
e,t,l;void*f;r(){P"% 6d\t",++l);for(;(t=fgetc(f))^-1&&l<1000000;){if(ferror(f))R 1;P"%c",t);if(t==10)P"% 6d\t",++l);}P"\n");R l<1000000?0:3;}main(int c,char**v){e=c>65?2:0;for(++v;*v||c<2;++v){t=c<2||!strcmp(*v,"-")?f=stdin,0:!(f=fopen(*v,"rb"));if(t||(t=r()))e=!e|(e>t)?t:e;if(f&&f!=stdin)fclose(f);}R e;}
</code>```

Title: Line numbering - implement nl

Body:
C, <s>362</s> 359

Just for the fun of it. ;-) Works with LF or CR/LF linefeeds.

#include<stdio.h>
#define R return
#define P printf(
e,t,l;void*f;r(){P"% 6d\t",++l);for(;(t=fgetc(f))^-1&&l<1000000;){if(ferror(f))R 1;P"%c",t);if(t==10)P"% 6d\t",++l);}P"\n");R l<1000000?0:3;}main(int c,char**v){e=c>65?2:0;for(++v;*v||c<2;++v){t=c<2||!strcmp(*v,"-")?f=stdin,0:!(f=fopen(*v,"rb"));if(t||(t=r()))e=!e|(e>t)?t:e;if(f&&f!=stdin)fclose(f);}R e;}


答:
Mathematica <s>63 62</s>  42 bytes

This shorter version benefitted from A Simmons' submission. No element needs to be removed from the list before IntegerPartitions is applied.

If an element cannot be partitioned into two integers (each from the list), then IntegerPartitions[#,{2},#]=={} holds.  And checks whether this holds for every element in the list.  If so, the list is sum-free.

```<code>And@@(IntegerPartitions[#,{2},#]=={}&/@#)&
</code>```

Examples

```<code> And@@(IntegerPartitions[#,{2},#]=={}&/@ #)&@{2, 4, 9, 13}
</code>```

False

```<code> And@@(IntegerPartitions[#,{2},#]=={}&/@ #)&@{1, 5, 7}
</code>```

True

There is a 2, but no odd numbers that differ by 2.

```<code> And@@(IntegerPartitions[#,{2},#]=={}&/@#)&@{2, 3, 7, 11, 17, 23, 29, 37, 41, 47, 53, 59, 67, 71}
</code>```

True

Title: Is it a sum-free set?

Body:
Mathematica <s>63 62</s>  42 bytes

This shorter version benefitted from A Simmons' submission. No element needs to be removed from the list before IntegerPartitions is applied.

If an element cannot be partitioned into two integers (each from the list), then IntegerPartitions[#,{2},#]=={} holds.  And checks whether this holds for every element in the list.  If so, the list is sum-free.

And@@(IntegerPartitions[#,{2},#]=={}&/@#)&

Examples

 And@@(IntegerPartitions[#,{2},#]=={}&/@ #)&@{2, 4, 9, 13}

False

 And@@(IntegerPartitions[#,{2},#]=={}&/@ #)&@{1, 5, 7}

True

There is a 2, but no odd numbers that differ by 2.

 And@@(IntegerPartitions[#,{2},#]=={}&/@#)&@{2, 3, 7, 11, 17, 23, 29, 37, 41, 47, 53, 59, 67, 71}

True


答:
Racket, 58 bytes

```<code>(λ(l)(andmap(λ(m)(andmap(λ(n)(not(memq(+ n m)l)))l))l))
</code>```

Explanation:

```<code>(λ(l)(andmap(λ(m)(andmap(λ(n)(not(memq(+ n m)l)))l))l))
(λ(l)                                                 ) # Define a lambda function that takes in one parameter
     (andmap(λ(m)                                  )l)  # If for all m in l
                 (andmap(λ(n)                   )l)     # If for all n in l
                             (not(memq(+ n m)l))        # n + m is not in l
</code>```

Title: Is it a sum-free set?

Body:
Racket, 58 bytes

(λ(l)(andmap(λ(m)(andmap(λ(n)(not(memq(+ n m)l)))l))l))

Explanation:

(λ(l)(andmap(λ(m)(andmap(λ(n)(not(memq(+ n m)l)))l))l))
(λ(l)                                                 ) # Define a lambda function that takes in one parameter
     (andmap(λ(m)                                  )l)  # If for all m in l
                 (andmap(λ(n)                   )l)     # If for all n in l
                             (not(memq(+ n m)l))        # n + m is not in l


答:
Julia, 18 bytes

```<code>!x=x∩(x'.+x)==[]
</code>```

Try it online!

Title: Is it a sum-free set?

Body:
Julia, 18 bytes

!x=x∩(x'.+x)==[]

Try it online!


答:
JavaScript, <s>86</s> <s>42</s> 41 bytes

```<code>n=>!n.some(m=>n.some(o=>n.includes(m+o)))
</code>```

Thanks Cᴏɴᴏʀ O'Bʀɪᴇɴ for saving me a ton of bytes off parentheses/curly brackets. Also thanks Neil for pointing out that the function was returning the opposite boolean value than it should have.

I tried to cut down on bytes by redefining n.some but that doesn't work because it's a prototype function unfortunately. There might be a better solution with Array.prototype.map in JS but the some function is really fun.

I'm now wondering if there's a shorter way than .includes using something such as .indexOf and adding 1 (which would give it a truthy value if it contains the number).

Testing:

```<code>> (n=>!n.some(m=>n.some(o=>n.includes(m+o))))([1,5,7]);
true
> (n=>!n.some(m=>n.some(o=>n.includes(m+o))))([1,5,7,12]);
false
</code>```

Title: Is it a sum-free set?

Body:
JavaScript, <s>86</s> <s>42</s> 41 bytes

n=>!n.some(m=>n.some(o=>n.includes(m+o)))

Thanks Cᴏɴᴏʀ O'Bʀɪᴇɴ for saving me a ton of bytes off parentheses/curly brackets. Also thanks Neil for pointing out that the function was returning the opposite boolean value than it should have.

I tried to cut down on bytes by redefining n.some but that doesn't work because it's a prototype function unfortunately. There might be a better solution with Array.prototype.map in JS but the some function is really fun.

I'm now wondering if there's a shorter way than .includes using something such as .indexOf and adding 1 (which would give it a truthy value if it contains the number).

Testing:

> (n=>!n.some(m=>n.some(o=>n.includes(m+o))))([1,5,7]);
true
> (n=>!n.some(m=>n.some(o=>n.includes(m+o))))([1,5,7,12]);
false


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

Simple solution:

```<code>f x=and[a+b/=c|a<-x,b<-x,c<-x]
</code>```

Two bytes saved by @Lynn

Title: Is it a sum-free set?

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

Simple solution:

f x=and[a+b/=c|a<-x,b<-x,c<-x]

Two bytes saved by @Lynn


答:
APL, 8 bytes

```<code>⊢≡⊢~∘.+⍨
</code>```

Explanation:

```<code>⊢         argument
 ≡        equals
  ⊢       argument
   ~      without
    ∘.+⍨  sums of its elements
</code>```

Test:

```<code>      ( ⊢≡⊢~∘.+⍨ ) ¨ (1 5 7)(2 4 9 13)
1 0
</code>```

Title: Is it a sum-free set?

Body:
APL, 8 bytes

⊢≡⊢~∘.+⍨

Explanation:

⊢         argument
 ≡        equals
  ⊢       argument
   ~      without
    ∘.+⍨  sums of its elements

Test:

      ( ⊢≡⊢~∘.+⍨ ) ¨ (1 5 7)(2 4 9 13)
1 0


答:
Haskell, 30 bytes

f s=and[x+y/=z|x<-s,y<-s,z<-s]
```
<p>I think there exists a shorter solution that's more interesting, but I haven't found it.</p>
<p>These are 33 and 34 bytes:</p>
<pre class="lang-haskell prettyprint-override"><code>f s=and$((/=)<$>s<*>)$(+)<$>s<*>s
f s|q<-((-)<$>s<*>)=all(/=0)$q$q$s
</code>```

Title: Is it a sum-free set?

Body:
Haskell, 30 bytes

f s=and[x+y/=z|x<-s,y<-s,z<-s]

I think there exists a shorter solution that's more interesting, but I haven't found it.

These are 33 and 34 bytes:

f s=and$((/=)<$>s<*>)$(+)<$>s<*>s
f s|q<-((-)<$>s<*>)=all(/=0)$q$q$s


问:
Groups of repeating items

Challenge description

Given a list / array of items, display all groups of consecutive repeating items.

Input / output description

Your input is a list / array of items (you can assume all of them are of the same type). You don't need to support every type your language has, but is has to support at least one (preferably int, but types like boolean, although not very interesting, are also fine). Sample outputs:

```<code>[4, 4, 2, 2, 9, 9] -> [[4, 4], [2, 2], [9, 9]]
[1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4] -> [[1, 1, 1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
[1, 1, 1, 3, 3, 1, 1, 2, 2, 2, 1, 1, 3] -> [[1, 1, 1], [3, 3], [1, 1], [2, 2, 2], [1, 1], [3]]
[9, 7, 8, 6, 5] -> [[9], [7], [8], [6], [5]]
[5, 5, 5] -> [[5, 5, 5]]
['A', 'B', 'B', 'B', 'C', 'D', 'X', 'Y', 'Y', 'Z'] -> [['A'], ['B', 'B', 'B'], ['C'], ['D'], ['X'], ['Y', 'Y'], ['Z']]
[True, True, True, False, False, True, False, False, True, True, True] -> [[True, True, True], [False, False], [True], [False, False], [True, True, True]]
[0] -> [[0]]
</code>```

As for empty lists, output is undefined - it can be nothing, an empty list, or an exception - whatever suits your golfing purposes the best. You don't have to create a separate list of lists either, so this is a perfectly valid output as well:

```<code>[1, 1, 1, 2, 2, 3, 3, 3, 4, 9] ->

1 1 1
2 2
3 3 3
4
9
</code>```

The important thing is to keep the groups separated in some way. This is code-golf so the shortest code in bytes wins

答:
Ruby, 24 bytes

In ruby Array instances have built-in method group_by

So solution will be:

```<code>a.group_by{|x| x}.values
</code>```

Title: Groups of repeating items

Body:
Ruby, 24 bytes

In ruby Array instances have built-in method group_by

So solution will be:

a.group_by{|x| x}.values


答:
R, <s>39</s> 36 bytes

```<code>w<-function(s)!any(outer(s,s,'+')%in%s)
</code>```

Call as w(s), where s is the set (actually vector) of values. Here is the output for some test cases:

```<code>> w(numeric(0)) # The empty set
[1] TRUE
> w(0)
[1] FALSE
> w(1)
[1] TRUE
> w(c(1, 5, 7))
[1] TRUE
> w(c(2, 4, 9, 13))
[1] FALSE
</code>```

Where c() is the concatenation function that takes a bunch of values and makes it a vector.

EDIT: Making it an anonymous function to save 3 bytes, thanks to @MickyT.

```<code>function(s)!any(outer(s,s,'+')%in%s)
</code>```

Title: Is it a sum-free set?

Body:
R, <s>39</s> 36 bytes

w<-function(s)!any(outer(s,s,'+')%in%s)

Call as w(s), where s is the set (actually vector) of values. Here is the output for some test cases:

> w(numeric(0)) # The empty set
[1] TRUE
> w(0)
[1] FALSE
> w(1)
[1] TRUE
> w(c(1, 5, 7))
[1] TRUE
> w(c(2, 4, 9, 13))
[1] FALSE

Where c() is the concatenation function that takes a bunch of values and makes it a vector.

EDIT: Making it an anonymous function to save 3 bytes, thanks to @MickyT.

function(s)!any(outer(s,s,'+')%in%s)


答:
05AB1E, <s>9</s> 5 bytes

Saved 4 bytes thanks to Magic Octopus Urn

```<code>ãOå_P
</code>```

Try it online!

Explanation

```<code>ã       # cartesian product
 O      # sum
  å     # check each if it exists in input
   _    # logical negation
    P   # product
</code>```

Title: Is it a sum-free set?

Body:
05AB1E, <s>9</s> 5 bytes

Saved 4 bytes thanks to Magic Octopus Urn

ãOå_P

Try it online!

Explanation

ã       # cartesian product
 O      # sum
  å     # check each if it exists in input
   _    # logical negation
    P   # product


答:
Brachylog, 13 bytes

```<code>'(p:?+L:?x'L)
</code>```

Explanation

```<code>'(          )  True if what's in the parentheses is impossible, false otherwise
  p            Get a permutation of Input
   :?+L        L is the list of element-wise sums of the permutation with Input
       :?x'L   There is at least one element of Input in L
</code>```

Title: Is it a sum-free set?

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

Body:
Brachylog, 13 bytes

'(p:?+L:?x'L)

Explanation

'(          )  True if what's in the parentheses is impossible, false otherwise
  p            Get a permutation of Input
   :?+L        L is the list of element-wise sums of the permutation with Input
       :?x'L   There is at least one element of Input in L


问:
Implement Takewhile

Introduction and Credit

Today without a fancy prelude: Please implement takewhile.

A variation of this (on a non-trivial data structure) was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitly).

Specification

Input

The input will be a list (or your language's equivalent concept) of positive integers.

Output

The output should be a list (or your language's equivalent concept) of positive integers.

What to do?

Your task is to implement takewhile (language built-ins are allowed) with the predicate that the number under consideration is even (to focus on takewhile).

So you iterate over the list from start to end and while the condition (is even) holds, you copy to the output-list and as soon as you hit an element that doesn't make the condition true, you abort the operation and output (a step-by-step example is below). This higher-order functionality is also called takeWhile (takewhile).

Potential corner cases

The order of the output list compared to the input list may not be changed, e.g. [14,42,2] may not become [42,14].

The empty list is a valid in- and output.

Who wins?

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

Standard rules apply of course.

Test Vectors

```<code>[14, 42, 2324, 97090, 4080622, 171480372] -> [14, 42, 2324, 97090, 4080622, 171480372]
[42, 14, 42, 2324] -> [42, 14, 42, 2324]
[7,14,42] -> []
[] -> []
[171480372, 13, 14, 42] -> [171480372]
[42, 14, 42, 43, 41, 4080622, 171480372] -> [42, 14, 42]
</code>```

Step-by-Step Example

```<code>Example Input: [42, 14, 42, 43, 41, 4080622, 171480372]

Consider first element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42]

Consider second element: 14
14 is even (7*2)
Put 14 into output list, output list is now [42,14]

Consider third element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42,14,42]

Consider fourth element: 43
43 is not even (2*21+1)
Drop 43 and return the current output list

return [42,14,42]
</code>```

答:
Perl 5.10, 36 bytes

Different way of doing it when compared to the other Perl answers which are based on regexes. 35 bytes + 1 byte for -a flag.

```<code>for(@F){$_%2?last:push@a,$_}say"@a"
</code>```

Try it here!

Title: Implement Takewhile

Body:
Perl 5.10, 36 bytes

Different way of doing it when compared to the other Perl answers which are based on regexes. 35 bytes + 1 byte for -a flag.

for(@F){$_%2?last:push@a,$_}say"@a"

Try it here!


答:
Haskell, 35 bytes

main=interact(\s->s++"q="++show s)
```

<p>Includes a trailing newline.  The quine command string is <code>(putStr$q++"q="++show q)</code>.  The language subset is programs with a trailing newline that do not use the variable <code>q</code> except as part of the quine command string.</p>

<h3>Demo</h3>

<p>Input program:</p>

<pre class="lang-hs prettyprint-override"><code>main = do
  putStrLn "I am a quine and my source is:"
  (putStr$q++"q="++show q)
  putStrLn "\nHave a nice day."
</code>```

Output program:

main = do
  putStrLn "I am a quine and my source is:"
  (putStr$q++"q="++show q)
  putStrLn "\nHave a nice day."
q="main = do\n  putStrLn \"I am a quine and my source is:\"\n  (putStr$q++\"q=\"++show q)\n  putStrLn \"\\nHave a nice day.\"\n"
```

<p>Output of output program:</p>

```I am a quine and my source is:
main = do
  putStrLn "I am a quine and my source is:"
  (putStr$q++"q="++show q)
  putStrLn "\nHave a nice day."
q="main = do\n  putStrLn \"I am a quine and my source is:\"\n  (putStr$q++\"q=\"++show q)\n  putStrLn \"\\nHave a nice day.\"\n"
Have a nice day.
```

Title: No Quine Built In? No Problem!

Body:
Are you tired of languages with built in quining techniques?

Your challenge, should you choose to accept it, is to add a built-in quine feature to the language of your choice.

Task

Given some programming language X, you should define

A language X′ that is a subset of X.

A quine command string Q.  (This is a string of your choice; it need not literally be “Q”.)

Now you have a new language Y, consisting of programs that are in X′ except that they may also contain copies of Q as if Q were a new built-in statement or function.  Your job is to implement this language Y, by writing

A compiler, written in X′, producing an output program B in X for each input program A in Y.

When B is run, it should behave like A would if all its copies of Q had been replaced with a statement in X that prints the source code of B.

You’ve therefore created a language Y that contains a quining builtin Q.

Rules

Your chosen language subset X′ must still satisfy the definition of a programming language.

The output programs B of your compiler must be proper quines.  You may not use quining builtins that may already be in X.

This is code golf, so the shortest code in bytes (defined as your language's default native encoding) wins.

Body:
Haskell, 35 bytes

main=interact(\s->s++"q="++show s)

Includes a trailing newline.  The quine command string is (putStr$q++"q="++show q).  The language subset is programs with a trailing newline that do not use the variable q except as part of the quine command string.

Demo

Input program:

main = do
  putStrLn "I am a quine and my source is:"
  (putStr$q++"q="++show q)
  putStrLn "\nHave a nice day."

Output program:

main = do
  putStrLn "I am a quine and my source is:"
  (putStr$q++"q="++show q)
  putStrLn "\nHave a nice day."
q="main = do\n  putStrLn \"I am a quine and my source is:\"\n  (putStr$q++\"q=\"++show q)\n  putStrLn \"\\nHave a nice day.\"\n"

Output of output program:

I am a quine and my source is:
main = do
  putStrLn "I am a quine and my source is:"
  (putStr$q++"q="++show q)
  putStrLn "\nHave a nice day."
q="main = do\n  putStrLn \"I am a quine and my source is:\"\n  (putStr$q++\"q=\"++show q)\n  putStrLn \"\\nHave a nice day.\"\n"
Have a nice day.


答:
PHP, 73 bytes

+8 to turn the snippet into a program, -8 on obsolete variables thanks to insertusernamehere

```<code><?foreach($argv as$p)foreach($argv as$q)if(in_array($p+$q,$argv))die;echo 1;
</code>```

prints 1 for true, empty output for false

usage: php <filename> <value1> <value2> ...

qualified function for testing (<s>94</s> 86): returns 1 or nothing

```<code>function f($a){foreach($a as$p)foreach($a as$q)if(in_array($p+$q,$a))return;return 1;}
</code>```

tests

```<code>function out($a){if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';}
function cmp($a,$b){if(is_numeric($a)&&is_numeric($b))return 1e-2<abs($a-$b);if(is_array($a)&&is_array($b)&&count($a)==count($b)){foreach($a as $v){$w = array_shift($b);if(cmp($v,$w))return true;}return false;}return strcmp($a,$b);}
function test($x,$e,$y){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>",out($x),'</td><td>',out($y),'</td><td>',out($e),'</td><td>',cmp($e,$y)?'N':'Y',"</td></tr>";$h='';}
$samples = [
    [], 1,
    [0], false,
    [1], 1,
    [0,1], false,
    [2, 4, 9, 13], false,
    [1,5,7], 1
];
while($samples)
{
    $a=array_shift($samples);
    $e=array_shift($samples);
    test($a,$e,f($a));
}
</code>```

Title: Is it a sum-free set?

Body:
PHP, 73 bytes

+8 to turn the snippet into a program, -8 on obsolete variables thanks to insertusernamehere

<?foreach($argv as$p)foreach($argv as$q)if(in_array($p+$q,$argv))die;echo 1;

prints 1 for true, empty output for false

usage: php <filename> <value1> <value2> ...

qualified function for testing (<s>94</s> 86): returns 1 or nothing

function f($a){foreach($a as$p)foreach($a as$q)if(in_array($p+$q,$a))return;return 1;}

tests

function out($a){if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';}
function cmp($a,$b){if(is_numeric($a)&&is_numeric($b))return 1e-2<abs($a-$b);if(is_array($a)&&is_array($b)&&count($a)==count($b)){foreach($a as $v){$w = array_shift($b);if(cmp($v,$w))return true;}return false;}return strcmp($a,$b);}
function test($x,$e,$y){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>",out($x),'</td><td>',out($y),'</td><td>',out($e),'</td><td>',cmp($e,$y)?'N':'Y',"</td></tr>";$h='';}
$samples = [
    [], 1,
    [0], false,
    [1], 1,
    [0,1], false,
    [2, 4, 9, 13], false,
    [1,5,7], 1
];
while($samples)
{
    $a=array_shift($samples);
    $e=array_shift($samples);
    test($a,$e,f($a));
}


答:
Python, 40 bytes

lambda s:s^{a+b for a in s for b in s}>s
```

^ = symmetric difference, new set with elements in either sets but not both

> True if the left set is a superset of the right set.

Title: Is it a sum-free set?

Body:
Python, 40 bytes

lambda s:s^{a+b for a in s for b in s}>s

^ = symmetric difference, new set with elements in either sets but not both

> True if the left set is a superset of the right set.


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

答:
Haskell, 241 189 characters

```<code>import Data.List
import Random
main=randomRIO(0,719)>>=mapM_ putStrLn.f
f n=map(\(x,y)->x++" buys for "++y).zip(l n).tail$cycle$l n
l=(permutations(words"Andy Barb Carl Didi Earl Fran")!!)
</code>```

Fully random output (that still satisfies the spec).

This generates all permutations of the list of the names, picks one at random (I think this is the shortest way in Haskell to shuffle a list - if anyone has anything smaller, I'd appreciate it), and then each person then buys a present for the next person in the list.

ContentLicense: CC BY-SA 2.5

Title: Holiday Gift Exchange

Body:
Haskell, 241 189 characters

import Data.List
import Random
main=randomRIO(0,719)>>=mapM_ putStrLn.f
f n=map(\(x,y)->x++" buys for "++y).zip(l n).tail$cycle$l n
l=(permutations(words"Andy Barb Carl Didi Earl Fran")!!)

Fully random output (that still satisfies the spec).

This generates all permutations of the list of the names, picks one at random (I think this is the shortest way in Haskell to shuffle a list - if anyone has anything smaller, I'd appreciate it), and then each person then buys a present for the next person in the list.


问:
Can you Golf Golf?
You are required to generate a random 18-hole golf course.

Example output:

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

Rules:

Your program must output a list of hole lengths for exactly 18 holes

Each hole must have a length of 3, 4 or 5

The hole lengths must add up to 72 for the entire course

Your program must be able to produce every possible hole configuration with some non-zero-probability (the probabilities of each configuration need not be equal, but feel free to claim extra kudos if this is the case)

Title: Can you Golf Golf?

Body:
Java (61 chars)

while(s!=72)for(i=0,s=0;i<18;i++)s+=3+(int)(Math.random()*3);

Sample output:

5 4 3 4 5 3 4 4 3 5 4 4 4 4 3 4 4 5


答:
32-bit x86 machine code, 14 bytes

In hex:

```<code>31C9FCADD1E87203E0F941F7D9C3
</code>```

The list of integers in machine code is something like C's "int a[]". Since the list contains positive integers let's assume the list is zero-terminated, i.e. the value zero marks the end of the array. It's also makes no sense to copy values to another buffer inside this function, that's what strncpy() is for.

The pointer to an array is passed via ESI register. Returns the number of elements comprising the resulting list in ECX.

Disassembly:

```<code>31 c9     xor    ecx,ecx  ;ECX=0
fc        cld
_loop:
ad        lodsd           ;Fetch a number to EAX
d1 e8     shr    eax,1    ;EAX=>>1
72 03     jc _end         ;If CF is set then the number is odd, break
e0 f9     loopne _loop    ;--ECX; if(CF==0&&ZF==0)continue
41        inc    ecx      ;Should not include the terminating 0 into the count
_end:
f7 d9     neg    ecx      ;Counting from 0 downward, so ECX=-ECX
c3        ret
</code>```

Title: Implement Takewhile

Body:
Introduction and Credit

Today without a fancy prelude: Please implement takewhile.

A variation of this (on a non-trivial data structure) was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitly).

Specification

Input

The input will be a list (or your language's equivalent concept) of positive integers.

Output

The output should be a list (or your language's equivalent concept) of positive integers.

What to do?

Your task is to implement takewhile (language built-ins are allowed) with the predicate that the number under consideration is even (to focus on takewhile).

So you iterate over the list from start to end and while the condition (is even) holds, you copy to the output-list and as soon as you hit an element that doesn't make the condition true, you abort the operation and output (a step-by-step example is below). This higher-order functionality is also called takeWhile (takewhile).

Potential corner cases

The order of the output list compared to the input list may not be changed, e.g. [14,42,2] may not become [42,14].

The empty list is a valid in- and output.

Who wins?

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

Standard rules apply of course.

Test Vectors

```<code>[14, 42, 2324, 97090, 4080622, 171480372] -> [14, 42, 2324, 97090, 4080622, 171480372]
[42, 14, 42, 2324] -> [42, 14, 42, 2324]
[7,14,42] -> []
[] -> []
[171480372, 13, 14, 42] -> [171480372]
[42, 14, 42, 43, 41, 4080622, 171480372] -> [42, 14, 42]
</code>```

Step-by-Step Example

```<code>Example Input: [42, 14, 42, 43, 41, 4080622, 171480372]

Consider first element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42]

Consider second element: 14
14 is even (7*2)
Put 14 into output list, output list is now [42,14]

Consider third element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42,14,42]

Consider fourth element: 43
43 is not even (2*21+1)
Drop 43 and return the current output list

return [42,14,42]
</code>```

Body:
32-bit x86 machine code, 14 bytes

In hex:

31C9FCADD1E87203E0F941F7D9C3

The list of integers in machine code is something like C's "int a[]". Since the list contains positive integers let's assume the list is zero-terminated, i.e. the value zero marks the end of the array. It's also makes no sense to copy values to another buffer inside this function, that's what strncpy() is for.

The pointer to an array is passed via ESI register. Returns the number of elements comprising the resulting list in ECX.

Disassembly:

31 c9     xor    ecx,ecx  ;ECX=0
fc        cld
_loop:
ad        lodsd           ;Fetch a number to EAX
d1 e8     shr    eax,1    ;EAX=>>1
72 03     jc _end         ;If CF is set then the number is odd, break
e0 f9     loopne _loop    ;--ECX; if(CF==0&&ZF==0)continue
41        inc    ecx      ;Should not include the terminating 0 into the count
_end:
f7 d9     neg    ecx      ;Counting from 0 downward, so ECX=-ECX
c3        ret


答:
CJam, 7 bytes

```<code>qp":Q~"
</code>```

The quine command string is Qp":Q~"o.  The language subset is programs that do not use the variable Q except as part of the quine command string.

Demo

Input program:

```<code>"I am a quine and my source is:
"oQp":Q~"o"
Have a nice day."o
</code>```

Try it online

Output program:

```<code>"\"I am a quine and my source is:
\"oQp\":Q~\"o\"
Have a nice day.\"o"
:Q~
</code>```

Try it online

Output of output program:

```<code>I am a quine and my source is:
"\"I am a quine and my source is:
\"oQp\":Q~\"o\"
Have a nice day.\"o"
:Q~
Have a nice day.
</code>```

Title: No Quine Built In? No Problem!

Body:
CJam, 7 bytes

qp":Q~"

The quine command string is Qp":Q~"o.  The language subset is programs that do not use the variable Q except as part of the quine command string.

Demo

Input program:

"I am a quine and my source is:
"oQp":Q~"o"
Have a nice day."o

Try it online

Output program:

"\"I am a quine and my source is:
\"oQp\":Q~\"o\"
Have a nice day.\"o"
:Q~

Try it online

Output of output program:

I am a quine and my source is:
"\"I am a quine and my source is:
\"oQp\":Q~\"o\"
Have a nice day.\"o"
:Q~
Have a nice day.


问:
Print all 3 by 3 sturdy squares
A sturdy square (akin to a magic square) is an arrangement of the integers 1 to \$N^2\$ on an \$N\$ by \$N\$ grid such that every 2 by 2 subgrid has the same sum.

For example, for \$N = 3\$ one sturdy square is

```<code>1 5 3
9 8 7
4 2 6
</code>```

because the four 2 by 2 subgrids

```<code>1 5
9 8</code>```
```<code>5 3
8 7</code>```
```<code>9 8
4 2</code>```
```<code>8 7
2 6</code>```

all sum to the same amount, 23:

$$23 = 1 + 5 + 9 + 8 = 5 + 3 + 8 + 7 = 9 + 8 + 4 + 2 = 8 + 7 + 2 + 6$$

Now there are sturdy squares for higher values of N and even rectangular versions but your only task in this challenge is to output all possible 3 by 3 sturdy squares. There are exactly 376 distinct 3 by 3 sturdy squares, including those that are reflections or rotations of others, and not all of them have the same sum of 23.

Write a program or function that takes no input but prints or returns a string of all 376 sturdy squares in any order, separated by empty lines, with up to two optional trailing newlines. Each square should consist of three lines of three space separated nonzero decimal digits.

Here is a valid output example:

```<code>1 5 3
9 8 7
4 2 6

1 5 6
8 7 3
4 2 9

1 5 6
8 9 3
2 4 7

1 5 7
9 6 3
2 4 8

1 6 2
8 9 7
4 3 5

1 6 2
9 7 8
4 3 5

1 6 3
9 8 7
2 5 4

1 6 7
8 5 2
3 4 9

1 6 7
9 4 3
2 5 8

1 7 2
9 4 8
5 3 6

1 7 2
9 6 8
3 5 4

1 7 4
8 3 5
6 2 9

1 7 4
9 2 6
5 3 8

1 7 6
9 2 4
3 5 8

1 8 2
5 9 4
6 3 7

1 8 3
6 5 4
7 2 9

1 8 3
9 2 7
4 5 6

1 8 4
5 7 2
6 3 9

1 8 4
6 9 3
2 7 5

1 8 4
9 3 6
2 7 5

1 8 6
7 3 2
4 5 9

1 9 2
5 6 4
7 3 8

1 9 2
6 4 5
7 3 8

1 9 2
6 8 5
3 7 4

1 9 2
8 3 7
4 6 5

1 9 3
7 2 5
6 4 8

1 9 3
7 6 5
2 8 4

1 9 4
5 8 2
3 7 6

1 9 4
6 7 3
2 8 5

1 9 4
8 2 5
3 7 6

1 9 5
7 2 3
4 6 8

1 9 5
7 4 3
2 8 6

2 3 5
9 8 6
4 1 7

2 3 6
9 7 5
4 1 8

2 4 3
8 9 7
5 1 6

2 4 3
9 7 8
5 1 6

2 4 6
7 8 3
5 1 9

2 4 7
8 9 3
1 5 6

2 4 8
9 6 3
1 5 7

2 5 3
9 4 8
6 1 7

2 5 4
9 3 7
6 1 8

2 5 4
9 8 7
1 6 3

2 5 7
6 8 1
4 3 9

2 5 7
6 9 1
3 4 8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 3 1
5 7 6

8 4 9
3 1 2
5 7 6

8 5 2
1 6 7
9 4 3

8 5 2
3 4 9
7 6 1

8 5 3
4 1 9
7 6 2

8 5 3
4 2 9
6 7 1

8 5 6
1 2 3
9 4 7

8 5 6
1 7 3
4 9 2

8 5 7
1 6 2
4 9 3

8 6 2
1 4 7
9 5 3

8 6 3
2 1 7
9 5 4

8 6 4
3 2 7
5 9 1

8 6 7
1 3 2
5 9 4

8 6 7
2 1 3
5 9 4

8 7 4
1 3 5
6 9 2

8 7 5
1 2 4
6 9 3

9 1 5
3 6 7
8 2 4

9 1 5
3 8 7
6 4 2

9 1 6
2 8 5
7 3 4

9 1 6
4 3 7
8 2 5

9 1 6
5 2 8
7 3 4

9 1 7
3 4 5
8 2 6

9 1 7
3 8 5
4 6 2

9 1 8
2 7 3
6 4 5

9 1 8
4 2 5
7 3 6

9 1 8
4 6 5
3 7 2

9 1 8
5 4 6
3 7 2

9 2 4
3 7 8
6 5 1

9 2 6
1 7 4
8 3 5

9 2 6
4 1 7
8 3 5

9 2 6
5 3 8
4 7 1

9 2 7
1 8 3
6 5 4

9 2 7
4 5 6
3 8 1

9 2 8
5 1 6
4 7 3

9 3 4
1 8 6
7 5 2

9 3 6
1 8 4
5 7 2

9 3 6
2 7 5
4 8 1

9 3 8
1 4 2
7 5 6

9 3 8
1 6 2
5 7 4

9 4 3
1 6 7
8 5 2

9 4 3
2 5 8
7 6 1

9 4 7
1 2 3
8 5 6

9 4 8
1 3 2
6 7 5

9 4 8
2 1 3
6 7 5

9 5 3
1 4 7
8 6 2

9 5 4
2 1 7
8 6 3

9 5 4
2 3 7
6 8 1

9 5 7
1 2 3
6 8 4</code>```

Your program must produce these same 376 sturdy squares, just not necessarily in this order. The output does not need to be deterministic, i.e. you could output them in different orders on different runs as long as they are all there.

The shortest code in bytes wins.

The topic of sturdy squares originated with this chat message of mine which led to a large amount of discussion on their properties and how to generate them. Props to Peter Taylor, feersum, and Sp3000 for continuing the discussion, and especially to El'endia Starman for drafting a corresponding OEIS sequence.

答:
J, 83 bytes

```<code>([:;@,(<LF),.~[:(<@(LF,~":)"1@#~([:*/2=/\[:,2 2+/@,;._3])"2)(3 3)($"1)1+!A.&i.])@9:
</code>```

This is a function that outputs a string containing the 376 sturdy squares. Uses brute-force, generates all permutations of 1 thru 9, shape each into a 3x3 array, and filters it by checking if the sums of each 2x2 subarray are equal. Completes in half a second.

Usage

```<code>   f =: ([:;@,(<LF),.~[:(<@(LF,~":)"1@#~([:*/2=/\[:,2 2+/@,;._3])"2)(3 3)($"1)1+!A.&i.])@9:
   $ f ''  NB. A function has to take something to be invoked,
           NB. but in this case it is not used by the function
   37 {. f ''  NB. Take the first 37 characters
1 5 3
9 8 7
4 2 6

1 5 6
8 7 3
4 2 9

   _38 {. f ''  NB. Take the last 38 characters
9 5 4
2 3 7
6 8 1

9 5 7
1 2 3
6 8 4

   NB. The output string ends with two newlines
</code>```

Title: Print all 3 by 3 sturdy squares

Body:
J, 83 bytes

([:;@,(<LF),.~[:(<@(LF,~":)"1@#~([:*/2=/\[:,2 2+/@,;._3])"2)(3 3)($"1)1+!A.&i.])@9:

This is a function that outputs a string containing the 376 sturdy squares. Uses brute-force, generates all permutations of 1 thru 9, shape each into a 3x3 array, and filters it by checking if the sums of each 2x2 subarray are equal. Completes in half a second.

Usage

   f =: ([:;@,(<LF),.~[:(<@(LF,~":)"1@#~([:*/2=/\[:,2 2+/@,;._3])"2)(3 3)($"1)1+!A.&i.])@9:
   $ f ''  NB. A function has to take something to be invoked,
           NB. but in this case it is not used by the function
   37 {. f ''  NB. Take the first 37 characters
1 5 3
9 8 7
4 2 6

1 5 6
8 7 3
4 2 9

   _38 {. f ''  NB. Take the last 38 characters
9 5 4
2 3 7
6 8 1

9 5 7
1 2 3
6 8 4

   NB. The output string ends with two newlines


问:
Can Pac-Man Eat This String?
In the arcade version of the game, Pac-Man eats pac-dots. However, in this challenge, he's hungry for alphanumeric characters and punctuation in a string.

Your task is to create a function that feeds Pac-Man a string, evaluates if he can eat it or not, and returns the string with Pac-Man's location in it.

Pac-Man (<) eats characters from left to right, leaving an underscore or space for each character as he goes, and his goal is to get from the first position-1 to the last position+1:

```<code>1. <Pac
2. _<ac
3. __<c
4. ___<
</code>```

However, Pac-Man's natural enemy, the ghost, will stop him if he encounters one of the letters in the word "GHOST" (not case sensitive). Your function should return the string with Pac-Man's location as he encounters the ghost character:

```<code>1. <No!
2. _<o!
</code>```

The only thing that can defeat a ghost is a power pellet. If Pac-Man reaches a letter in the word "PELLET" (also not case sensitive) before coming to a ghost, he will eat the ghost and keep moving, and that pellet will be used up. Power pellets can stack (ie, in ppgg both ghosts would be eaten). The T character exists as both as a ghost and a pellet, so it can be ignored (treated as any other letter, like a).

```<code>1. <Pop
2. _<op
3. __<p
4. ___<
</code>```

To further clarify, in the string "Pac-Man loses here", the following operations occur:

```<code>P <P, +1 Pellet (1 pellet)
a <a
c <c
- <-
M <M
a <a
n <n
  <[space]
l <l, +1 Pellet (2 pellets)
o <o, -1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
e <e, +1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
  <[space]
h <h, ghost wins, returns
e
r
e
</code>```

Examples

```<code>Input: Pacman wins!
Output: ____________<

Input: Pacman loses wah-wah :(
Output: _______________<h-wah :(

Input: PELLET PELLET GHOST
Output: ___________________<

Input: Hello World!
Output: <Hello World!

Input: <_!@12<_<_<
Output: ___________<
</code>```

This is code-golf--lowest score in bytes wins.

答:
Python 3, <s>114</s> 110 bytes

My first code golf.

Thanks to Dr Green Eggs and Iron Man for saving 4 bytes.

```<code>l,x=1,0
f,y,s="ghosGHOS","pelPEL",input()
while s[x:]*l:l+=(s[x]in y)-(s[x]in f);x+=l>0
print("_"*x+"<"+s[x:])
</code>```

Utilises the evaluation of booleans to one and zero to condense a logical AND to a multiplication. (0*0=0, 1*0=0, 1*1=1). I hope this is a good first try.

Title: Can Pac-Man Eat This String?

Body:
Python 3, <s>114</s> 110 bytes

My first code golf.

Thanks to Dr Green Eggs and Iron Man for saving 4 bytes.

l,x=1,0
f,y,s="ghosGHOS","pelPEL",input()
while s[x:]*l:l+=(s[x]in y)-(s[x]in f);x+=l>0
print("_"*x+"<"+s[x:])

Utilises the evaluation of booleans to one and zero to condense a logical AND to a multiplication. (0*0=0, 1*0=0, 1*1=1). I hope this is a good first try.


答:
TSQL, 47 bytes

```<code>CREATE table T(a int)
INSERT T values(1),(5),(7),(12)

SELECT min(iif(a.a+b.a<>T.a,1,0))FROM T a,T b,T
</code>```

Note: This will only run once, then the table needs to be deleted or dropped to run again. The fiddle editor doesn't allow creation of tables. Therefore the fiddle included in my answer uses 2 extra bytes to compensate for this - the fiddle version doesn't require cleanup.

Fiddle

Title: Is it a sum-free set?

Body:
TSQL, 47 bytes

CREATE table T(a int)
INSERT T values(1),(5),(7),(12)

SELECT min(iif(a.a+b.a<>T.a,1,0))FROM T a,T b,T

Note: This will only run once, then the table needs to be deleted or dropped to run again. The fiddle editor doesn't allow creation of tables. Therefore the fiddle included in my answer uses 2 extra bytes to compensate for this - the fiddle version doesn't require cleanup.

Fiddle


答:
Retina, <s>45</s> 44 bytes

```<code>\d+
<$&$*1>
$
$`$`
M`(<1*)>.*<(1*>).*\1\2
^0
</code>```

Input is a decimal list of comma-separated numbers. Output is 0 (falsy) or 1 (truthy).

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

Stage 1: Substitution

```<code>\d+
<$&$*1>
</code>```

This converts all elements of the input to unary and wraps them in <...>. The purpose of the angle brackets is to distinguish a list containing only 0 from an empty list (since the unary representation of 0 is empty itself).

Stage 2: Substitution

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

We repeat the string 3 times by append it twice at the end.

Stage 3: Match

```<code>M`(<1*)>.*<(1*>).*\1\2
</code>```

We now try to find three numbers in the result such that the first two add up to the third. Those matches are counted (this doesn't actually count all such tuples, because matches cannot overlap, but if such a tuple exists it will be found). Hence, we get 0 for sum-free sets and something positive otherwise.

Stage 4: Match

```<code>^0
</code>```

Since the previous stage gave the opposite of what we want, we negate the result by counting the matches of ^0 which is 1 for input 0 and 0 for everything else.

Title: Is it a sum-free set?

Body:
Retina, <s>45</s> 44 bytes

\d+
<$&$*1>
$
$`$`
M`(<1*)>.*<(1*>).*\1\2
^0

Input is a decimal list of comma-separated numbers. Output is 0 (falsy) or 1 (truthy).

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

Stage 1: Substitution

\d+
<$&$*1>

This converts all elements of the input to unary and wraps them in <...>. The purpose of the angle brackets is to distinguish a list containing only 0 from an empty list (since the unary representation of 0 is empty itself).

Stage 2: Substitution

$
$`$`

We repeat the string 3 times by append it twice at the end.

Stage 3: Match

M`(<1*)>.*<(1*>).*\1\2

We now try to find three numbers in the result such that the first two add up to the third. Those matches are counted (this doesn't actually count all such tuples, because matches cannot overlap, but if such a tuple exists it will be found). Hence, we get 0 for sum-free sets and something positive otherwise.

Stage 4: Match

^0

Since the previous stage gave the opposite of what we want, we negate the result by counting the matches of ^0 which is 1 for input 0 and 0 for everything else.


问:
What's the second non-repeating character?
Based on this question from Code Review

Given a non-empty string of printable ASCII characters, output the second non-repeating character. For example, for input DEFD, output F.

Input

A single string, in any suitable format.

Output

The second character that doesn't repeat, when reading left-to-right, again in a suitable format.

The output character is case-insensitive.

If no such character exists (e.g., all characters repeat), output an empty string.

Rules

The algorithm should ignore case. That is, D and d count as the same character.

Either a full program or a function are acceptable.

The input string will be guaranteed non-empty (i.e., at least one character in length).

The input string is ASCII. Any valid character could repeat, not just alphanumeric (this includes spaces).

Standard loopholes are forbidden.

This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

Input is on first line, output is on second line.

```<code>DEFD
F

FEED
D

This is an example input sentence.
x

...,,,..,,!@
@

ABCDefgHijklMNOPqrsTuVWxyz
B

AAAAAABBBBB

Thisxthis

This this.
.
</code>```

答:
Java 8, <s>172</s> 157 bytes

```<code>(String s)->{s=s.toLowerCase();for(char i=0,c;s.length()>0;s=s.replace(c+"","")){c=s.charAt(0);if(!s.matches(".*"+c+".*"+c+".*")&&++i>1)return c;}return' ';}
</code>```

-15 bytes.. Dang I was bad at golfing back then. ;)

Explanation:

Try it here.

```<code>(String s)->{                          // Method with String parameter and character return-type
  s=s.toLowerCase();                   // Make the input-String lowercase
  for(char i=0,c;s.length()>0;         // Loop over the characters of `s`
      s=s.replace(c+"","")){           // And after every iteration, remove all occurrences of the previous iteration
    c=s.charAt(0);                     // Get the current first character
    if(!s.matches(".*"+c+".*"+c+".*")  // If it doesn't occur more than once
     &&++i>1)                          // And this was the second one we've found
      return c;                        // Return this second characters
  }                                    // End of loop
  return' ';                           // Else: return an empty character/nothing
}                                      // End of method
</code>```

Body:
Java 8, <s>172</s> 157 bytes

(String s)->{s=s.toLowerCase();for(char i=0,c;s.length()>0;s=s.replace(c+"","")){c=s.charAt(0);if(!s.matches(".*"+c+".*"+c+".*")&&++i>1)return c;}return' ';}

-15 bytes.. Dang I was bad at golfing back then. ;)

Explanation:

Try it here.

(String s)->{                          // Method with String parameter and character return-type
  s=s.toLowerCase();                   // Make the input-String lowercase
  for(char i=0,c;s.length()>0;         // Loop over the characters of `s`
      s=s.replace(c+"","")){           // And after every iteration, remove all occurrences of the previous iteration
    c=s.charAt(0);                     // Get the current first character
    if(!s.matches(".*"+c+".*"+c+".*")  // If it doesn't occur more than once
     &&++i>1)                          // And this was the second one we've found
      return c;                        // Return this second characters
  }                                    // End of loop
  return' ';                           // Else: return an empty character/nothing
}                                      // End of method


问:
"99 Bottles of Beer"
Write a program that outputs the lyrics to 99 Bottles of Beer, in as few bytes as possible.

Lyrics:

```<code>99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.

97 bottles of beer on the wall, 97 bottles of beer.
Take one down and pass it around, 96 bottles of beer on the wall.

96 bottles of beer on the wall, 96 bottles of beer.
Take one down and pass it around, 95 bottles of beer on the wall.

95 bottles of beer on the wall, 95 bottles of beer.
Take one down and pass it around, 94 bottles of beer on the wall.

....

3 bottles of beer on the wall, 3 bottles of beer.
Take one down and pass it around, 2 bottles of beer on the wall.

2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
</code>```

Rules:

Your program must log to STDOUT or an acceptable alternative, or be returned from a function (with or without a trailing newline).

Your program must be a full, runnable program or function.

Languages specifically written to submit a 0-byte answer to this challenge are allowed, just not particularly interesting.

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

This is different from the output by HQ9+ or 99. Any answers written in these languages will be deleted.

As this is a catalog challenge, this is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

Catalogue

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Python 3, 234 bytes

```<code>i=99
s='s'
b='%s bottle%s of beer'
o=' on the wall'
y=b%(i,s)
while i:print(y+o+', '+y+'.');i-=1;s=('',s)[i>1];y=b%(i,s);print(('Take one down, pass it around, '+y+o+'.\n','Go to the store and buy some more, 99'+b%(s,'s')+o+'.')[i<1])
</code>```

with newlines for some more readability

```<code>i=99;
s='s';
b='%s bottle%s of beer';
o=' on the wall';
y=b%(i,s)
while i:
  print(y+o+', '+y+'.');
  i-=1;
  s=('',s)[i>1];
  y=b%(i,s);
  print(('Take one down, pass it around, '+y+o+'.\n','Go to the store and buy some more, 99'+b%(s,'s')+o+'.')[i<1])
</code>```

makes use of a quirk of booleans to evaluate to zero or one; this allows them to be used as index in two value tuples or lists, and are shorter than the 'proper' equivalent. These pseudo ternaries are used to keep all the loop code on one line.

Title: "99 Bottles of Beer"

Body:
Python 3, 234 bytes

i=99
s='s'
b='%s bottle%s of beer'
o=' on the wall'
y=b%(i,s)
while i:print(y+o+', '+y+'.');i-=1;s=('',s)[i>1];y=b%(i,s);print(('Take one down, pass it around, '+y+o+'.\n','Go to the store and buy some more, 99'+b%(s,'s')+o+'.')[i<1])

with newlines for some more readability

i=99;
s='s';
b='%s bottle%s of beer';
o=' on the wall';
y=b%(i,s)
while i:
  print(y+o+', '+y+'.');
  i-=1;
  s=('',s)[i>1];
  y=b%(i,s);
  print(('Take one down, pass it around, '+y+o+'.\n','Go to the store and buy some more, 99'+b%(s,'s')+o+'.')[i<1])

makes use of a quirk of booleans to evaluate to zero or one; this allows them to be used as index in two value tuples or lists, and are shorter than the 'proper' equivalent. These pseudo ternaries are used to keep all the loop code on one line.


问:
Reverse a string while maintaining the capitalization in the same places
The goal here is to simply reverse a string, with one twist:

Keep the capitalization in the same places.

Example Input 1: Hello, Midnightas

Example Output 1: SathginDim ,olleh

Example Input 2: .Q

Exmaple Output 2: q.

Rules:

Output to STDOUT, input from STDIN

The winner will be picked 13th of July on GMT+3 12:00 (One week)

The input may only consist of ASCII symbols, making it easier for programs that do not use any encoding that contains non-ASCII characters.

Any punctuation ending up in a position where there was an upper-case letter must be ignored.

答:
Java 7, <s>221</s> <s>217</s> 180 bytes

```<code>void c(char[]s){int x=0,y=s.length-1;for(char t;x<y;s[x]=s(t,s[y]),s[y]=s(s[y],t),x++,y--)t=s[x];}char s(char a,char b){return(char)(64<a&a<91?96<b&b<123?b-32:b:64<b&b<91?b+32:b);}
</code>```

Loads of bytes saved thanks to @LeakuNun's approach.

Ungolfed & test cases:

Try it here.

```<code>class Main{
  void c(char[] s){
    int x = 0,
        y = s.length-1;
    for(char t; x < y; s[x] = s(t, s[y]),
                       s[y] = s(s[y], t),
                       x++,
                       y--){
       t = s[x];
    }
  }

  char s(char a, char b){
    return (char)(64 < a & a < 91
                    ? 96 < b & b < 123
                        ? b-32
                        : b
                    : 64 < b & b < 91
                        ? b+32
                        : b);
  }

  public static void main(String[] a){
    print("Hello, Midnightas");
    print("TEST");
    print("test");
    print("Test");
    print(".,..,,!@");
    print("ABCDefgHijklMNOPqrsTuVWxyz");
    print("AbCdEfGHIJKlmnop123");
  }

  static void print(String s){
    char[] t = s.toCharArray();
    c(t);
    System.out.println(t);
  }
}
</code>```

Output:

```<code>SathginDim ,olleh
q.
TSET
tset
Tset
@!,,..,.
ZYXWvutSrqpoNMLKjihGfEDcba
321pOnMLKJIhgfedcba
</code>```

Body:
Java 7, <s>221</s> <s>217</s> 180 bytes

void c(char[]s){int x=0,y=s.length-1;for(char t;x<y;s[x]=s(t,s[y]),s[y]=s(s[y],t),x++,y--)t=s[x];}char s(char a,char b){return(char)(64<a&a<91?96<b&b<123?b-32:b:64<b&b<91?b+32:b);}

Loads of bytes saved thanks to @LeakuNun's approach.

Ungolfed & test cases:

Try it here.

class Main{
  void c(char[] s){
    int x = 0,
        y = s.length-1;
    for(char t; x < y; s[x] = s(t, s[y]),
                       s[y] = s(s[y], t),
                       x++,
                       y--){
       t = s[x];
    }
  }

  char s(char a, char b){
    return (char)(64 < a & a < 91
                    ? 96 < b & b < 123
                        ? b-32
                        : b
                    : 64 < b & b < 91
                        ? b+32
                        : b);
  }

  public static void main(String[] a){
    print("Hello, Midnightas");
    print("TEST");
    print("test");
    print("Test");
    print(".,..,,!@");
    print("ABCDefgHijklMNOPqrsTuVWxyz");
    print("AbCdEfGHIJKlmnop123");
  }

  static void print(String s){
    char[] t = s.toCharArray();
    c(t);
    System.out.println(t);
  }
}

Output:

SathginDim ,olleh
q.
TSET
tset
Tset
@!,,..,.
ZYXWvutSrqpoNMLKjihGfEDcba
321pOnMLKJIhgfedcba


问:
Leave a Comment
Task:

Make a program that leaves a comment on this question. The content should be 1234567890123456.

Edits:

You may leave your usernames and passwords as U and P if you are
using username and password. (if applicable)

No URL Shorteners (if applicable)

You may not use the browser console.

答:
Java 8 with Selenium Webdriver, 684 bytes:

```<code>import java.util.*;import org.openqa.selenium.*;import org.openqa.selenium.firefox.*;class Leave_a_Comment_PPCG_Challenge_Golfed_Version_1{static void Y(String U,String P){WebDriver D=new FirefoxDriver();D.get("http://www.codegolf.stackexchange.com/users/login");D.findElement(By.name("email")).sendKeys(U);WebElement Z=D.findElement(By.name("password"));Z.sendKeys(P);Z.submit();D.get("http://www.codegolf.stackexchange.com/questions/84546");D.findElement(By.linkText("add a comment")).click();WebElement V=D.findElement(By.name("comment"));V.sendKeys("1234567890123456");D.findElement(By.xpath("//input[@value='Add Comment']")).click();}public static void main(String[]a){Scanner I=new Scanner(System.in);Y(I.next(),I.next());}}
</code>```

A direct adaptation in Java 8 of my second full program answer in Python. Works perfectly in Firefox and asks for space separated email and password input immediately when the program starts. In other words, the input is in the format Email Password where the space in between the two is needed.

Title: Leave a Comment

Body:
Java 8 with Selenium Webdriver, 684 bytes:

import java.util.*;import org.openqa.selenium.*;import org.openqa.selenium.firefox.*;class Leave_a_Comment_PPCG_Challenge_Golfed_Version_1{static void Y(String U,String P){WebDriver D=new FirefoxDriver();D.get("http://www.codegolf.stackexchange.com/users/login");D.findElement(By.name("email")).sendKeys(U);WebElement Z=D.findElement(By.name("password"));Z.sendKeys(P);Z.submit();D.get("http://www.codegolf.stackexchange.com/questions/84546");D.findElement(By.linkText("add a comment")).click();WebElement V=D.findElement(By.name("comment"));V.sendKeys("1234567890123456");D.findElement(By.xpath("//input[@value='Add Comment']")).click();}public static void main(String[]a){Scanner I=new Scanner(System.in);Y(I.next(),I.next());}}

A direct adaptation in Java 8 of my second full program answer in Python. Works perfectly in Firefox and asks for space separated email and password input immediately when the program starts. In other words, the input is in the format Email Password where the space in between the two is needed.


问:
IPv4 Integer Conversion Function
Write the shortest function to convert an IP address into it's integer representation and output it as an integer.

To change an IPv4 address to it's integer representation, the following calculation is required:

Break the IP address into it's four octets.

(Octet1 * 16777216) + (Octet2 * 65536) + (Octet3 * 256) + (Octet4)

Sample Input

```<code>192.168.1.1           10.10.104.36           8.8.8.8
</code>```

Sample Output

```<code>3232235777            168454180              134744072
</code>```

答:
C# – 77 chars

```<code>Func<string,uint>F=s=>s.Split('.').Aggregate(0u,(c,b)=>(c<<8)+uint.Parse(b));
</code>```

Title: IPv4 Integer Conversion Function

Body:
C# – 77 chars

Func<string,uint>F=s=>s.Split('.').Aggregate(0u,(c,b)=>(c<<8)+uint.Parse(b));


Title: Is it a sum-free set?

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

Body:
Actually, 7 bytes

;;∙♂Σ∩Y

Try it online!

;;∙♂Σ∩Y              Stack: [1,5,7]
;         duplicate         [1,5,7] [1,5,7]
 ;        duplicate         [1,5,7] [1,5,7] [1,5,7]
  ∙       cartesian product [1,5,7] [[1,1],[1,5],[1,7],[5,1],[5,5],[5,7],[7,1],[7,5],[7,7]]
   ♂Σ     sum each          [1,5,7] [2,6,8,6,10,12,8,12,14]
     ∩    intersect         []
      Y   negate            1


答:
Clojure, <s>47</s> 37 bytes

```<code>#(=(for[a % b % :when(%(+ a b))]a)[])
</code>```

quite plain solution. uses list comprehension to find all elements which sum is equal to another element.

38 bytes variant:

```<code>#(every? nil?(for[a % b %](%(+ a b))))
</code>```

Title: Is it a sum-free set?

Body:
Clojure, <s>47</s> 37 bytes

#(=(for[a % b % :when(%(+ a b))]a)[])

quite plain solution. uses list comprehension to find all elements which sum is equal to another element.

38 bytes variant:

#(every? nil?(for[a % b %](%(+ a b))))


问:
Print a bunch of uninteresting numbers!
An uninteresting number (which I totally didn't make up only for this challenge) is created like this:

Take a positive integer N

Create a new number O by adding the digits of N at the end of N

The final uninteresting number is O*N

For example for N=12:

O = 1212

O*N = 1212 * 12

Final number is 14544

Input

A positive integer N (N > 0) or your language's equivalent. You don't have to catch incorrect input.

Output

The corresponding uninteresting number.

Test cases

```<code>  1 -> 11
  2 -> 44
  3 -> 99
 10 -> 10100
174 -> 30306276
</code>```

Scoring

Shortest Code in Bytes wins.

答:
Python 2.7, 21 bytes:

```<code>lambda f:int(`f`*2)*f
</code>```

Well, this has to be the shortest Python answer I have ever written in the shortest amount of time ever. It's an anonymous lambda function that can be executed by naming it anything you want and then calling it like a normal function wrapped in print(). For instance, if your input is 12, and the function was named H, this this would be called like print(H(12)).

Try It Online! (Ideone)

Note that this only works for values up and equal to 9223372036854775807 since any higher value and repr() puts a L at the end of the integer. Therefore, for values greater than 9223372036854775807, this 24 byte version would be the one that works:

```<code>lambda f:int(str(f)*2)*f
</code>```

Try This Online! (Ideone)

Title: Print a bunch of uninteresting numbers!

Body:
Python 2.7, 21 bytes:

lambda f:int(`f`*2)*f

Well, this has to be the shortest Python answer I have ever written in the shortest amount of time ever. It's an anonymous lambda function that can be executed by naming it anything you want and then calling it like a normal function wrapped in print(). For instance, if your input is 12, and the function was named H, this this would be called like print(H(12)).

Try It Online! (Ideone)

Note that this only works for values up and equal to 9223372036854775807 since any higher value and repr() puts a L at the end of the integer. Therefore, for values greater than 9223372036854775807, this 24 byte version would be the one that works:

lambda f:int(str(f)*2)*f

Try This Online! (Ideone)


答:
Mathematica, 23 Bytes

```<code>{}==#⋂Tr/@#~Tuples~2&
</code>```

Title: Is it a sum-free set?

Body:
Mathematica, 23 Bytes

{}==#⋂Tr/@#~Tuples~2&


答:
MATL, 6 bytes

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

Try it online!

```<code>tV     % Input number implicitly. Duplicate and convert to string
th     % Duplicate and concatenate the two equal strings
U      % Convert to number
*      % Multiply
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
An uninteresting number (which I totally didn't make up only for this challenge) is created like this:

Take a positive integer N

Create a new number O by adding the digits of N at the end of N

The final uninteresting number is O*N

For example for N=12:

O = 1212

O*N = 1212 * 12

Final number is 14544

Input

A positive integer N (N > 0) or your language's equivalent. You don't have to catch incorrect input.

Output

The corresponding uninteresting number.

Test cases

```<code>  1 -> 11
  2 -> 44
  3 -> 99
 10 -> 10100
174 -> 30306276
</code>```

Scoring

Shortest Code in Bytes wins.

Body:
MATL, 6 bytes

tVthU*

Try it online!

tV     % Input number implicitly. Duplicate and convert to string
th     % Duplicate and concatenate the two equal strings
U      % Convert to number
*      % Multiply


答:
Lua, 20 Bytes

Takes in a command-line argument, and outputs via STDOUT

a=...print((a..a)*a)
```
<p>And ungolfed as @LeakyNun asked in the comment :)</p>
<pre class="lang-lua prettyprint-override"><code>a=...       -- alias for the first argument
print(
     (a..a) -- concatenate a with itself, equivalent to a:rep(2)
     *a)    -- multiply the resulting number by a
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
Lua, 20 Bytes

Takes in a command-line argument, and outputs via STDOUT

a=...print((a..a)*a)

And ungolfed as @LeakyNun asked in the comment :)

a=...       -- alias for the first argument
print(
     (a..a) -- concatenate a with itself, equivalent to a:rep(2)
     *a)    -- multiply the resulting number by a


答:
JavaScript (ES6), 10 bytes

_=>(_+_)*_
```

<p>Needs to be called with the argument as a <code>String</code>, not a <code>Number</code>.</p>

<h3>Usage:</h3>

<pre class="lang-js prettyprint-override"><code>(_=>(_+_)*_)('3')
99
</code>```

-3 bytes thanks to @Quill's suggestion.

Title: Print a bunch of uninteresting numbers!

Body:
JavaScript (ES6), 10 bytes

_=>(_+_)*_

Needs to be called with the argument as a String, not a Number.

Usage:

(_=>(_+_)*_)('3')
99

-3 bytes thanks to @Quill's suggestion.


答:
Clojure, 22 bytes

```<code>#(*(bigint(str % %))%)
</code>```

Anonymous function which concatenates string representation of its argument covnerts it to BigInteger and multiplies by the argument. The output is in format 11N (N signifies its a bigint), if there should be no N at the end then we can use

```<code>#(*(read-string(str % %))%)
</code>```

for 27 bytes.

See it online: https://ideone.com/QqYfpo

Title: Print a bunch of uninteresting numbers!

Body:
Clojure, 22 bytes

#(*(bigint(str % %))%)

Anonymous function which concatenates string representation of its argument covnerts it to BigInteger and multiplies by the argument. The output is in format 11N (N signifies its a bigint), if there should be no N at the end then we can use

#(*(read-string(str % %))%)

for 27 bytes.

See it online: https://ideone.com/QqYfpo


答:
05AB1E, 3 bytes

```<code>Ð«*
</code>```

Explained

```<code>Ð    # triplicate input
 «   # conactenate
  *  # multiply
</code>```

Try it online

Title: Print a bunch of uninteresting numbers!

Body:
05AB1E, 3 bytes

Ð«*

Explained

Ð    # triplicate input
 «   # conactenate
  *  # multiply

Try it online


问:
Quickly find length of n-th term of the look-and-say sequence
The look and say sequence is an example of a run length encoding sequence.  To get the next term of the sequence one groups the sequence into runs of the same number, each group in the next term then becomes two digits, first the number of terms in the group, followed by the value in the group.  The first term is 1.

Here is how we would calculate the first couple of terms by hand:

We start with 1, grouping that gives us [1] a single group of 1 1.  Thus our next term is 11.  We group this and get [11] a single group of 2 1s, so our next term is 21.  Grouping again we get [2],[1], we translate each of these groups into 2 digits each, 12,11 and concatenate, 1211.  Group again [1],[2],[11], then convert each group, 11,12,21 and concatenate, 111221.

The first couple terms of the sequence are:

```<code>1
11
21
1211
111221
312211
13112221
1113213211
</code>```

Write a program that when given n as input returns the length of the nth term of this sequence as output.
Programs should have a runtime of O(n log n).

Answers will be scored in bytes with less bytes being better.


答:
C#, 19 23 bytes

```<code>n=>int.Parse(""+n+n)*n;
</code>```

Without strings, 47 bytes

```<code>n=>{int i=1;while(i<=n)i*=10;return(i+1)*n*n;};
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
C#, 19 23 bytes

n=>int.Parse(""+n+n)*n;

Without strings, 47 bytes

n=>{int i=1;while(i<=n)i*=10;return(i+1)*n*n;};


答:
CJam, 8 bytes

```<code>ri_`_+i*
</code>```

Try it online!

```<code>r     e# Read input
i     e# Convert to integer
_     e# Duplicate
`     e# Convert to string
_     e# Duplicate
+     e# Concatenate
i     e# Convert to integer
*     e# Multiply. Implicitly display
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
CJam, 8 bytes

ri_`_+i*

Try it online!

r     e# Read input
i     e# Convert to integer
_     e# Duplicate
`     e# Convert to string
_     e# Duplicate
+     e# Concatenate
i     e# Convert to integer
*     e# Multiply. Implicitly display


答:
zsh, 13 bytes

```<code><<<$[$1$1*$1]
</code>```

Takes input as a command line argument, outputs to STDOUT.

This only works in zsh, but here's 15 bytes in Bash using echo instead of <<<:

```<code>echo $[$1$1*$1]
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
zsh, 13 bytes

<<<$[$1$1*$1]

Takes input as a command line argument, outputs to STDOUT.

This only works in zsh, but here's 15 bytes in Bash using echo instead of <<<:

echo $[$1$1*$1]


答:
Java 8, <s>29 26 25</s> 21  Bytes

God bless lambda

```<code>c->new Long(c+""+c)*c
</code>```

<s>c->Long.decode(c+""+c)*c;</s>

Title: Print a bunch of uninteresting numbers!

Body:
Java 8, <s>29 26 25</s> 21  Bytes

God bless lambda

c->new Long(c+""+c)*c

<s>c->Long.decode(c+""+c)*c;</s>


答:
Pyth, <s>5</s> 4 bytes

```<code>*s+`
</code>```

Explanation:

```<code>    Q    input
   `     representation, basically str(Q)
  +  Q   add Q to its own string form
 s       parse int
*     Q  multiply by input
         print
</code>```

Test it here.

Title: Print a bunch of uninteresting numbers!

Body:
Pyth, <s>5</s> 4 bytes

*s+`

Explanation:

    Q    input
   `     representation, basically str(Q)
  +  Q   add Q to its own string form
 s       parse int
*     Q  multiply by input
         print

Test it here.


答:
Dyalog APL, 7 bytes

```<code>⊢×#⍎⍕,⍕
</code>```

⍕ string representation

⍕, prepend string representation

#⍎ make into number (in root namespace)

⊢× multiply by original number

Title: Print a bunch of uninteresting numbers!

Body:
Dyalog APL, 7 bytes

⊢×#⍎⍕,⍕

⍕ string representation

⍕, prepend string representation

#⍎ make into number (in root namespace)

⊢× multiply by original number


答:
Pyke, <s>5</s> 4 bytes

```<code>`+b*
</code>```

Try it here!

```<code>`    -    str(input)
 +   -   ^+input  (convert to string implicitly)
  b  -  int(^)
   * - ^*input
</code>```

Also 5 bytes with string inputs

```<code>+bRb*
+]mbB
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
Pyke, <s>5</s> 4 bytes

`+b*

Try it here!

`    -    str(input)
 +   -   ^+input  (convert to string implicitly)
  b  -  int(^)
   * - ^*input

Also 5 bytes with string inputs

+bRb*
+]mbB


问:
Dig to Australia - antipodes

Background

Countless generations of children have wondered where they would end up if they dug a hole directly downwards. It turns out that this would, unsurprisingly, be rather dangerous, but anyway...

Antipodes are points that are directly opposite each other on the Earth's surface. This means that if a line was drawn between the two points, it would pass through the centre of the Earth.

Challenge

Write a program or function that, given a point, finds its antipode.

In this challenge, points are represented using the longitude-latitude system and degrees, arc minutes and arc seconds. To find the antipode, swap the directions of each ordinate (N <-> S and W <-> E) and subtract the longitude ordinate from 180 degrees.

Example:

Take the point N 50 26 23 W 4 18 29. Swap the directions to give S 50 26 23 E 4 18 29. Subtract the longitude ordinate from 180 0 0 to give 175 41 31, leaving the antipode coordinates as S 50 26 23 E 175 41 31.

Rules

Input

A set of latitude-longitude coordinates, in any reasonable format, where each ordinate contains a direction, a number of degrees, a number of arc minutes, and a number of arc seconds.

Output

The latitude-longitude coordinates of the antipode, in any reasonable format, where each ordinate contains a direction, a number of degrees, a number of arc minutes, and a number of arc seconds.

Take reasonable to mean that each part of the coordinate can be distinguished unambiguously.

Specs

The direction for the latitude ordinate is N or S, and that for the longitude ordinate is W or E.

All coordinate values are integers. The degree value will be between 0 and 90 for latitude, and between 0 and 180 for longitude. The arc minute and arc second values for both ordinates will be between 0 and 59.

If all the values for an ordinate are 0, either direction is acceptable.

There is no need to zero-pad any values.

No latitude ordinate will ever  be larger than 90 degrees, and no longitude ordinate will ever be larger than 180 degrees.

Standard loopholes apply.

Test cases

```<code>N 50 26 23 W 4 18 29 -> S 50 26 23 E 175 41 31

S 43 9 9 E 0 0 5     -> N 43 9 9 W 179 59 55

N 0 0 0 E 0 0 0      -> S/N 0 0 0 W/E 180 0 0 (either direction fine in each case)

S 1 2 3 W 4 5 6      -> N 1 2 3 E 175 54 54

S 9 21 43 W 150 7 59 -> N 9 21 43 E 29 52 1

S 27 40 2 W 23 0 0   -> N 27 40 2 E 157 0 0

N 0 58 37 W 37 0 0   -> S 0 58 37 E 143 0 0
</code>```

Useful links

Latitude and longitude

Antipodes

Arc minutes and arc seconds

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

答:
PostGIS, 123 bytes

The Tool-For-The-Job is disappointingly verbose, partly because of SQL wordiness and partly due to the need to cast to geometry and back:

CREATE FUNCTION f(p geography)
RETURNS geography
AS 'SELECT ST_Affine(p::geometry,1,0,0,-1,180,0)::geography' LANGUAGE sql;
```

On the other hand, this single function will transform points, collections of points, or more complex shapes (such as the entire coastline of Australia and New Zealand).

Title: Dig to Australia - antipodes

Body:
PostGIS, 123 bytes

The Tool-For-The-Job is disappointingly verbose, partly because of SQL wordiness and partly due to the need to cast to geometry and back:

CREATE FUNCTION f(p geography)
RETURNS geography
AS 'SELECT ST_Affine(p::geometry,1,0,0,-1,180,0)::geography' LANGUAGE sql;

On the other hand, this single function will transform points, collections of points, or more complex shapes (such as the entire coastline of Australia and New Zealand).


答:
vim, 11

```<code>C<C-r>=<C-r>"<C-r>"*<C-r>"<cr>
</code>```

crcrcrcrcr...

```<code>C       change (delete and enter insert mode) until the end of the line
<C-r>=  insert an expression via the special "expression register"
<C-r>"  insert the contents of the default register (what we just C'd)
<C-r>"  ... again
*       multiplied by
<C-r>"  the input (again)
<cr>    insert the result of this expression
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
vim, 11

C<C-r>=<C-r>"<C-r>"*<C-r>"<cr>

crcrcrcrcr...

C       change (delete and enter insert mode) until the end of the line
<C-r>=  insert an expression via the special "expression register"
<C-r>"  insert the contents of the default register (what we just C'd)
<C-r>"  ... again
*       multiplied by
<C-r>"  the input (again)
<cr>    insert the result of this expression