问:
Simple cat program
One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a "cat program": read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility cat it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc.

Task

You should write a full program which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's prompt and alert). These are the only admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable.

The output should contain exactly the input and nothing else. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. This also applies to trailing newlines. If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.)

Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. If you do this, I encourage you to add an error-free version to your answer as well (for reference).

As this is intended as a challenge within each language and not between languages, there are a few language specific rules:

If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well).

If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example yes | tr -d \\n | ./my_cat should print an infinite stream of ys. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing).

Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output.

Additional rules

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.

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

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

Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but 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.

Also note that languages do have to fulfil our usual criteria for programming languages.

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

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

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

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

```

答:
C++ (109 Bytes)

Thanks to Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ for reducing 4 bytes.

```<code>#include <iostream>
#include <string>
using namespace std;main(){string A,W;while(cin>>A)W+=A;cout<<W<<endl;}
</code>```

Title: Simple cat program

Body:
C++ (109 Bytes)

Thanks to Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ for reducing 4 bytes.

#include <iostream>
#include <string>
using namespace std;main(){string A,W;while(cin>>A)W+=A;cout<<W<<endl;}


问:
Obfuscated FizzBuzz Golf
Create the shortest possible obfuscated FizzBuzz implementation.

To be considered obfuscated, it should satisfy at least one of the following:

Does not contain any of the words "Fizz", "Buzz", or "FizzBuzz"

Does not contain the numbers 3, 5, or 15.

Use any of the above in a misleading way.

Remember: The goal is to be short and hard to follow.

The code sample which inspired this question follows:

```<code>public class Default
{
        enum FizzBuzz
        {
            Buzz = 1,
            Fizz,
            FizzBuzz
        }
        public static void Main(string[] args)
        {
            byte[] foo =
              Convert.FromBase64String("IAmGMEiCIQySYAiDJBjCIAmGMEiCIQySYA==");
            MemoryStream ms = new MemoryStream(foo);
            byte[] myByte = new byte[1];
            do
            {
                FizzBuzz fb;
                ms.Read(myByte, 0, 1);
                for (int i = 0; i < 4; i++)
                {
                    fb = (FizzBuzz)(myByte[0] >> (2 * i)
                         & (int)FizzBuzz.FizzBuzz);
                    Console.Out.WriteLine( (((int)fb > 0) ? "" + fb : ""
                         + ((ms.Position - 1) * 4 + i + 1)));
                }
            } while (ms.Position < ms.Length);
        }
}
</code>```

答:
C++ (478 Bytes)

It beats the previous C++ code easily.

```<code>#include<iostream>
#include<string>
using namespace std;int main() {string K = "FBiuzzzz";for (int i = 1; i <= 100; i++) {if (i % ((35 / 10)*(35 % 10))==0) {for (int j = 0; j < 8; j += 2)cout << K.at(j);for (int j = 1; j < 8; j += 2)cout << K.at(j);cout << endl;}else if (i % (35 / 10) == 0) {for (int j = 0; j < 8; j += 2)cout << K.at(j);cout << endl;}else if (i % (35 % 10) == 0) {for (int j = 1; j < 8; j += 2)cout << K.at(j);cout << endl;} else cout << i << endl;}return 0;}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Obfuscated FizzBuzz Golf

Body:
C++ (478 Bytes)

It beats the previous C++ code easily.

#include<iostream>
#include<string>
using namespace std;int main() {string K = "FBiuzzzz";for (int i = 1; i <= 100; i++) {if (i % ((35 / 10)*(35 % 10))==0) {for (int j = 0; j < 8; j += 2)cout << K.at(j);for (int j = 1; j < 8; j += 2)cout << K.at(j);cout << endl;}else if (i % (35 / 10) == 0) {for (int j = 0; j < 8; j += 2)cout << K.at(j);cout << endl;}else if (i % (35 % 10) == 0) {for (int j = 1; j < 8; j += 2)cout << K.at(j);cout << endl;} else cout << i << endl;}return 0;}

ContentLicense: CC BY-SA 3.0


答:
J, 14 bytes

```<code>stdout]stdin''
</code>```

Reads the entire input from stdin until EOF is reached and store it as an array of characters. Then output all of it to stdout. This will work when saved as a script to be run using jconsole, where scripts are programs for interpreted languages.

Title: Simple cat program

Body:
One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a "cat program": read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility cat it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc.

Task

You should write a full program which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's prompt and alert). These are the only admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable.

The output should contain exactly the input and nothing else. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. This also applies to trailing newlines. If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.)

Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. If you do this, I encourage you to add an error-free version to your answer as well (for reference).

As this is intended as a challenge within each language and not between languages, there are a few language specific rules:

If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well).

If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example yes | tr -d \\n | ./my_cat should print an infinite stream of ys. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing).

Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output.

Additional rules

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.

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

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

Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but 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.

Also note that languages do have to fulfil our usual criteria for programming languages.

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

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

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

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

```

Body:
J, 14 bytes

stdout]stdin''

Reads the entire input from stdin until EOF is reached and store it as an array of characters. Then output all of it to stdout. This will work when saved as a script to be run using jconsole, where scripts are programs for interpreted languages.


问:
Time for some TEA!

Introduction

A while back I stumbled across the tiny encryption algorithm (TEA) and since then I have recommended it whenever special cryptographic security properties were un-needed and a self-implementation was a requirement.

Now today, we want to take the name *tiny* encryption algorithm literally and your task will be to implement the tiniest encryption algorithm!

Specification

Input

The input is a list of 8 bytes (or your language equivalent), this is the plaintext, and another list of 16 bytes (or your language equivalent), this is the key.

Input conversion from decimal, hexadecimal, octal or binary is allowed.
 Reading 1 64-bit, 2 32-bit or 4 16-bit integers as output (optionally as a list) is allowed (for the plaintext, double the numbers for the key)

Output

The output is a list of 8 bytes (or your language equivalent), this is the ciphertext.

Output conversion to decimal, hexadecimal, octal or binary is allowed, but not mandatory.

Writing 1 64-bit, 2 32-bit or 4 16-bit integers as output (optionally as a list) is allowed.

What to do?

Your task is to implement the encryption direction of the tiny encryption algorithm (TEA), note XTEA and XXTEA are other algorithms.

Wikipedia has a C-code example and a list of references to some implementations in other languages, this is the original description (PDF).

More Formally:

```<code>Let k1, k2, k3, k4, v1, v2, sum be unsigned 32-bit integers.
(k1,k2,k3,k4) <- key input
(v1,v2) <- plaintext input
sum <- 0
repeat 32 times:
    sum <- ( sum + 0x9e3779b9 ) mod 2^32
    v0  <- ( v0 + ( ((v1 << 4) + k0) XOR (v1 + sum) XOR ((v1 >> 5) + k1) ) ) mod 2^32
    v1  <- ( v1 + ( ((v0 << 4) + k2) XOR (v0 + sum) XOR ((v0 >> 5) + k3) ) ) mod 2^32
output <- (v0,v1)

where 0x9e3779b9 is a hexadecimal constant and
"<<" denotes logical left shift and ">>" denotes logical right shift.
</code>```

Potential corner cases

\0 is a valid character and you may not shorten your input nor output.

Integer encoding is assumed to be little-endian (e.g. what you probably already have).

Who wins?

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

Standard rules apply of course.

Test-cases

Test vectors were generated using the Wikipedia C code example.

```<code>Key: all zero (16x \0)
Plaintext -> Ciphertext (all values as two 32-bit hexadecimal words)
00000000 00000000 -> 41ea3a0a 94baa940
3778001e 2bf2226f -> 96269d3e 82680480
48da9c6a fbcbe120 -> 2cc31f2e 228ad143
9bf3ceb8 1e076ffd -> 4931fc15 22550a01
ac6dd615 9c593455 -> 392eabb4 505e0755
ebad4b59 7b962f3c -> b0dbe165 cfdba177
ca2d9099 a18d3188 -> d4641d84 a4bccce6
b495318a 23a1d131 -> 39f73ca0 bda2d96c
bd7ce8da b69267bf -> e80efb71 84336af3
235eaa32 c670cdcf -> 80e59ecd 6944f065
762f9c23 f767ea2c -> 3f370ca2 23def34c
</code>```

Here are some self-generated test vectors with non-zero keys:

```<code>format: ( 4x 32-bit word key , 2x 32-bit word plaintext ) -> ( 2x 32-bit word ciphertext )
(all in hexadecimal)

( 4300e123 e39877ae 7c4d7a3c 98335923 , a9afc671 79dcdb73 ) -> ( 5d357799 2ac30c80 )
( 4332fe8f 3a127ee4 a9ca9de9 dad404ad , d1fe145a c84694ee ) -> ( a70b1d53 e7a9c00e )
( 7f62ac9b 2a0771f4 647db7f8 62619859 , 618f1ac2 67c3e795 ) -> ( 0780b34d 2ca7d378 )
( 0462183a ce7edfc6 27abbd9a a634d96e , 887a585d a3f83ef2 ) -> ( d246366c 81b87462 )
( 34c7b65d 78aa9068 599d1582 c42b7e33 , 4e81fa1b 3d22ecd8 ) -> ( 9d5ecc3b 947fa620 )
( f36c977a 0606b8a0 9e3fe947 6e46237b , 5d8e0fbe 2d3b259a ) -> ( f974c6b3 67e2decf )
( cd4b3820 b2f1e5a2 485dc7b3 843690d0 , 48db41bb 5ad77d7a ) -> ( b4add44a 0c401e70 )
( ee2744ac ef5f53ec 7dab871d d58b3f70 , 70c94e92 802f6c66 ) -> ( 61e14e3f 89408981 )
( 58fda015 c4ce0afb 49c71f9c 7e0a16f0 , 6ecdfbfa a705a912 ) -> ( 8c2a9f0c 2f56c18e )
( 87132255 41623986 bcc3fb61 7e6142ce , 9d0eff09 55ac6631 ) -> ( 8919ea55 c7d430c6 )
</code>```

答:
C, 116 bytes

T(v,w,k,l,m,n,s)unsigned*v,*w;{for(s=0;s+957401312;*v+=*w*16+k^*w+s^*w/32+l,*w+=*v*16+m^*v+s^*v/32+n)s+=2654435769;}
```

Takes plaintext as v and w; key as k, l, m, and n; and stores the ciphertext in v and w.

Test it on Ideone.

Title: Time for some TEA!

Body:
C, 116 bytes

T(v,w,k,l,m,n,s)unsigned*v,*w;{for(s=0;s+957401312;*v+=*w*16+k^*w+s^*w/32+l,*w+=*v*16+m^*v+s^*v/32+n)s+=2654435769;}

Takes plaintext as v and w; key as k, l, m, and n; and stores the ciphertext in v and w.

Test it on Ideone.


问:
Write a chicken interpreter!
You have to write an interpreter for a cool language called Chicken!

You should read a Chicken program from a file, standard input, program or function arguments, or whatever is most convenient for your language, as well as input to the program.

You should print or return the result of interpreting the program according to the Chicken language specification.

More description about the language.

Chicken Program Overview

Chicken operates on a single stack, which composes its entire memory model. As instructions are executed, the program will push and pop values from the stack, but there are also instructions that allow the program to modify other parts of the stack at will.

There are three segments in the stack:

The registers, at indices 0 and 1. Index 0 is a reference to the stack itself, and index 1 is a reference to the user input. Mostly used for instruction 6 (see below).

The loaded code: for each line of code there is cell in this segment that contains the number of "chicken"s in the line. This is padded with a 0 (opcode for terminate program) at the end.

The actual program stack, where values are pushed/popped as the program runs. Note that the segments are not isolated, which means that it is possible to create self-modifying code or execute code from this segment of the stack space.

The Chicken ISA

Chicken's instruction set is based around the number of times the word "chicken" appears on each line of the program. An empty line terminates the program and prints the topmost value in the stack.

The Chicken instruction set, by number of "chicken"s per line:

Push the literal string "chicken" to the stack

Add top two stack values as natural numbers and push the result.

Subtract top two values as natural numbers and push the result.

Multiply top two values as natural numbers and push the result.

Compare two top values for equality, push 1 if they are equal and 0 otherwise.

Look at the next instruction to determine which source to load from: 0 loads from stack, 1 loads from user input. Top of stack points to address/index to load from the given source; load that value and push it onto stack. Since this is a double wide instruction, the instruction pointer skips the instruction used to determine the source.

Top of stack points to address/index to store to. The value below that will be popped and stored in the stack at the given index.

Top of stack is a relative offset to jump to. If the value below that is truthy, then the program jumps by the offset.

Interprets the top of the stack as ascii and pushes the corresponding character.

(10 + N) Pushes the literal number n-10 onto the stack.

Example

Assume the program is:

```<code>chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
(an empty line)
</code>```

(A cat program. Note that the empty line is required because of the preceding line having 6 "chicken".)

Input provided to Chicken program

```<code>Chicken
</code>```

Output

```<code>Chicken
</code>```

The Chicken.js reference implementation.

Error detection

The interpreter should leave an error and terminate when any word not "chicken" is present in the source.

Good luck!

答:
Ruby, 335 bytes

Takes the input file name as a command line argument and takes user input (for instruction #6) from STDIN.

Because of Ruby "truthy" (everything except false and nil) being different from the Javascript "truthy" (Ruby truthy plus 0, empty strings, etc.), there might be some edge cases where programs that work fine on a JS interpreter fail on this one because of instruction #8, such as if "" is on the stack. I've fixed the biggest case, though, which is falsy 0.

Works with the test program and the Hello World program on the Chicken website.

```<code>+(/^(#{c='chicken'}|\s)*$/m=~f=$<.read+"

")
s=[0,STDIN.read]+f.lines.map{|l|l.split.size};s[0]=s;i=1
s<<(s[i]<10?[->{c},->{x,y=s.pop 2;x+y},->{x,y=s.pop 2;x-y},->{s.pop*s.pop},->{s.pop==s.pop},->{s[s[i+=1]][s.pop]},->{s[s.pop]=s.pop;s.pop},->{l,k,j=s.pop 3;i+=j if k&&k!=0;l},->{s.pop.chr}][s[i]-1][]:s[i]-10)while s[i+=1]>0
$><<s.pop
</code>```

Explanation

The interpreter immediately starts off by running a regex match /^(chicken|\s)*$/m against the entire file ($<.read), which makes sure the file contains nothing but chicken and whitespace. In Ruby, this operator returns the index for the match, or nil if it wasn't found.

Two byte-saving tricks are used here: instead of directly matching chicken, the string substitution operator #{} is used instead to also assign that string to a variable for later (saves 1 byte), and when storing the contents of the file to a variable for processing, it appends two newlines to allow the lines function later to naturally append an extra 0 to the end of the instruction set. (Two are needed because of ignored trailing newline, which is necessary for the Chicken program.)

The error used is NoMethodError: undefined method '+@' for nil:NilClass, which is done by wrapping the regex match in parens and putting a + in front. If the file matches the pattern, you get +0, which evaluates to 0 and proceeds normally.

Next, the stack is assembled. The initial list must be created before the self-reference to the stack can be assigned, so a placeholder is used and then replaced. The instruction pointer is set to 1 instead of 2 because post-increment operators don't exist in Ruby.

Finally, it uses the lambda trick from @BassdropCumberwubwubwub to determine what to push on the stack next. If an operation doesn't push anything onto the stack, the interpreter simply pops an extra value so the stack stays the same. (This saves bytes over adding a push operation into every single lambda.)

Ungolfed code:

```<code>f = $<.read + "\n\n"
+(/^(chicken|\s)*$/m =~ f)
s = [0, STDIN.read] + f.lines.map{|l|l.split.size}
s[0] = s
i = 1

while s[i += 1] > 0
    if s[i] < 10
        s.push [
            ->{'chicken'},
            ->{
                x,y = s.pop 2
                x+y
                },
            ->{
                x,y = s.pop 2
                x-y
                },
            ->{s.pop*s.pop},
            ->{s.pop==s.pop},
            ->{s[s[i+=1]][s.pop]},
            ->{s[s.pop]=s.pop;s.pop},
            ->{
                l,k,j=s.pop 3
                i+=j if k&&k!=0
                l
                },
            ->{s.pop.chr}
        ][s[i] - 1][]
    else
        s.push(s[i] - 10)
    end
end

print s.pop
</code>```

Title: Write a chicken interpreter!

Body:
Ruby, 335 bytes

Takes the input file name as a command line argument and takes user input (for instruction #6) from STDIN.

Because of Ruby "truthy" (everything except false and nil) being different from the Javascript "truthy" (Ruby truthy plus 0, empty strings, etc.), there might be some edge cases where programs that work fine on a JS interpreter fail on this one because of instruction #8, such as if "" is on the stack. I've fixed the biggest case, though, which is falsy 0.

Works with the test program and the Hello World program on the Chicken website.

+(/^(#{c='chicken'}|\s)*$/m=~f=$<.read+"

")
s=[0,STDIN.read]+f.lines.map{|l|l.split.size};s[0]=s;i=1
s<<(s[i]<10?[->{c},->{x,y=s.pop 2;x+y},->{x,y=s.pop 2;x-y},->{s.pop*s.pop},->{s.pop==s.pop},->{s[s[i+=1]][s.pop]},->{s[s.pop]=s.pop;s.pop},->{l,k,j=s.pop 3;i+=j if k&&k!=0;l},->{s.pop.chr}][s[i]-1][]:s[i]-10)while s[i+=1]>0
$><<s.pop

Explanation

The interpreter immediately starts off by running a regex match /^(chicken|\s)*$/m against the entire file ($<.read), which makes sure the file contains nothing but chicken and whitespace. In Ruby, this operator returns the index for the match, or nil if it wasn't found.

Two byte-saving tricks are used here: instead of directly matching chicken, the string substitution operator #{} is used instead to also assign that string to a variable for later (saves 1 byte), and when storing the contents of the file to a variable for processing, it appends two newlines to allow the lines function later to naturally append an extra 0 to the end of the instruction set. (Two are needed because of ignored trailing newline, which is necessary for the Chicken program.)

The error used is NoMethodError: undefined method '+@' for nil:NilClass, which is done by wrapping the regex match in parens and putting a + in front. If the file matches the pattern, you get +0, which evaluates to 0 and proceeds normally.

Next, the stack is assembled. The initial list must be created before the self-reference to the stack can be assigned, so a placeholder is used and then replaced. The instruction pointer is set to 1 instead of 2 because post-increment operators don't exist in Ruby.

Finally, it uses the lambda trick from @BassdropCumberwubwubwub to determine what to push on the stack next. If an operation doesn't push anything onto the stack, the interpreter simply pops an extra value so the stack stays the same. (This saves bytes over adding a push operation into every single lambda.)

Ungolfed code:

f = $<.read + "\n\n"
+(/^(chicken|\s)*$/m =~ f)
s = [0, STDIN.read] + f.lines.map{|l|l.split.size}
s[0] = s
i = 1

while s[i += 1] > 0
    if s[i] < 10
        s.push [
            ->{'chicken'},
            ->{
                x,y = s.pop 2
                x+y
                },
            ->{
                x,y = s.pop 2
                x-y
                },
            ->{s.pop*s.pop},
            ->{s.pop==s.pop},
            ->{s[s[i+=1]][s.pop]},
            ->{s[s.pop]=s.pop;s.pop},
            ->{
                l,k,j=s.pop 3
                i+=j if k&&k!=0
                l
                },
            ->{s.pop.chr}
        ][s[i] - 1][]
    else
        s.push(s[i] - 10)
    end
end

print s.pop


问:
If a program terminates and there is no one to see it, does it halt?
It's time to face the truth: We will not be here forever, but at least we can write a program that will outlive the human race even if it struggles till the end of time.

Your task is to write a program that has a expected running time greater than the remaining time till the end of the universe.

You may assume that:

The universe will die from entropy in 101000 years.

Your computer:

Will outlive the universe, because it is made of Unobtainium.

Has infinite memory/stack/recursion limit.

Its processor has limited speed.

You must show that your program terminates (sorry, no infinite loops) and calculate its expected running time.

The standard loopholes apply.

This is a code golf challenge, so the shortest code satisfying the criteria wins.

EDIT:

Unfortunately, it was found (30min later) that the improbability field of Unobtainium interferes with the internal clock of the computer, rendering it useless. So time based programs halt immediately. (Who would leave a program that just waits as its living legacy, anyway?).

The computer processor is similar to the Intel i7-4578U, so one way to measure the running time is to run your program in a similar computer with a smaller input (I hope) and extrapolate its running time.

Podium

#
Chars
Language
Upvotes
Author

1
5
CJam
20
Dennis

2
5
J
5
algorithmshark

3
7
GolfScript
30
Peter Taylor

4
9
Python
39
xnor

5
10
Matlab
5
SchighSchagh

* Upvotes on 31/08

答:
Python 3, 191 Bytes

```<code>from random import*
r=randint
f=lambda n:2if n<2else f(n-1)
x=9E999
s=x**x
for i in range(f(x)**f(s)):
 while exec(("r(0,f(x**i))+"*int(f(x)))+"r(0,f(x**i))")!=0:
  s=f(x**s)
  print(s)
</code>```

First, f is a recursive factorial function and ultra slow.
Then, there is 9*10⁹⁹⁹ powed with itself, which generates an OverflowError, but this doesn't happen on this Unobtanium computer. The For-Loop iterates 9E999! ^ (9E999^9E999)! times and it only goes to the next iteration, if 9E999!+1 random ints between 0 and 9E99*^i! are all 0 and in every iteration of the while-loop s gets set to (9E999^s)!. Uh, I forgot that the printing of s takes muuuuccchhhh time...

I know it's not the shortest soloution, but I think it's really effective. Can someone help me calculating the running time?

ContentLicense: CC BY-SA 4.0

Body:
Python 3, 191 Bytes

from random import*
r=randint
f=lambda n:2if n<2else f(n-1)
x=9E999
s=x**x
for i in range(f(x)**f(s)):
 while exec(("r(0,f(x**i))+"*int(f(x)))+"r(0,f(x**i))")!=0:
  s=f(x**s)
  print(s)

First, f is a recursive factorial function and ultra slow.
Then, there is 9*10⁹⁹⁹ powed with itself, which generates an OverflowError, but this doesn't happen on this Unobtanium computer. The For-Loop iterates 9E999! ^ (9E999^9E999)! times and it only goes to the next iteration, if 9E999!+1 random ints between 0 and 9E99*^i! are all 0 and in every iteration of the while-loop s gets set to (9E999^s)!. Uh, I forgot that the printing of s takes muuuuccchhhh time...

I know it's not the shortest soloution, but I think it's really effective. Can someone help me calculating the running time?


问:
Visualise long multiplication with ASCII art

The challenge

Write a program that takes two integers from standard input, separated by a comma, and then prints a visualisation of long multiplication of those two integers to standard output.

Eg:

Input

```<code>14, 11
</code>```

Program output

```<code>     14
    x11
   _____
     14
    14
  ______
    154
</code>```

Input

```<code>-7, 20
</code>```

Program output

```<code>     -7
    x20
   _____
     00
    14
   _____
   -140
</code>```

Assume always correct inputs and numbers in the range [-999, 999]

Winning criteria

Shortest code wins!

答:
Perl, 108 chars

Best of breed 108 char solution, incorporating some ideas from Orabig.

```<code>($x,$y)=<>=~/[-\d]+/g;printf"%7s
",$_ for$x,x.$y,"-"x7,(map{abs($x*$_).$"x$i++}reverse$y=~/\d/g),"-"x7,$x*$y
</code>```

Earlier 139 char solution

```<code>sub P{sprintf"%*d",@_}
($x,$y)=<>=~/[^,]+/g;$,=$/;
print P(7,$x),"  x".P(4,$y),"-"x7,(map{P 7-$i++,abs$_*$x}reverse$y=~/\d/g),
"-"x7,P 7,$x*$y
</code>```

Body:
Perl, 108 chars

Best of breed 108 char solution, incorporating some ideas from Orabig.

($x,$y)=<>=~/[-\d]+/g;printf"%7s
",$_ for$x,x.$y,"-"x7,(map{abs($x*$_).$"x$i++}reverse$y=~/\d/g),"-"x7,$x*$y

Earlier 139 char solution

sub P{sprintf"%*d",@_}
($x,$y)=<>=~/[^,]+/g;$,=$/;
print P(7,$x),"  x".P(4,$y),"-"x7,(map{P 7-$i++,abs$_*$x}reverse$y=~/\d/g),
"-"x7,P 7,$x*$y


问:
Weapons of Math Instruction
Last time when I tried to come up with something easy that wasn't a duplicate, it ended up being way too hard.. So hopefully this time it's indeed something newcomers can try as well.

Input:

An array/list with integers/decimals. (Or a string representing an array with integers/decimals.)

Output:

Loop through the numbers and apply the following five mathematical operands in this order:

Addition (+);

Subtraction (−);

Multiplication (* or × or ·);

Real / Calculator Division (/ or ÷);

Exponentiation (^ or **).

(NOTE: The symbols between parenthesis are just added as clarification. If your programming language uses a completely different symbol for the mathematical operation than the examples, then that is of course completely acceptable.)

Keep continuing until you've reached the end of the list, and then give the result of the sum.

Challenge rules:

Exponentiation by 0 (n ^ 0) should result in 1 (this also applies to 0 ^ 0 = 1).

There are no test cases for division by 0 (n / 0), so you don't have to worry about that edge-case.

If the array contains just a single number, we return that as the result.

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Test cases:

```<code>[1,2,3,4,5] -> 0
-> 1 + 2 = 3
  -> 3 - 3 = 0
    -> 0 * 4 = 0
      -> 0 / 5 = 0

[5,12,23,2,4,4,2,6,7] -> 539
-> 5 + 12 = 17
  -> 17 - 23 = -6
    -> -6 * 2 = -12
      -> -12 / 4 = -3
        -> -3 ^ 4 = 81
          -> 81 + 2 = 83
            -> 83 - 6 = 77
              -> 77 * 7 -> 539

[-8,50,3,3,-123,4,17,99,13] -> -1055.356...
-> -8 + 50 = 42
  -> 42 - 3 = 39
    -> 39 * 3 = 117
      -> 117 / -123 = -0.9512...
        -> -0.9512... ^ 4 = 0.818...
          -> 0.818... + 17 = 17.818...
            -> 17.818... - 99 -> -81.181...
              -> -81.181... * 13 = -1055.356...

[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] -> 256
-> 2 + 2 = 4
  -> 4 - 2 = 2
    -> 2 * 2 = 4
      -> 4 / 2 = 2
        -> 2 ^ 2 = 4
          -> 4 + 2 = 6
            -> 6 - 2 = 4
              -> 4 * 2 = 8
                -> 8 / 2 = 4
                  -> 4 ^ 2 = 16
                    -> 16 + 2 = 18
                      -> 18 - 2 = 16
                        -> 16 * 2 = 32
                          -> 32 / 2 = 16
                            -> 16 ^ 2 = 256

[1,0,1,0,1,0] -> 1
-> 1 + 0 = 1
  -> 1 - 1 = 0
    -> 0 * 0 = 0
      -> 0 / 1 = 0
        -> 0 ^ 0 = 1

[-9,-8,-1] -> -16
  -> -9 + -8 = -17
    -> -17 - -1 = -16

[0,-3] -> -3
  -> 0 + -3 = -3

[-99] -> -99
</code>```

答:
A few tricks can reduce @Willmore´s approach by 23 to 174 bytes (requires php 5.6 or later). The most saving part is removing unneccessary parentheses (-10 bytes).

 function f($a){while(count($a)>1){$l=array_shift($a);$r=array_shift($a);array_unshift($a,($j=$i++%5)?($j==1?$l-$r:($j==2?$l*$r:($j==3?$l/$r:$l**$r))):$l+$r);}return end($a);}

But using the ** operator instead of pow() also allows to use eval with an array for the operations; and with a few more tricks ...

PHP >= 5.6, 82 bytes

while(--$argc)eval('$x'.['/','**','+','-','*'][$i++?$i%5:2]."=$argv[$i];");echo$x;
```
<p>takes list from command line parameters. Run with <code>php -nr '<code>'</code> or try it online.</p>
<h2>old version, <s>161 157 151 145 144 140 137</s> 117 bytes</h2>
<pre class="lang-php prettyprint-override"><code>function f($a){while(count($a)>1)eval('$a[0]=array_shift($a)'.['+','-','*','/','**'][$i++%5].'$a[0];');return$a[0];}
</code>```

The most effective golfing came from writing the intermediate result directly to the first element - after shifting the previous result from the array.

breakdown

function f($a)
{
    while(count($a)>1)  // while array has more than one element ...
        eval('$a[0]='                           // future first element :=
            . 'array_shift($a)'                 // = old first element (removed)
            . ['+','-','*','/','**'][$i++%5]    // (operation)
            .'$a[0];'                           // new first element (after shift)
        );
    return$a[0];        // return last remaining element
}
```
<p><strong>test suite</strong></p>
<pre class="lang-php prettyprint-override"><code>$cases = array (
    0=>[1,2,3,4,5],
    539=>[5,12,23,2,4,4,2,6,7],
    '-1055.356...' => [-8,50,3,3,-123,4,17,99,13],
    256 => [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
    1 => [1,0,1,0,1,0],
    -16 => [-9,-8,-1],
    -3 => [0, -3],
    -99 => [-99]
);
echo '<table border=1><tr><th>values</th><th>expected</th><th>actual result</th></tr>';
foreach ($cases as $expect=>$a)
{
    $result=f($a);
    echo "<tr><td>[", implode(',',$a),"]</td><td>$expect</td><td>$result</td></tr>";
}
echo '</table>';
</code>```

Title: Weapons of Math Instruction

Body:
A few tricks can reduce @Willmore´s approach by 23 to 174 bytes (requires php 5.6 or later). The most saving part is removing unneccessary parentheses (-10 bytes).

 function f($a){while(count($a)>1){$l=array_shift($a);$r=array_shift($a);array_unshift($a,($j=$i++%5)?($j==1?$l-$r:($j==2?$l*$r:($j==3?$l/$r:$l**$r))):$l+$r);}return end($a);}

But using the ** operator instead of pow() also allows to use eval with an array for the operations; and with a few more tricks ...

PHP >= 5.6, 82 bytes

while(--$argc)eval('$x'.['/','**','+','-','*'][$i++?$i%5:2]."=$argv[$i];");echo$x;

takes list from command line parameters. Run with php -nr '<code>' or try it online.

old version, <s>161 157 151 145 144 140 137</s> 117 bytes

function f($a){while(count($a)>1)eval('$a[0]=array_shift($a)'.['+','-','*','/','**'][$i++%5].'$a[0];');return$a[0];}

The most effective golfing came from writing the intermediate result directly to the first element - after shifting the previous result from the array.

breakdown

function f($a)
{
    while(count($a)>1)  // while array has more than one element ...
        eval('$a[0]='                           // future first element :=
            . 'array_shift($a)'                 // = old first element (removed)
            . ['+','-','*','/','**'][$i++%5]    // (operation)
            .'$a[0];'                           // new first element (after shift)
        );
    return$a[0];        // return last remaining element
}

test suite

$cases = array (
    0=>[1,2,3,4,5],
    539=>[5,12,23,2,4,4,2,6,7],
    '-1055.356...' => [-8,50,3,3,-123,4,17,99,13],
    256 => [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
    1 => [1,0,1,0,1,0],
    -16 => [-9,-8,-1],
    -3 => [0, -3],
    -99 => [-99]
);
echo '<table border=1><tr><th>values</th><th>expected</th><th>actual result</th></tr>';
foreach ($cases as $expect=>$a)
{
    $result=f($a);
    echo "<tr><td>[", implode(',',$a),"]</td><td>$expect</td><td>$result</td></tr>";
}
echo '</table>';


问:
Falling ASCII balls

Input

You are given a 2D map with balls and ground in it.
It looks like this:

```<code>  1         5          2
                 3
     4

__________________________
</code>```

Each number is a ball, and the _ is ground level. The underscore _ character is not allowed in any other line than ground level line. There are only spaces, newlines and digits 0-9 allowed above ground level. You cannot assume that last line is the ground level - empty lines below ground level are allowed. You can also add spaces, to fill empty lines, if that does help you.

Balls can have numbers from 0 to 9, can be placed above each other, but not under ground. The ball's numbers will be unique.

Assume that each character is one meter.

Get map from pastebin!

Test case 1 - should output something like this

Test case 2 - should produce same results as first map

Challenge

Your challenge is to read a map like that from a file or from stdin — you are allowed to use cat balls.txt | ./yourexecutable — and output velocity of each ball when it hits the ground.

Here's the formula for velocity:

Assume that h is the line number difference between the ground's line number, and the ball's line number, and that g equals 10m/s^2.

Output

You should output each balls number and velocity in m/s at ground level.
For example N - Vm/s, where N is ball number and V is its velocity.
You can also output an array if you want.

Happy coding! :)

答:
C -<s>194(-5)</s> <s>150</s> 137 bytes

With a little bit more time and thinking, I golfed off 44 bytes

 Thanks to orlp for helping me to save 13 bytes

I'll start with my C code:

b[256]={},n,i=47;main(l,c){for(;~(c=getchar());n=c==95?l:n)b[c]=(l+=c==10);for(;++i<58;)b[i]&&printf("%d %f\n",i-48,sqrt((n-b[i])*20));}
```
<p>And human readable version:</p>
<pre class="lang-c prettyprint-override"><code>//Throws many warnings, but lack of libraries is tolerated

/*
    c - current character
    l - line number (starts at 1)
    n - ground level
    i - iterator
    b - balls array
*/

b[256] = {}, n, i = 47; //That actually works, as long as you are using ASCII

main( l, c )
{
    for ( ;~( c = getchar( ) ); n = c == 95 ? l : n ) //Read stdin and search for ground
        b[c] = ( l += c == 10 ); //Increment lines counter on newlines, and save line numbers

    for ( ; ++i < 58; ) //Iterate through balls
        b[i] && printf( "%d %f\n", i - 48, sqrt( ( n - b[i] ) * 20 ) ); //Print out data
}
</code>```

Compile and run like that:
gcc -o balls ballsgolf.c -lm && cat 1.txt | ./balls

Output

```<code>1 10.000000
2 10.000000
3 8.944272
4 7.745967
5 10.000000
</code>```

Title: Falling ASCII balls

Body:
C -<s>194(-5)</s> <s>150</s> 137 bytes

With a little bit more time and thinking, I golfed off 44 bytes

 Thanks to orlp for helping me to save 13 bytes

I'll start with my C code:

b[256]={},n,i=47;main(l,c){for(;~(c=getchar());n=c==95?l:n)b[c]=(l+=c==10);for(;++i<58;)b[i]&&printf("%d %f\n",i-48,sqrt((n-b[i])*20));}

And human readable version:

//Throws many warnings, but lack of libraries is tolerated

/*
    c - current character
    l - line number (starts at 1)
    n - ground level
    i - iterator
    b - balls array
*/

b[256] = {}, n, i = 47; //That actually works, as long as you are using ASCII

main( l, c )
{
    for ( ;~( c = getchar( ) ); n = c == 95 ? l : n ) //Read stdin and search for ground
        b[c] = ( l += c == 10 ); //Increment lines counter on newlines, and save line numbers

    for ( ; ++i < 58; ) //Iterate through balls
        b[i] && printf( "%d %f\n", i - 48, sqrt( ( n - b[i] ) * 20 ) ); //Print out data
}

Compile and run like that:
gcc -o balls ballsgolf.c -lm && cat 1.txt | ./balls

Output

1 10.000000
2 10.000000
3 8.944272
4 7.745967
5 10.000000


Title: Falling ASCII balls

Body:
Input

You are given a 2D map with balls and ground in it.
It looks like this:

```<code>  1         5          2
                 3
     4

__________________________
</code>```

Each number is a ball, and the _ is ground level. The underscore _ character is not allowed in any other line than ground level line. There are only spaces, newlines and digits 0-9 allowed above ground level. You cannot assume that last line is the ground level - empty lines below ground level are allowed. You can also add spaces, to fill empty lines, if that does help you.

Balls can have numbers from 0 to 9, can be placed above each other, but not under ground. The ball's numbers will be unique.

Assume that each character is one meter.

Get map from pastebin!

Test case 1 - should output something like this

Test case 2 - should produce same results as first map

Challenge

Your challenge is to read a map like that from a file or from stdin — you are allowed to use cat balls.txt | ./yourexecutable — and output velocity of each ball when it hits the ground.

Here's the formula for velocity:

Assume that h is the line number difference between the ground's line number, and the ball's line number, and that g equals 10m/s^2.

Output

You should output each balls number and velocity in m/s at ground level.
For example N - Vm/s, where N is ball number and V is its velocity.
You can also output an array if you want.

Happy coding! :)

Body:
Pyth, <s>27</s> <s>26</s> <s>25</s> 24 bytes

<s>smf-hT" _".e,b@*20-xd\_k2dC</s>
<s>smf@hT`M;.e,b@*20-xd\_k2dC</s>
<s>smf@T`M;.e,b@*20-xd\_k2dC</s>
sm@#`M;.e,b@*20-xd\_k2dC

Try it online!


Title: Falling ASCII balls

Body:
C, 125 122 121 bytes

b[99]={};main(l,c){for(;(c=getchar())<95u;)b[c]=(l+=c==10);for(c=47;++c<58;)b[c]&&printf("%c,%f\n",c,sqrt((l-b[c])*20));}

Compile & run with gcc -w golf.c -lm && cat balls.txt | ./a.out.


答:
MATL, <s>31</s> <s>30</s> <s>27</s> 25 bytes

```<code>95\16\5B#fG&X>1)b- 20*X^h
</code>```

Input is a 2D char array with ; as row separator:

```<code>['  1         5          2  ';'                 3        ';'     4                    ';'                          ';'                          ';'__________________________']
</code>```

Try it online! Or include an initial t in the code to display the map for greater clarity.

Here are the other test cases: first, second.

Explanation

```<code>95\      % Take input implicitly. Modulo 95: convert to numbers and map '_' into 0
16\      % Modulo 16: map space into 0 and digit chars into corresponding numbers
5B#f     % Find row indices and values of nonzero entries
G        % Push input again
&X>      % Index of maximum of each column. This finds character '_'
1)       % Get first value (they are all equal)
b        % Bubble row indices of numbers up in the stack
-        % Subtract to get distance from each number to the ground
20*X^    % Multiply by 20, take sqrt. This gives the velocity values
h        % Horizontally concat numbers and velocities. Display implicitly
</code>```

Title: Falling ASCII balls

Body:
MATL, <s>31</s> <s>30</s> <s>27</s> 25 bytes

95\16\5B#fG&X>1)b- 20*X^h

Input is a 2D char array with ; as row separator:

['  1         5          2  ';'                 3        ';'     4                    ';'                          ';'                          ';'__________________________']

Try it online! Or include an initial t in the code to display the map for greater clarity.

Here are the other test cases: first, <a href="http://matl.tryitonline.net/#code=OTVcMTZcNUIjZkcmWD4xKWItIDIwKlheaA&input=WycgICAgICAgICAgICAgICAgICAgICAgICAgICc7JyAgICAgICAgICAgICAgICAgICAgICAgICAgJzsnICAxICAgICAgICAgNSAgICAgICAgICAyICAnOycgICAgICAgICAgICAgICAgIDMgICAgICAgICc7JyAgICAgNCAgICAgICAgICAgICAgICAgICAgJzsnICAgICAgICAgICAgICAgICAgICAgICAgICAnOycgICAgICAgICAgICAgICAgICAgICAgICAgICc7J19fX19fX19fX19fX19fX19fX19fX19fX19fJzsnICAgICAgICAgICAgICAgICAgICAgICAgICAnOycgICAgICAgICAgICAgICAgICAgICAgICAgICdd" rel="nofollow noreferrer">second.

Explanation

95\      % Take input implicitly. Modulo 95: convert to numbers and map '_' into 0
16\      % Modulo 16: map space into 0 and digit chars into corresponding numbers
5B#f     % Find row indices and values of nonzero entries
G        % Push input again
&X>      % Index of maximum of each column. This finds character '_'
1)       % Get first value (they are all equal)
b        % Bubble row indices of numbers up in the stack
-        % Subtract to get distance from each number to the ground
20*X^    % Multiply by 20, take sqrt. This gives the velocity values
h        % Horizontally concat numbers and velocities. Display implicitly


问:
Merge two sorted lists

Merge Sort

In this challenge, you will implement the merge subroutine of merge sort. Specifically, you must create a function or program or verb or similar which takes two lists, each sorted in increasing order, and combines them into one list sorted in increasing order.
Requirements:

 - Your algorithm must take an asymptotically linear amount of time in the size of the input. Please stop giving O(n^2) solutions.

You may not use any built-in functions capable of sorting a list, or merging a list, or anything like that. Author's discretion.

The code should be able to handle repeated elements.

Don't worry about empty lists.

Examples:

```<code>merge([1],[0,2,3,4])
[0,1,2,3,4]

merge([1,5,10,17,19],[2,5,9,11,13,20])
[1, 2, 5, 5, 9, 10, 11, 13, 17, 19, 20]
</code>```

This is code-golf, so may the shortest code win!

答:
PHP <s>91 98</s> 91 bytes

edit #1: Empty $b requires an addional condition in the curly braces (+7).

edit #2: minor golfings

edit #3: added second version

pretty straight forward. The nicest part is the ternary inside the array_shift

(which fails if you try it without the curlys)

function m($a,$b){for($c=[];$a|$b;)$c[]=array_shift(${$a&(!$b|$a[0]<$b[0])?a:b});return$c;}
```
<p>or</p>
<pre class="lang-php prettyprint-override"><code>function m($a,$b){for($c=[];$a|$b;)$c[]=array_shift(${$a?!$b|$a[0]<$b[0]?a:b:b});return$c;}
</code>```

ungolfed

function m($a,$b)
{
    $c=[];
    while($a||$b)
    {
        $c[] = array_shift(${
            $a&&(!$b||$a[0]<$b[0])
                ?a
                :b
        });
#       echo '
', outA($a), ' / ', outA($b) , ' -> ', outA($c);
    }
    return $c;
}
```
<p><strong>test</strong></p>
<pre class="lang-php prettyprint-override"><code>$cases = array (
    [1],[0,2,3,4], [0,1,2,3,4],
    [1,5,10,17,19],[2,5,9,11,13,20], [1, 2, 5, 5, 9, 10, 11, 13, 17, 19, 20],
    [1,2,3],[], [1,2,3],
    [],[4,5,6], [4,5,6],
);
function outA($a) { return '['. implode(',',$a). ']'; }
echo '<table border=1><tr><th>A</th><th>B</th><th>expected</th><th>actual result</th></tr>';
while ($cases)
{
    $a = array_shift($cases);
    $b = array_shift($cases);
#   echo '<hr>', outA($a), ' / ', outA($b) , ' -> ', outA($c);
    $expect = array_shift($cases);
    $result=m($a,$b);
    echo '<tr><td>',outA($a),'</td><td>',outA($b),'</td><td>', outA($expect), '</td><td>', outA($result),'</td></tr>';
}
echo '</table>';
</code>```

Title: Merge two sorted lists

Body:
PHP <s>91 98</s> 91 bytes

edit #1: Empty $b requires an addional condition in the curly braces (+7).

edit #2: minor golfings

edit #3: added second version

pretty straight forward. The nicest part is the ternary inside the array_shift

(which fails if you try it without the curlys)

function m($a,$b){for($c=[];$a|$b;)$c[]=array_shift(${$a&(!$b|$a[0]<$b[0])?a:b});return$c;}

or

function m($a,$b){for($c=[];$a|$b;)$c[]=array_shift(${$a?!$b|$a[0]<$b[0]?a:b:b});return$c;}

ungolfed

function m($a,$b)
{
    $c=[];
    while($a||$b)
    {
        $c[] = array_shift(${
            $a&&(!$b||$a[0]<$b[0])
                ?a
                :b
        });
#       echo '<br>', outA($a), ' / ', outA($b) , ' -> ', outA($c);
    }
    return $c;
}

test

$cases = array (
    [1],[0,2,3,4], [0,1,2,3,4],
    [1,5,10,17,19],[2,5,9,11,13,20], [1, 2, 5, 5, 9, 10, 11, 13, 17, 19, 20],
    [1,2,3],[], [1,2,3],
    [],[4,5,6], [4,5,6],
);
function outA($a) { return '['. implode(',',$a). ']'; }
echo '<table border=1><tr><th>A</th><th>B</th><th>expected</th><th>actual result</th></tr>';
while ($cases)
{
    $a = array_shift($cases);
    $b = array_shift($cases);
#   echo '<hr>', outA($a), ' / ', outA($b) , ' -> ', outA($c);
    $expect = array_shift($cases);
    $result=m($a,$b);
    echo '<tr><td>',outA($a),'</td><td>',outA($b),'</td><td>', outA($expect), '</td><td>', outA($result),'</td></tr>';
}
echo '</table>';


问:
Bytes/Character

Task

Given a UTF-8 string (by any means) answer (by any means) an equivalent list where every element is the number of bytes used to encode the corresponding input character.

Examples

! → 1

Ciao → 1 1 1 1

tʃaʊ → 1 2 1 2

Adám → 1 1 2 1

ĉaŭ → 2 1 2 (single characters)

ĉaŭ → 1 2 1 1 2 (uses combining overlays)

チャオ → 3 3 3

 (empty input) →  (empty output)

!±≡ → 1 2 3 4

� (a null byte) → 1

Null bytes

If the only way to keep reading input beyond null bytes is by knowing the total byte count, you may get the byte count by any means (even user input).

If your language cannot handle null bytes at all, you may assume the input does not contain nulls.

答:
Python 3, 82 bytes

```<code>import math
lambda x:[ord(i)<128and 1or int((math.log2(ord(i))-1)//5+1)for i in x]
</code>```

This is much longer than the other Python answer, and the majority of the other answers, but uses an approach involving logarithms that I haven't yet seen.

An anonymous function that takes input, via argument, as a string and returns a list.

Try it on Ideone

How it works

This method relies on the way in which UTF-8 encodes the code-point of a character. If the code-point is less than 128, the character is encoded as in ASCII:

```<code>0xxxxxxx
</code>```

where x represents the bits of the code point. However, for code-points greater than or equal to 128, the first byte is padded with the same number of 1 s as the total number of bytes, and subsequent bytes begin 10. The bits of the code-point are then entered to give the shortest possible multibyte sequence, and any remaining bits become 0.

```<code>No. of bytes  Format
1             0xxxxxxx
2             110xxxxx 10xxxxxx
3             1110xxxx 10xxxxxx 10xxxxxx
4             11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
...           ...
</code>```

and so forth.

It can now be noticed that for each number of bytes n, the upper limit for the number of code-point bits is given by (-n+7)+6(n-1) = 5n+1. Hence, the upper limit code-point c for each n is given, in decimal, by  c= 2^(5n+1). Rearranging this gives n = (log2(c)-1)/5. So for any code-point, the number of bytes can be found by evaluating the above expression, and then taking the ceiling.

However, this does not work for code points in the range 64 <= c <= 127, since the lack of a padding 1 due to the ASCII-like encoding for 1 byte characters means that the wrong upper limit is predicted, and log2 is undefined for c = 0, which happens if a null byte is present in the input. Therefore, if c <= 127, a value of 1 is returned for n.

This is exactly what the code is doing; for each character i in the string x, the code-point is found using the ord function, and the ceiling of the expression is found by using integer rather than float division by 5 and then adding 1. Since Python's float type always represents integers as x.0, even after integer division, the result is passed to the int function to remove the trailing zero. If ord(i) <= 127, logical short-circuiting means that 1 is instead returned. The number of bytes for each character is stored as an element in a list, and this list is returned.

Title: Bytes/Character

Body:
Python 3, 82 bytes

import math
lambda x:[ord(i)<128and 1or int((math.log2(ord(i))-1)//5+1)for i in x]

This is much longer than the other Python answer, and the majority of the other answers, but uses an approach involving logarithms that I haven't yet seen.

An anonymous function that takes input, via argument, as a string and returns a list.

Try it on Ideone

How it works

This method relies on the way in which UTF-8 encodes the code-point of a character. If the code-point is less than 128, the character is encoded as in ASCII:

0xxxxxxx

where x represents the bits of the code point. However, for code-points greater than or equal to 128, the first byte is padded with the same number of 1 s as the total number of bytes, and subsequent bytes begin 10. The bits of the code-point are then entered to give the shortest possible multibyte sequence, and any remaining bits become 0.

No. of bytes  Format
1             0xxxxxxx
2             110xxxxx 10xxxxxx
3             1110xxxx 10xxxxxx 10xxxxxx
4             11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
...           ...

and so forth.

It can now be noticed that for each number of bytes n, the upper limit for the number of code-point bits is given by (-n+7)+6(n-1) = 5n+1. Hence, the upper limit code-point c for each n is given, in decimal, by  c= 2^(5n+1). Rearranging this gives n = (log2(c)-1)/5. So for any code-point, the number of bytes can be found by evaluating the above expression, and then taking the ceiling.

However, this does not work for code points in the range 64 <= c <= 127, since the lack of a padding 1 due to the ASCII-like encoding for 1 byte characters means that the wrong upper limit is predicted, and log2 is undefined for c = 0, which happens if a null byte is present in the input. Therefore, if c <= 127, a value of 1 is returned for n.

This is exactly what the code is doing; for each character i in the string x, the code-point is found using the ord function, and the ceiling of the expression is found by using integer rather than float division by 5 and then adding 1. Since Python's float type always represents integers as x.0, even after integer division, the result is passed to the int function to remove the trailing zero. If ord(i) <= 127, logical short-circuiting means that 1 is instead returned. The number of bytes for each character is stored as an element in a list, and this list is returned.


答:
LISP, 117 bytes

The algorithm ends in n + 1 iterations, where n is the length of the shortest list in input.

```<code>(defun o(a b)(let((c(car a))(d(car b)))(if(null a)b(if(null b)a(if(< c d)(cons c(o(cdr a)b))(cons d(o a(cdr b))))))))
</code>```

Title: Merge two sorted lists

Body:
Merge Sort

In this challenge, you will implement the merge subroutine of merge sort. Specifically, you must create a function or program or verb or similar which takes two lists, each sorted in increasing order, and combines them into one list sorted in increasing order.
Requirements:

 - Your algorithm must take an asymptotically linear amount of time in the size of the input. Please stop giving O(n^2) solutions.

You may not use any built-in functions capable of sorting a list, or merging a list, or anything like that. Author's discretion.

The code should be able to handle repeated elements.

Don't worry about empty lists.

Examples:

```<code>merge([1],[0,2,3,4])
[0,1,2,3,4]

merge([1,5,10,17,19],[2,5,9,11,13,20])
[1, 2, 5, 5, 9, 10, 11, 13, 17, 19, 20]
</code>```

This is code-golf, so may the shortest code win!

Body:
LISP, 117 bytes

The algorithm ends in n + 1 iterations, where n is the length of the shortest list in input.

(defun o(a b)(let((c(car a))(d(car b)))(if(null a)b(if(null b)a(if(< c d)(cons c(o(cdr a)b))(cons d(o a(cdr b))))))))


问:
Calculate the nth term of Golomb's self-describing sequence
Inspired by the previous question.

Golomb's self-describing sequence g(n) is a sequence where any natural number n is repeated within the sequence g(n) times.

The first few numbers in the sequence are:

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

You can see that g(4)=3, and that "4" is repeated 3 times in the sequence.

Given an input of n, output g(n).

Limitations: n < 100000.

Smallest code wins.

答:
PHP

This recursive version is shorter (60) but computationally inefficient:

```<code>function g($n){return$n==1?1:1+g($n-g(g($n-1)));}echo g($n);
</code>```

This is much faster but longer (78):

```<code>$a=[1,2,2];for($i=3;$i<$n;$i++)for($j=0;$j<$a[$i-1];$j++)$a[]=$i;echo$a[$n-1];
</code>```

Much faster, but at 89 characters would be:

```<code>$a=[1,2,2];for($i=3;!isset($a[$n-1]);$i++)for($j=0;$j<$a[$i-1];$j++)$a[]=$i;echo$a[$n-1];
</code>```

Which is O(n)

Body:
PHP

This recursive version is shorter (60) but computationally inefficient:

function g($n){return$n==1?1:1+g($n-g(g($n-1)));}echo g($n);

This is much faster but longer (78):

$a=[1,2,2];for($i=3;$i<$n;$i++)for($j=0;$j<$a[$i-1];$j++)$a[]=$i;echo$a[$n-1];

Much faster, but at 89 characters would be:

$a=[1,2,2];for($i=3;!isset($a[$n-1]);$i++)for($j=0;$j<$a[$i-1];$j++)$a[]=$i;echo$a[$n-1];

Which is O(n)


问:
I only pay with dollars
As the title -- although discretely -- hints, I only pay with dollars.

The challenge

Write a function/program that takes a string as input, which is a monetary value preceded by a symbol. ex) £4.99. Then, return that same amount converted to USD.

Input

You will get a string as input. It will have the currency symbol followed by a number with two decimal places (which could be .00). There will either be decimal points . and/or commas , separating the number. The following currency symbols will come in the inputs:

Euro: €
Pound Sterling: £
Yuan Renminbi: ¥

Also, there will be a comma or decimal point depending on the currency to separate the 'dollars' from the 'cents':

Euro: #.###,##
Pound Sterling: #,###.##
Yuan Renminbi: #,###.##

Output

You will convert the input from the currency determined by the symbol to USD, rounding to two decimal places. The output will be in the format $#,###.##, and there will of course be more numbers on the left of the output if need be (EDIT: this means that there is an arbitrary number of commas in the output, just like in the input). The currency exchange rate we will be using are below.

You can assume that the input contains a symbol that is only one of the above (€ £ ¥ . ,)--that it is always valid.

Exchange rates

```<code>€1 : $1.10
£1 : $1.37
¥1 : $0.15
</code>```

Examples

```<code>Input:
€1,37
£4.00
¥2,782,122.78

Respective output:
$1.51
$5.48
$417,318.42
</code>```

Final words

If you use one of the above symbols (€, £, ¥), you may count them as 1 byte

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

答:
PHP, 117 bytes

```<code>function f($s){return'$'.number_format(ereg_replace('[^0-9]','',substr($s,1))*[E=>.011,P=>.0137,Y=>.0015][$s[0]],2);}
</code>```

This makes use of a deprecated function; replace ereg_replace('[^0-9]' with preg_replace('%[^\d]%' to make the code fully modern; adds 1 byte.

Title: I only pay with dollars

Body:
PHP, 117 bytes

function f($s){return'$'.number_format(ereg_replace('[^0-9]','',substr($s,1))*[E=>.011,P=>.0137,Y=>.0015][$s[0]],2);}

This makes use of a deprecated function; replace ereg_replace('[^0-9]' with preg_replace('%[^\d]%' to make the code fully modern; adds 1 byte.


答:
Matlab, <s>100</s> <s>96</s> <s>89</s> 90  bytes

```<code>s=input('');X=find(s==95);for i=0:9
[x y]=find(s==48+i);if(x)[i sqrt(20*(X(1)-x))]
end
end
</code>```

Many bytes saved thanks to Luis Mendo

Input format:

```<code>['  1         9          2  ';'                 3        ';'     4                    ';'                          ';'                          ';'__________________________']
</code>```

Explanation:

```<code>X=find(s==95)         -- finds '_', we'll need X(1) to determine max height
for i=0:9             -- loops through balls' numbers
[x y]=find(s==48+i)   -- finds the ball
if(x)                 -- if it is present
[i sqrt(20*(X(1)-x))] -- output its number and velocity
</code>```

Title: Falling ASCII balls

Body:
Matlab, <s>100</s> <s>96</s> <s>89</s> 90  bytes

s=input('');X=find(s==95);for i=0:9
[x y]=find(s==48+i);if(x)[i sqrt(20*(X(1)-x))]
end
end

Many bytes saved thanks to Luis Mendo

Input format:

['  1         9          2  ';'                 3        ';'     4                    ';'                          ';'                          ';'__________________________']

Explanation:

X=find(s==95)         -- finds '_', we'll need X(1) to determine max height
for i=0:9             -- loops through balls' numbers
[x y]=find(s==48+i)   -- finds the ball
if(x)                 -- if it is present
[i sqrt(20*(X(1)-x))] -- output its number and velocity


答:
Python 3, 84 bytes

Version 6, 84 bytes: (Thanks to Leaky Nun!)

```<code>lambda a:[(c,(~-(len(a)-i)*20)**.5)for i,s in enumerate(a)for c in s if c.isdigit()]
</code>```

Version 5, 91 bytes:

```<code>lambda a:[c+":"+str((~-(len(a)-i)*20)**.5)for i,s in enumerate(a)for c in s if c.isdigit()]
</code>```

Version 4, 92 bytes:

```<code>lambda i:[c+":"+str((~-(len(i)-n)*20)**.5)for n in range(len(i))for c in i[n]if c.isdigit()]
</code>```

Version 3, 99 bytes:

```<code>def r(i):x=len(i);print([c+":"+str((~-(x-n)*20)**.5)for n in range(x)for c in i[n] if c.isdigit()])
</code>```

Version 2, 102 bytes:

```<code>def r(i):
 n=len(i)
 for l in i:
  for c in l:
   if c.isdigit():print(c+":"+str((~-n*20)**.5))
  n-=1
</code>```

The above versions take an array of strings as input.

Version 1, 140 bytes:

```<code>with open(input(),"r")as i:
 n=sum(1for l in i);i.seek(0)
 for l in i:
  for c in l:
   if c.isdigit():print(c+":"+str((~-n*20)**.5))
  n-=1
</code>```

This takes the directory of the file as input from the user.

Title: Falling ASCII balls

Body:
Python 3, 84 bytes

Version 6, 84 bytes: (Thanks to Leaky Nun!)

lambda a:[(c,(~-(len(a)-i)*20)**.5)for i,s in enumerate(a)for c in s if c.isdigit()]

Version 5, 91 bytes:

lambda a:[c+":"+str((~-(len(a)-i)*20)**.5)for i,s in enumerate(a)for c in s if c.isdigit()]

Version 4, 92 bytes:

lambda i:[c+":"+str((~-(len(i)-n)*20)**.5)for n in range(len(i))for c in i[n]if c.isdigit()]

Version 3, 99 bytes:

def r(i):x=len(i);print([c+":"+str((~-(x-n)*20)**.5)for n in range(x)for c in i[n] if c.isdigit()])

Version 2, 102 bytes:

def r(i):
 n=len(i)
 for l in i:
  for c in l:
   if c.isdigit():print(c+":"+str((~-n*20)**.5))
  n-=1

The above versions take an array of strings as input.

Version 1, 140 bytes:

with open(input(),"r")as i:
 n=sum(1for l in i);i.seek(0)
 for l in i:
  for c in l:
   if c.isdigit():print(c+":"+str((~-n*20)**.5))
  n-=1

This takes the directory of the file as input from the user.


问:
Generating Picture Mazes

Challenge

Write a program/function that accepts an "image" and outputs a picture maze formed from that image.

Input

Your program should accept two arguments:

I, the image to form the maze from

S, a boolean specifying whether or not to display the solution to the maze

I is given in the following form:

```<code>.......
.#####.
.#####.
#######
.#####.
.#####.
.......
</code>```

where #'s are cells to be included in the solution path and .'s are cells to be excluded.
You may swap out the .'s, #'s and newlines with any character of your choosing as long as they differ from each other.
Alternatively, you may accept an actual bitmap of the input image.

Output

Your resulting maze should be in the following form:

```<code>###############
#             #
# ### ####### #
# #.........# #
# #.#######.# #
# #.#.......# #
###.#.#########
....#.#........
#####.#.#######
#  ...#.....  #
# #.#######.# #
# #.........# #
# ####### ### #
#   #       # #
###############
</code>```

where #'s denote walls, .'s denote portions of the path that are part of the solution, and spaces are paths excluded from the solution. The .'s may be replaced by spaces if S is false. Again, characters may be swaped with other characters of your choosing or you may output an actual bitmap of the maze with the solution highlighted.

Additional Details

Paths must be one cell wide (cannot have giant pool of empty space be the path)

The maze must not contain any loops

The maze must be fully connected (all cells must be reachable from the entrance/exit)

The maze must be surrounded by walls (unless its an entrance/exit)

The solution path must not include dead-ends

There must be exactly 1 entrance and 1 exit for the maze

The entrance and exit must be aligned to the edge of the grid and adjacent to a cell included in the solution path

You may choose where the entrance and exit are placed

You may assume that a valid path can be formed from the given input image

(Added for clarification) The diagram below shows how the solution path is correlated to the input image:

```<code>Input (I): |    Output:            |    Corresponding Cells:
           |                       |    (@'s denote #'s from I)
           |                       |
.......    |    ###############    |    ###############
.#####.    |    #             #    |    #             #
.#####.    |    # ### ####### #    |    # ### ####### #
#######    |    # #.........# #    |    # #@.@.@.@.@# #
.#####.    |    # #.#######.# #    |    # #.#######.# #
.#####.    |    # #.#.......# #    |    # #@#@.@.@.@# #
.......    |    ###.#.#########    |    ###.#.#########
           |    ....#.#........    |    .@.@#@#@.@.@.@.
           |    #####.#.#######    |    #####.#.#######
           |    #  ...#.....  #    |    #  @.@#@.@.@  #
           |    # #.#######.# #    |    # #.#######.# #
           |    # #.........# #    |    # #@.@.@.@.@# #
           |    # ####### ### #    |    # ####### ### #
           |    #   #       # #    |    #   #       # #
           |    ###############    |    ###############
           |                       |
</code>```

Test Cases

Watering can example from Wikipedia:

Input:

```<code>..................
..................
.......####.......
......##..##......
.....##....##....#
.....#......#...##
.#############.##.
##..############..
#...###########...
#...##########....
#...##########....
#...##########....
#...##########....
....##########....
....##########....
....##########....
..................
..................
</code>```

Output (S=false):

```<code>#####################################
#   #     #   #   #     #           #
# ### ### ### # # ##### ### ### ### #
#     # #   # # #         # #   # # #
# ### # ##### # ########### # ### # #
# # #         #           # # #   # #
# # # ### ##### # ### ### # ### ### #
#   # # #   #   # # #   # #   # #   #
# ### # ##### ##### ### ##### # # ###
# #   #       #   #   #       # # #
### ####### ### ### # ### ##### ### #
#   #     # #   #   #   # #   # #   #
# ### ##### # ### ####### # # # # # #
# #       #             #   # #   # #
# # ##### ############# ### ### ### #
#   #   #       #     #   # #   # # #
# ### # ####### # ### ### # # ### # #
# # # #         #   # #   #   #     #
# # # ### ######### # # ##### # #####
# #   # # #       # #   #   # # #   #
# ##### # # ##### # ##### # # ### # #
#       # #   #   # #     # #   # # #
# ### ### ### # ### # ##### ####### #
#   # # #     # #   # #       #     #
# # # # ####### # ### # ##### # ### #
  # # # #   #   #     #     # #   # #
### # # # # # ############# # ### # #
#   # # # #   #         #   # #   # #
##### # # ##### ####### # ### ##### #
#     # # #   #       # #   #       #
##### # # # # ####### # ### #########
#     #     #         #       #     #
# ### ######### ############# # #####
# # #   #     # #       #     #     #
# # ######### # ####### ####### ### #
#             #                 #   #
#####################################
</code>```

Output (S=true):

```<code>#####################################
#   #     #   #   #     #           #
# ### ### ### # # ##### ### ### ### #
#     # #   # # #         # #   # # #
# ### # ##### # ########### # ### # #
# # #         #.......    # # #   # #
# # # ### #####.# ###.### # ### ### #
#   # # #   #...# # #...# #   # #   #
# ### # #####.##### ###.##### # # ###
# #   #    ...#   #   #...    # # #..
### #######.### ### # ###.##### ###.#
#   #     #.#   #   #   #.#   # #...#
# ### #####.# ### #######.# # # #.# #
# #.......#.............#...# #...# #
# #.#####.#############.###.###.### #
#...#   #.......#.....#...#.#...# # #
#.### # #######.#.###.###.#.#.### # #
#.# # #  .......#...#.#...#...#     #
#.# # ###.#########.#.#.##### # #####
#.#   # #.#.......#.#...#...# # #   #
#.##### #.#.#####.#.#####.#.# ### # #
#.      #.#...#...#.#.....#.#   # # #
#.### ###.###.#.###.#.#####.####### #
#.  # # #.....#.#...#.#.....  #     #
#.# # # #######.#.###.#.##### # ### #
..# # # #...#...#.....#.....# #   # #
### # # #.#.#.#############.# ### # #
#   # # #.#...#.........#...# #   # #
##### # #.#####.#######.#.### ##### #
#     # #.#...#.......#.#...#       #
##### # #.#.#.#######.#.###.#########
#     #  ...#.........#.....  #     #
# ### ######### ############# # #####
# # #   #     # #       #     #     #
# # ######### # ####### ####### ### #
#             #                 #   #
#####################################
</code>```

Bitmap example (same maze as above):

Input:  Output (S=false):  Output (S=true):

答:
Python 3, 1491 Bytes

I found this to be a fun project and very interesting (and somewhat lengthy). When I saw this, I was reminded of the summer I spent exclusively writing and improving a maze generation algorithm and instantly got to work on this.

After a while, I had an initial draft around 6000 bytes long and I spent the next couple of hours condensing it into the following program:

```<code>import random;R=range;L=len;T=sorted;P=print;N=random.randint;d='#';A=abs
def M(I,S):
 I=I.rsplit('\n');G=[[0]*(1+L(I[0])*2)for i in R(1+L(I)*2)]
 for i in R(L(I)):*G[1::2][i][1::2],=I[i]
 l=L(G[0])-2;c=E(G,l,-2);G[c][-1]=1;e=[c,l];c=E(G,1,2);G[c][:2]=1,1;s=[c,1]
 while s!=e:
  o=[];Q(G,s,e,-2,0,o,0);Q(G,s,e,0,2,o,1);Q(G,s,e,2,0,o,2);Q(G,s,e,0,-2,o,3);o=T(o,key=lambda x:(x[2],-x[1]))[0][0]
  if o==0:G[s[0]-1][s[1]]=1;s[0]-=2
  elif o==1:G[s[0]][s[1]+1]=1;s[1]+=2
  elif o==2:G[s[0]+1][s[1]]=1;s[0]+=2
  else:G[s[0]][s[1]-1]=1;s[1]-=2
  G[s[0]][s[1]]=1
 while 1 in['.'in x for x in G]:
  r=N(1,L(I))*2-1;c=N(1,L(I[0]))*2-1
  if G[r][c]in[1,2]:
   o=[];F(G,r-2,c,o,0);F(G,r,c+2,o,1);F(G,r+2,c,o,2);F(G,r,c-2,o,3)
   try:
    if o[0]==0:G[r-1][c]=2;G[r-2][c]=2
    elif o[0]==1:G[r][c+1]=2;G[r][c+2]=2
    elif o[0]==2:G[r+1][c]=2;G[r+2][c]=2
    else:G[r][c-1]=2;G[r][c-2]=2
   except:0
 *s,='#  '
 if S:s[1]='.'
 for x in G:P(*[s[y]for y in x],sep='')
def Q(G,s,e,x,y,o,a,n=0):
 c=lambda x,y:G[s[0]+x][s[1]+y]is d
 try:
  if c(x,y):
   try:n+=c(2*x,2*y)
   except:0
   try:n+=c(x+A(x)-2,y+A(y)-2)
   except:0
   try:n+=c(x-A(x)+2,y-A(y)+2)
   except:0
   o+=[[a,((s[0]+x-e[0])**2+(s[1]+y-e[1])**2)**.5,n]]
 except:0
def F(G,r,c,o,a):
 try:
  if G[r][c]is'.':o+=[a]
 except:0
def E(G,y,z):
 c=[]
 for x in R(1,L(G)-1,2):
  n=0
  try:n+=G[x-2][y]==d
  except:0
  try:n+=G[x+2][y]==d
  except:0
  n+=G[x][y+z]==d
  if G[x][y]==d:c+=[[x,n]]
 if L(c)>1:c=T(c,key=lambda x:x[1])
 return c[0][0]
</code>```

Which is about as non-sensical to look at as an ascii-art maze is...

It's worth noting that, since the random function is not used until after the correct path has been found, no matter how many times the same input is given, the route from the start to the end will be the same and, while this program does work for the above examples, sometimes it will be unable to find a solution if it 'drives itself into a wall' so to speak.

When running the above examples, it gives this:

```<code>>>> M('''.......
.#####.
.#####.
#######
.#####.
.#####.
.......''',True)
###############
# # #   # #   #
# # # ### # # #
# #...#.....# #
# #.#.#.###.###
#  .#.#.#...# #
###.#.#.#.### #
....#.#.#.#....
# ###.#.#.#.###
# #...#.#.#.  #
# #.###.#.#.# #
# #.....#...# #
### ####### # #
#         # # #
###############
>>>
</code>```

this:

```<code>>>> M('''..................
..................
.......####.......
......##..##......
.....##....##....#
.....#......#...##
.#############.##.
##..############..
#...###########...
#...##########....
#...##########....
#...##########....
#...##########....
....##########....
....##########....
....##########....
..................
..................''',False)
#####################################
# #     #   # # #   # #   # # # # # #
# ### ##### # # # ### # ### # # # # #
#   # # #   #   # # # #   # # #   # #
### # # ### # ### # # # ### # ### # #
# #     #   # #         # # # # # # #
# ### ##### # # ##### ### # # # # # #
# # #   #   #     # #   # # # # # # #
# # # ##### # ##### ### # # # # # # #
# # # #         # # #         #
# # # # # # ##### # ### # ######### #
# #   # # # #   # # # # # # # # #   #
# # ####### # ### # # ### # # # # # #
#         # #           #   #     # #
### ##### # # ######### ### ### ### #
#     #   # # #   #   #     #   # # #
# ### ### # # # # # # ####### ### # #
#   # #   # # # # # # #   #       # #
# ##### # # # # # # # # # # # ##### #
#   #   # # # # # # # # #   #     # #
# ####### # # # # # # # #############
#   #     # # # # # # #         #   #
# ####### # # # # # # ##### ##### # #
#   #     # # # # # #           # # #
# ### ### # # # # # ######### ### ###
    # #   # # # # #         #   #   #
# ### # # # # # # ######### ##### ###
#   # # # # # # #                 # #
# # # ### # # # ################### #
# # # # # # # #               #     #
# ### # # # # ############# ### ### #
# # # #     #                     # #
# # ##### # # # ##### # # ##### ### #
# # #     # # #     # # #     #   # #
### ##### # ### # # # ##### # ### # #
#         #   # # # #     # #   # # #
#####################################
>>>
</code>```

and this:

```<code>>>> M('''..................
..................
.......####.......
......##..##......
.....##....##....#
.....#......#...##
.#############.##.
##..############..
#...###########...
#...##########....
#...##########....
#...##########....
#...##########....
....##########....
....##########....
....##########....
..................
..................''',True)
#####################################
#     #     # #   # # # # # # #     #
##### # # ### ### # # # # # # ### # #
# # # # # # # #     # # # # # # # # #
# # # ### # # ##### # # # # # # # ###
#   # #   # # #.......# #     #   # #
### # ### # # #.#####.# # ####### # #
#   # #   # #...#   #...#   # #   # #
### # ### # #.# # ### #.# ### ### # #
# # # # # #...# #   # #...  # #   #..
# # # # # #.# ### #######.### ### #.#
# #     #  .# #   # # #  .    # #...#
# # #######.##### # # ###.##### #.# #
#  .......#.#...........#...# #...# #
###.# ###.#.#.#########.###.# #.### #
#...# #  .#.#.#...#...#.....#...  # #
#.#######.#.#.#.#.#.#.#######.#######
#.    #  .#.#.#.#.#.#.#...#...#     #
#.#######.#.#.#.#.#.#.#.#.#.### #####
#.    #  .#.#.#.#.#.#.#.#...        #
#.#######.#.#.#.#.#.#.#.#############
#.    # #.#.#.#.#.#.#.#.....        #
#.##### #.#.#.#.#.#.#.#####.#########
#.  #    .#.#.#.#.#.#.......  # #   #
#.# # ###.#.#.#.#.#.########### # ###
..# # #  .#.#.#.#.#.........#   # # #
# # #####.#.#.#.#.#########.# ### # #
# # #    .#.#.#.#...........        #
#########.#.#.#.############### #####
#   #    .#.#.#.............# #     #
### # ###.#.#.#############.# ##### #
#     #  ...#...............      # #
##### # # ### # # # # ### # # ##### #
#     # #   # # # # #   # # #   #   #
####### # ### # # # ##### # ####### #
#       # #   # # #     # #       # #
#####################################
>>>
</code>```

For anyone who'd like to try running this program themselves, use the command M(Image, Show solution). I would recommend using the triple-quotes to input the image since otherwise there'll be a lot of back slashes or newline characters involved.

Title: Generating Picture Mazes

Body:
Python 3, 1491 Bytes

I found this to be a fun project and very interesting (and somewhat lengthy). When I saw this, I was reminded of the summer I spent exclusively writing and improving a maze generation algorithm and instantly got to work on this.

After a while, I had an initial draft around 6000 bytes long and I spent the next couple of hours condensing it into the following program:

import random;R=range;L=len;T=sorted;P=print;N=random.randint;d='#';A=abs
def M(I,S):
 I=I.rsplit('\n');G=[[0]*(1+L(I[0])*2)for i in R(1+L(I)*2)]
 for i in R(L(I)):*G[1::2][i][1::2],=I[i]
 l=L(G[0])-2;c=E(G,l,-2);G[c][-1]=1;e=[c,l];c=E(G,1,2);G[c][:2]=1,1;s=[c,1]
 while s!=e:
  o=[];Q(G,s,e,-2,0,o,0);Q(G,s,e,0,2,o,1);Q(G,s,e,2,0,o,2);Q(G,s,e,0,-2,o,3);o=T(o,key=lambda x:(x[2],-x[1]))[0][0]
  if o==0:G[s[0]-1][s[1]]=1;s[0]-=2
  elif o==1:G[s[0]][s[1]+1]=1;s[1]+=2
  elif o==2:G[s[0]+1][s[1]]=1;s[0]+=2
  else:G[s[0]][s[1]-1]=1;s[1]-=2
  G[s[0]][s[1]]=1
 while 1 in['.'in x for x in G]:
  r=N(1,L(I))*2-1;c=N(1,L(I[0]))*2-1
  if G[r][c]in[1,2]:
   o=[];F(G,r-2,c,o,0);F(G,r,c+2,o,1);F(G,r+2,c,o,2);F(G,r,c-2,o,3)
   try:
    if o[0]==0:G[r-1][c]=2;G[r-2][c]=2
    elif o[0]==1:G[r][c+1]=2;G[r][c+2]=2
    elif o[0]==2:G[r+1][c]=2;G[r+2][c]=2
    else:G[r][c-1]=2;G[r][c-2]=2
   except:0
 *s,='#  '
 if S:s[1]='.'
 for x in G:P(*[s[y]for y in x],sep='')
def Q(G,s,e,x,y,o,a,n=0):
 c=lambda x,y:G[s[0]+x][s[1]+y]is d
 try:
  if c(x,y):
   try:n+=c(2*x,2*y)
   except:0
   try:n+=c(x+A(x)-2,y+A(y)-2)
   except:0
   try:n+=c(x-A(x)+2,y-A(y)+2)
   except:0
   o+=[[a,((s[0]+x-e[0])**2+(s[1]+y-e[1])**2)**.5,n]]
 except:0
def F(G,r,c,o,a):
 try:
  if G[r][c]is'.':o+=[a]
 except:0
def E(G,y,z):
 c=[]
 for x in R(1,L(G)-1,2):
  n=0
  try:n+=G[x-2][y]==d
  except:0
  try:n+=G[x+2][y]==d
  except:0
  n+=G[x][y+z]==d
  if G[x][y]==d:c+=[[x,n]]
 if L(c)>1:c=T(c,key=lambda x:x[1])
 return c[0][0]

Which is about as non-sensical to look at as an ascii-art maze is...

It's worth noting that, since the random function is not used until after the correct path has been found, no matter how many times the same input is given, the route from the start to the end will be the same and, while this program does work for the above examples, sometimes it will be unable to find a solution if it 'drives itself into a wall' so to speak.

When running the above examples, it gives this:

>>> M('''.......
.#####.
.#####.
#######
.#####.
.#####.
.......''',True)
###############
# # #   # #   #
# # # ### # # #
# #...#.....# #
# #.#.#.###.###
#  .#.#.#...# #
###.#.#.#.### #
....#.#.#.#....
# ###.#.#.#.###
# #...#.#.#.  #
# #.###.#.#.# #
# #.....#...# #
### ####### # #
#         # # #
###############
>>>

this:

>>> M('''..................
..................
.......####.......
......##..##......
.....##....##....#
.....#......#...##
.#############.##.
##..############..
#...###########...
#...##########....
#...##########....
#...##########....
#...##########....
....##########....
....##########....
....##########....
..................
..................''',False)
#####################################
# #     #   # # #   # #   # # # # # #
# ### ##### # # # ### # ### # # # # #
#   # # #   #   # # # #   # # #   # #
### # # ### # ### # # # ### # ### # #
# #     #   # #         # # # # # # #
# ### ##### # # ##### ### # # # # # #
# # #   #   #     # #   # # # # # # #
# # # ##### # ##### ### # # # # # # #
# # # #         # # #         #
# # # # # # ##### # ### # ######### #
# #   # # # #   # # # # # # # # #   #
# # ####### # ### # # ### # # # # # #
#         # #           #   #     # #
### ##### # # ######### ### ### ### #
#     #   # # #   #   #     #   # # #
# ### ### # # # # # # ####### ### # #
#   # #   # # # # # # #   #       # #
# ##### # # # # # # # # # # # ##### #
#   #   # # # # # # # # #   #     # #
# ####### # # # # # # # #############
#   #     # # # # # # #         #   #
# ####### # # # # # # ##### ##### # #
#   #     # # # # # #           # # #
# ### ### # # # # # ######### ### ###
    # #   # # # # #         #   #   #
# ### # # # # # # ######### ##### ###
#   # # # # # # #                 # #
# # # ### # # # ################### #
# # # # # # # #               #     #
# ### # # # # ############# ### ### #
# # # #     #                     # #
# # ##### # # # ##### # # ##### ### #
# # #     # # #     # # #     #   # #
### ##### # ### # # # ##### # ### # #
#         #   # # # #     # #   # # #
#####################################
>>>

and this:

>>> M('''..................
..................
.......####.......
......##..##......
.....##....##....#
.....#......#...##
.#############.##.
##..############..
#...###########...
#...##########....
#...##########....
#...##########....
#...##########....
....##########....
....##########....
....##########....
..................
..................''',True)
#####################################
#     #     # #   # # # # # # #     #
##### # # ### ### # # # # # # ### # #
# # # # # # # #     # # # # # # # # #
# # # ### # # ##### # # # # # # # ###
#   # #   # # #.......# #     #   # #
### # ### # # #.#####.# # ####### # #
#   # #   # #...#   #...#   # #   # #
### # ### # #.# # ### #.# ### ### # #
# # # # # #...# #   # #...  # #   #..
# # # # # #.# ### #######.### ### #.#
# #     #  .# #   # # #  .    # #...#
# # #######.##### # # ###.##### #.# #
#  .......#.#...........#...# #...# #
###.# ###.#.#.#########.###.# #.### #
#...# #  .#.#.#...#...#.....#...  # #
#.#######.#.#.#.#.#.#.#######.#######
#.    #  .#.#.#.#.#.#.#...#...#     #
#.#######.#.#.#.#.#.#.#.#.#.### #####
#.    #  .#.#.#.#.#.#.#.#...        #
#.#######.#.#.#.#.#.#.#.#############
#.    # #.#.#.#.#.#.#.#.....        #
#.##### #.#.#.#.#.#.#.#####.#########
#.  #    .#.#.#.#.#.#.......  # #   #
#.# # ###.#.#.#.#.#.########### # ###
..# # #  .#.#.#.#.#.........#   # # #
# # #####.#.#.#.#.#########.# ### # #
# # #    .#.#.#.#...........        #
#########.#.#.#.############### #####
#   #    .#.#.#.............# #     #
### # ###.#.#.#############.# ##### #
#     #  ...#...............      # #
##### # # ### # # # # ### # # ##### #
#     # #   # # # # #   # # #   #   #
####### # ### # # # ##### # ####### #
#       # #   # # #     # #       # #
#####################################
>>>

For anyone who'd like to try running this program themselves, use the command M(Image, Show solution). I would recommend using the triple-quotes to input the image since otherwise there'll be a lot of back slashes or newline characters involved.


问:
"Add one" to every color in an image
You would simply take this image and make every color added one to every hexadecimal digit. For example, #49de5f would become #5aef60 (with the 9 looping to an a, and the f looping to a 0.)

This would also mean that all white (#ffffff) would become black (#000000) because all f loops back to 0, but all black will become a lighter shade of black (#111111).

Scoring is based on the least number of bytes used, as this is a code-golf question.

Use the below image as the input image for your code, and put the output image of your code into your answer.

If you want to, you can also use this other rainbow image:

答:
R, 302 bytes

Far from perfect, but here goes:

```<code>a<-as.raster(imager::load.image(file.choose()));l=letters;n=as.numeric;d=a;f=function(x){if(suppressWarnings(is.na(n(x)))){if(x=="F")"0" else{l[match(x,toupper(l))+1]}}else{if(x==9)"A" else as.character(n(x)+1)}};for(o in 1:90){for(g in 1:200){for(h in 2:7){substr(d[o,g],h,h)<-f(substr(a[o,g],h,h))}}}
</code>```

Explanation:

```<code>a<-as.raster(imager::load.image(file.choose()));  //chooses file
l=letters;n=as.numeric;d=a;                      //shortens some names and creates
                                                   duplicate variable to modify

f=function(x){                                //creates a function that takes in a
   if(suppressWarnings(is.na(n(x)))){            character type and checks whether it is
      if(x=="F")"0"                              a number or letter.
      else{l[match(x,toupper(l))+1]}}            Returns the converted letter or number.
   else{
      if(x==9)"A"
      else as.character(n(x)+1)}
};

for(o in 1:90){                       //loops through every single hex digit and applies
   for(g in 1:200){                     the converting function, modifying the duplicate
      for(h in 2:7){                    variable. Now you have 2 images =D

         substr(d[o,g],h,h)<-f(substr(a[o,g],h,h))

      }
   }
}
</code>```

Title: "Add one" to every color in an image

Body:
R, 302 bytes

Far from perfect, but here goes:

a<-as.raster(imager::load.image(file.choose()));l=letters;n=as.numeric;d=a;f=function(x){if(suppressWarnings(is.na(n(x)))){if(x=="F")"0" else{l[match(x,toupper(l))+1]}}else{if(x==9)"A" else as.character(n(x)+1)}};for(o in 1:90){for(g in 1:200){for(h in 2:7){substr(d[o,g],h,h)<-f(substr(a[o,g],h,h))}}}

Explanation:

a<-as.raster(imager::load.image(file.choose()));  //chooses file
l=letters;n=as.numeric;d=a;                      //shortens some names and creates
                                                   duplicate variable to modify

f=function(x){                                //creates a function that takes in a
   if(suppressWarnings(is.na(n(x)))){            character type and checks whether it is
      if(x=="F")"0"                              a number or letter.
      else{l[match(x,toupper(l))+1]}}            Returns the converted letter or number.
   else{
      if(x==9)"A"
      else as.character(n(x)+1)}
};

for(o in 1:90){                       //loops through every single hex digit and applies
   for(g in 1:200){                     the converting function, modifying the duplicate
      for(h in 2:7){                    variable. Now you have 2 images =D

         substr(d[o,g],h,h)<-f(substr(a[o,g],h,h))

      }
   }
}


Title: I only pay with dollars

Body:
As the title -- although discretely -- hints, I only pay with dollars.

The challenge

Write a function/program that takes a string as input, which is a monetary value preceded by a symbol. ex) £4.99. Then, return that same amount converted to USD.

Input

You will get a string as input. It will have the currency symbol followed by a number with two decimal places (which could be .00). There will either be decimal points . and/or commas , separating the number. The following currency symbols will come in the inputs:

Euro: €
Pound Sterling: £
Yuan Renminbi: ¥

Also, there will be a comma or decimal point depending on the currency to separate the 'dollars' from the 'cents':

Euro: #.###,##
Pound Sterling: #,###.##
Yuan Renminbi: #,###.##

Output

You will convert the input from the currency determined by the symbol to USD, rounding to two decimal places. The output will be in the format $#,###.##, and there will of course be more numbers on the left of the output if need be (EDIT: this means that there is an arbitrary number of commas in the output, just like in the input). The currency exchange rate we will be using are below.

You can assume that the input contains a symbol that is only one of the above (€ £ ¥ . ,)--that it is always valid.

Exchange rates

```<code>€1 : $1.10
£1 : $1.37
¥1 : $0.15
</code>```

Examples

```<code>Input:
€1,37
£4.00
¥2,782,122.78

Respective output:
$1.51
$5.48
$417,318.42
</code>```

Final words

If you use one of the above symbols (€, £, ¥), you may count them as 1 byte

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

Body:
CJam, 54 bytes

'$q(\",."-de-2\"€£¥"#[1.1 1.37 .15]=*2mOs'./~\3/',*'.@

Try it here!


问:
Legen… wait for it…

dary!

In events entirely unrelated to what will hopefully happen to me in the next couple of days, I task you to write code that does the following:

Print

```<code>Legen... wait for it...
</code>```

immediately, with a trailing newline.

Wait until the next full hour (when the cron job for awarding the badge runs).

Print

```<code>dary!
</code>```

with an optional trailing newline.

Additional rules

You may write a program or a function, but the output has to be printed to STDOUT (or its closest alternative of your language).

You have to wait until the next full hour, not just for 60 minutes. If the code is run at 6:58, it should print the second line at 7:00.

The last line must be printed no later than one second after the next full hour.

In the event that the program is started in the first second of a full hour, it should it wait for the next full hour.

You may query local or UTC time.

Standard code-golf rules apply.

答:
Java, 136 bytes

```<code>class a{void A(){System.out.println("Legen... wait for it...");while(System.currentTimeMillis()%3600000!=0);System.out.print("dary!");}}
</code>```

How many milliseconds passed since the last full hour is the result of System.currentTimeMillis() mod 3,600,000.

The equivalent monolithic program is 159 bytes long:

```<code>interface a{static void main(String[]A){System.out.println("Legen... wait for it...");while(System.currentTimeMillis()%3600000!=0);System.out.print("dary!");}}
</code>```

Title: Legen… wait for it…

Body:
Java, 136 bytes

class a{void A(){System.out.println("Legen... wait for it...");while(System.currentTimeMillis()%3600000!=0);System.out.print("dary!");}}

How many milliseconds passed since the last full hour is the result of System.currentTimeMillis() mod 3,600,000.

The equivalent monolithic program is 159 bytes long:

interface a{static void main(String[]A){System.out.println("Legen... wait for it...");while(System.currentTimeMillis()%3600000!=0);System.out.print("dary!");}}


答:
Python 3, 84 bytes

```<code>lambda x:[[i,(20*x[x.find(i):x.find('_')].count('\n'))**.5]for i in x if i.isdigit()]
</code>```

An anonymous function that accepts input by argument as a multi-line string with all empty lines filled with spaces, and returns an array where each element is of the form [ball number, speed].

How it works

```<code>lambda x                      Function with input x
...for i in x if i.isdigit()  Loop through all characters i in x for which i is a digit,
                              and hence one of the balls
x[x.find(i):x.find('_')]      Slice x to give the substring between the ball and the ground
....count('\n')               Count the number of newlines in the substring to give the
                              height of the ball
(20*...)**.5                  Calculate the speed of the ball as it hits the ground
[i,...]                       Package the ball number and speed into a list
:[...]                        Return all ball-speed pairs as a list with elements [ball
                              number, speed]
</code>```

Try it on Ideone

Title: Falling ASCII balls

Body:
Input

You are given a 2D map with balls and ground in it.
It looks like this:

```<code>  1         5          2
                 3
     4

__________________________
</code>```

Each number is a ball, and the _ is ground level. The underscore _ character is not allowed in any other line than ground level line. There are only spaces, newlines and digits 0-9 allowed above ground level. You cannot assume that last line is the ground level - empty lines below ground level are allowed. You can also add spaces, to fill empty lines, if that does help you.

Balls can have numbers from 0 to 9, can be placed above each other, but not under ground. The ball's numbers will be unique.

Assume that each character is one meter.

Get map from pastebin!

Test case 1 - should output something like this

Test case 2 - should produce same results as first map

Challenge

Your challenge is to read a map like that from a file or from stdin — you are allowed to use cat balls.txt | ./yourexecutable — and output velocity of each ball when it hits the ground.

Here's the formula for velocity:

Assume that h is the line number difference between the ground's line number, and the ball's line number, and that g equals 10m/s^2.

Output

You should output each balls number and velocity in m/s at ground level.
For example N - Vm/s, where N is ball number and V is its velocity.
You can also output an array if you want.

Happy coding! :)

Body:
Python 3, 84 bytes

lambda x:[[i,(20*x[x.find(i):x.find('_')].count('\n'))**.5]for i in x if i.isdigit()]

An anonymous function that accepts input by argument as a multi-line string with all empty lines filled with spaces, and returns an array where each element is of the form [ball number, speed].

How it works

lambda x                      Function with input x
...for i in x if i.isdigit()  Loop through all characters i in x for which i is a digit,
                              and hence one of the balls
x[x.find(i):x.find('_')]      Slice x to give the substring between the ball and the ground
....count('\n')               Count the number of newlines in the substring to give the
                              height of the ball
(20*...)**.5                  Calculate the speed of the ball as it hits the ground
[i,...]                       Package the ball number and speed into a list
:[...]                        Return all ball-speed pairs as a list with elements [ball
                              number, speed]

Try it on Ideone