答:
05AB1E, <s>65</s> 63 bytes

Code:

```<code>"+---"17×'+J©,žhAu6£¹J16÷)v„| ?N>iðëN<16B}y«ð17×ðñvy„ |ðJ?}¶?®,
</code>```

Try it online!. Uses CP-1252 encoding.

Title: Code a code page

Body:
Introduction

A code page maps integer values to a specific character. We can visualize a code page like this:

```
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
|   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | q | w | e | r | t | z | u | i | o | p | a | s | d | f | g | j |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 1 | k | l | y | x | c | v | b | n | m | Q | W | E | R | T | Z | U |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 2 | I | O | P | A | S | D | F | G | H | J |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
```

The rows specify the first digit and the columns the second digit of the hex-number.

The Challenge

Given a string of 16-255 unique characters, output the corresponding code page using the zero-based index of each character in the string as it's value.
The input qwertzuiopasdfgjklyxcvbnmQWERTZUIOPASDFGHJ for example would yield the table above.

The output has to be in the exact same format as the table above. Only a trailing newline is optional.

If the input length is not a multiple of 16, you need to start a new row for the remaining characters and leave the unused cells empty (=filled with 3 spaces).

Each character is placed exactly in the middle of a cell, padded by one space to the left and right.

The values in the first row and column are given by hex-numbers with the digits 0123456789ABCDEF. Those are padded with one space to the left and right as well. You may choose to use lowercase hex-digits but you need to stick to one.

The only characters present in the output are hyphens -, pluses +, pipes |, spaces  , the digits for hexadecimal numbers and the characters from the input.

Any builtins that are related to ASCII-art tables or trivialize the problem in any way are forbidden.

You may assume that the input consists only of characters of a specific encoding. Please specify if that is the case.

If your language can only handle ASCII input, you may assume ASCII-only input and repeated characters.

Rules

Function or full program allowed.

Default rules for input/output.

Standard loopholes apply.

This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Happy Coding!

Body:
05AB1E, <s>65</s> 63 bytes

Code:

"+---"17×'+J©,žhAu6£¹J16÷)v„| ?N>iðëN<16B}y«ð17×ðñvy„ |ðJ?}¶?®,

<a href="http://05ab1e.tryitonline.net/#code=IistLS0iMTfDlycrSsKpLMW-aEF1NsKjwrlKMTbDtyl24oCefCA_Tj5pw7DDq048MTZCfXnCq8OwMTfDl8Oww7F2eeKAniB8w7BKP33Ctj_Criw&input=ISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0-P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fiDCocKiwqPCpMKlwqbCp8KowqnCqsKrwqzCrsKvwrDCscKywrPCtMK1wrbCt8K4wrnCusK7wrzCvcK-wr_DgMOBw4LDg8OEw4XDhsOHw4jDicOKw4vDjMONw47Dj8OQw5HDksOTw5TDlcOWw5fDmMOZw5rDm8Ocw53DnsOfw6DDocOiw6PDpMOlw6bDp8Oow6nDqsOrw6zDrcOuw6_DsMOxw7LDs8O0w7XDtsO3w7jDucO6w7vDvMO9w77Dvw" rel="nofollow noreferrer">Try it online!. Uses CP-1252 encoding.


问:
Create output twice the length of the code

The Challenge

Write a complete program that writes twice as many bytes to standard output as the length of the program.

Rules

The program must write ASCII characters to the standard output.

The contents of the output doesn't matter.

The output, measured in bytes, must be exactly twice the length of the program, also measured in bytes, unless you fulfill the bonus.

Any trailing newline is included in the output's byte count.

Bonus

Your program can optionally take a number, n, as input. If so, the output must be exactly n * program length bytes. You can assume that n will always be a positive integer. If no input is provided, n must default to 2.

If you do this,  you can subtract 25 bytes from your score.

Shortest program wins.

Restrictions

No standard loopholes.

The program must be at least 1 byte long.

No adding unnecessary whitespace to the source code to change its length. Similarly, comments don't count.

Unless you fulfill the bonus, the program must accept no input. If you do fulfill the bonus, the integer must be the only input.

Lowest score (program length in bytes - bonus) wins.

The shortest answer for each language wins for that language.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

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 leaderboard snippet:

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

var QUESTION_ID=59436,OVERRIDE_USER=41505;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\-?\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Batch, 17 bytes

```<code>@type %0 %0 2>nul
</code>```

This one does not require a special locale (as the date solution does)

And it does not require %PATH% to be set. (No environment at all, for that matter)

2>nul is required to supress type to output the filenames on stderr (which it does when more than 1 file is printed)

Currently I couldn't conjure up a f(x)=x*N solution that is shorter than 17+25 bytes

This is the best I could come up with:

```<code>@if !%1 == ! (call %0 2) else (for /l %%x in (1,1,%1) do @type %0 2>nul)
</code>```

Which has a score of (72-25) 45 bytes

ContentLicense: CC BY-SA 3.0

Body:
Batch, 17 bytes

@type %0 %0 2>nul

This one does not require a special locale (as the date solution does)

And it does not require %PATH% to be set. (No environment at all, for that matter)

2>nul is required to supress type to output the filenames on stderr (which it does when more than 1 file is printed)

Currently I couldn't conjure up a f(x)=x*N solution that is shorter than 17+25 bytes

This is the best I could come up with:

@if !%1 == ! (call %0 2) else (for /l %%x in (1,1,%1) do @type %0 2>nul)

Which has a score of (72-25) 45 bytes


问:
Tweetable hash function challenge
In this code-challenge you will write a hash function in 140 bytes1 or less of source code. The hash function must take an ASCII string as input, and return a 24-bit unsigned integer ([0, 224-1]) as output.

Your hash function will be evaluated for every word in this large British English dictionary2. Your score is the amount of words that share a hash value with another word (a collision).

The lowest score wins, ties broken by first poster.

Test case

Before submitting, please test your scoring script on the following input:

```<code>duplicate
duplicate
duplicate
duplicate
</code>```

If it gives any score other than 4, it is buggy.

Clarifying rules:

Your hash function must run on a single string, not a whole array. Also, your hash function may not do any other I/O than the input string and output integer.

Built-in hash functions or similar functionality (e.g. encryption to scramble bytes) is disallowed.

Your hash function must be deterministic.

Contrary to most other contests optimizing specifically for the scoring input is allowed.

1 I am aware Twitter limits characters instead of bytes, but for simplicity we will use bytes as a limit for this challenge.

2 Modified from Debian's wbritish-huge, removing any non-ASCII words.

答:
Python, <s>6995</s> <s>6862</s> 6732

Just a simple RSA function. Pretty lame, but beats some answers.

```<code>M=0x5437b3a3b1
P=0x65204c34d
def H(s):
    n=0
    for i in range(len(s)):
        n+=pow(ord(s[i]),P,M)<<i
    return n%(8**8)
</code>```

Title: Tweetable hash function challenge

Body:
Python, <s>6995</s> <s>6862</s> 6732

Just a simple RSA function. Pretty lame, but beats some answers.

M=0x5437b3a3b1
P=0x65204c34d
def H(s):
    n=0
    for i in range(len(s)):
        n+=pow(ord(s[i]),P,M)<<i
    return n%(8**8)


问:
Find the shortest way to advance a counter to a certain number
I have a counter. It's a small device that looks like this:

The display goes from 0000 to 9999. It has a little push-button at the top that increases the count by 1, and a little knob at the right whose purpose is to reset the counter back to 0.

Now, the thing about the little knob is that if you turn it backwards, you can make it increase any digit that you want once you turn it forwards again. So if I push the counter button 10 times so that the counter shows 0010, I can then turn the knob backwards until i hear a tiny click, then turn it forwards again and make it go straight to 0090.

But, the knob will always increase all occurrences of the same digit by 1 every time it pushes numbers forward. So if the counter shows 6060, you can only make it increase to 7070, not to 6070 or 7060. Also, the knob will roll 9s over to 0 without carrying, so 0990 will advance to 0000 instead of 1000 or 1100.

I want to know the most efficient way to set the counter to a certain number. Your task is to write a program or function that will determine the shortest sequence of button pushes and knob advancements required to do so.

Your program will take as input a 4-digit number from 0000 to 9999, and return a series of steps in the following format:

```<code>> 0001
C
> 0093
C12345678C12345678CCC
> 1000
C12345678C12345678C12345678C12345678C12345678C12345678C12345678C
> 9999
012345678
</code>```

Where C stands for "push the counter button" and any digit D from 0 to 9 stands for "use the knob to advance all occurrences of D by 1".

Your program must produce a valid sequence of steps for all possible four-digit combinations, and will be scored by the total number of steps required for all 10,000 cases. In the case of a tie (most likely when the optimal algorithm is found), the shorter code will win.

答:
Mathematica, score 512710

```<code>Unprotect[StringRepeat]
StringRepeat[x_String, 0]:=""
Protect[StringRepeat]
#<>StringRepeat["C",#3-#2*1111]&[Array[ToString@#&,#,0],##]&[If[#<10^3,0,Quotient[#,1111]],#]&
</code>```

Fixes a bug with StringRepeat (behaves incorrectly for StringRepeat[x_String,0])

Body:
Mathematica, score 512710

Unprotect[StringRepeat]
StringRepeat[x_String, 0]:=""
Protect[StringRepeat]
#<>StringRepeat["C",#3-#2*1111]&[Array[ToString@#&,#,0],##]&[If[#<10^3,0,Quotient[#,1111]],#]&

Fixes a bug with StringRepeat (behaves incorrectly for StringRepeat[x_String,0])


答:
Pyth, 327763 steps (optimum, 130 bytes)

Since the online compiler is inept at dealing with such enormous task, I have given it less work, so that it only generates 0, 1, and 1111. However, it can theoretically solve the problem, because it uses the same algorithm as the Lua at the top.

Try it online!

```<code>=Y.d((0k;V53=ZYFGY XZG=k@YG=N%"%04d"GV4=b@NH=di:Nb%"%d"ehibTT XZd.x?>l@Ydlk+kb@Yd+kb)=bhGI<G9999 XZb.x?>l@Yblk+k\C@Yb+k\C))=YZ;@YQ
</code>```

How it works:

```<code>=Y.d((0k;V53=ZYFGY XZG=k@YG=N%"%04d"GV4=b@NH=di:Nb%"%d"ehibTT XZd.x?>l@Ydlk+kb@Yd+kb)=bhGI<G9999 XZb.x?>l@Yblk+k\C@Yb+k\C))=YZ)@YQ
                  assign_copy('Q',eval_input())
=Y.d((0k;         assign_copy('Y',dict(0=k))
V53               for N in range(0,53):
=ZY                   assign_copy('Z',Y)
FGY                   for G in num_to_range(Y):
 XZG=k@YG                 no_print(Z[G] = assign_copy('k',lookup(Y,G)))
=N%"%04d"G                assign_copy('N',format("%04d",G))
V4                        for H in range(0,4):
=b@NH                         assign_copy('b',lookup(N,H))
=di:Nb%"%d"ehibTT             assign_copy('d',base(replace(N,b,format("%d",mod10(increment(base(b,10))))),10))
 XZd.x?>l@Ydlk+kb@Yd+kb       no_print(Z[d]=try_and_catch(greater_than(Plen(lookup(Y,d)),Plen(k)) ? concat(k,b) : lookup(Y,d)), lambda:plus(k,b))
)                         <anti-indent>
=bhG                      assign_copy('b',head(G))
I<G9999                   if less_than(G,9999):
 XZb.x?>l@Yblk+k\C@Yb+k\C     no_print(Z[b]=try_and_catch(greater_than(Plen(lookup(Y,b)),Plen(k)) ? concat(k,"C") : lookup(Y,b)), lambda:plus(k,"C"))
)                         <anti-indent>
)                     <anti-indent>
=YZ                   assign('Y',Z)
)                 <anti-indent>
@YQ               print(lookup(Y,Q))
</code>```

Title: Find the shortest way to advance a counter to a certain number

Body:
I have a counter. It's a small device that looks like this:

The display goes from 0000 to 9999. It has a little push-button at the top that increases the count by 1, and a little knob at the right whose purpose is to reset the counter back to 0.

Now, the thing about the little knob is that if you turn it backwards, you can make it increase any digit that you want once you turn it forwards again. So if I push the counter button 10 times so that the counter shows 0010, I can then turn the knob backwards until i hear a tiny click, then turn it forwards again and make it go straight to 0090.

But, the knob will always increase all occurrences of the same digit by 1 every time it pushes numbers forward. So if the counter shows 6060, you can only make it increase to 7070, not to 6070 or 7060. Also, the knob will roll 9s over to 0 without carrying, so 0990 will advance to 0000 instead of 1000 or 1100.

I want to know the most efficient way to set the counter to a certain number. Your task is to write a program or function that will determine the shortest sequence of button pushes and knob advancements required to do so.

Your program will take as input a 4-digit number from 0000 to 9999, and return a series of steps in the following format:

```<code>> 0001
C
> 0093
C12345678C12345678CCC
> 1000
C12345678C12345678C12345678C12345678C12345678C12345678C12345678C
> 9999
012345678
</code>```

Where C stands for "push the counter button" and any digit D from 0 to 9 stands for "use the knob to advance all occurrences of D by 1".

Your program must produce a valid sequence of steps for all possible four-digit combinations, and will be scored by the total number of steps required for all 10,000 cases. In the case of a tie (most likely when the optimal algorithm is found), the shorter code will win.

Body:
Pyth, 327763 steps (optimum, 130 bytes)

Since the online compiler is inept at dealing with such enormous task, I have given it less work, so that it only generates 0, 1, and 1111. However, it can theoretically solve the problem, because it uses the same algorithm as the Lua at the top.

Try it online!

=Y.d((0k;V53=ZYFGY XZG=k@YG=N%"%04d"GV4=b@NH=di:Nb%"%d"ehibTT XZd.x?>l@Ydlk+kb@Yd+kb)=bhGI<G9999 XZb.x?>l@Yblk+k\C@Yb+k\C))=YZ;@YQ

How it works:

=Y.d((0k;V53=ZYFGY XZG=k@YG=N%"%04d"GV4=b@NH=di:Nb%"%d"ehibTT XZd.x?>l@Ydlk+kb@Yd+kb)=bhGI<G9999 XZb.x?>l@Yblk+k\C@Yb+k\C))=YZ)@YQ
                  assign_copy('Q',eval_input())
=Y.d((0k;         assign_copy('Y',dict(0=k))
V53               for N in range(0,53):
=ZY                   assign_copy('Z',Y)
FGY                   for G in num_to_range(Y):
 XZG=k@YG                 no_print(Z[G] = assign_copy('k',lookup(Y,G)))
=N%"%04d"G                assign_copy('N',format("%04d",G))
V4                        for H in range(0,4):
=b@NH                         assign_copy('b',lookup(N,H))
=di:Nb%"%d"ehibTT             assign_copy('d',base(replace(N,b,format("%d",mod10(increment(base(b,10))))),10))
 XZd.x?>l@Ydlk+kb@Yd+kb       no_print(Z[d]=try_and_catch(greater_than(Plen(lookup(Y,d)),Plen(k)) ? concat(k,b) : lookup(Y,d)), lambda:plus(k,b))
)                         <anti-indent>
=bhG                      assign_copy('b',head(G))
I<G9999                   if less_than(G,9999):
 XZb.x?>l@Yblk+k\C@Yb+k\C     no_print(Z[b]=try_and_catch(greater_than(Plen(lookup(Y,b)),Plen(k)) ? concat(k,"C") : lookup(Y,b)), lambda:plus(k,"C"))
)                         <anti-indent>
)                     <anti-indent>
=YZ                   assign('Y',Z)
)                 <anti-indent>
@YQ               print(lookup(Y,Q))


问:
Shortest code for infinite disk I/O
(Just open 50 tabs in Google Chrome :D (just kidding, no you can't))

Shortest code for infinite disk I/O any language, C# example:

using System.IO;

namespace FileApp {
    static class Program {
        public static void Main() {
            do {
                File.WriteAllText("a", "a");
                File.Delete("a");
            } while (true);
        }
    }
}
```

You can't just fill the entire disk though, as then it would halt in the end and would be finite.

And you can't do reading only, infinite writing has to happen. (It has to kill my SSD after enough runtime.)

Get cracking! :)

答:
C, 40 bytes

```<code>main(){for(;;)write(open("a",1)," ",1);}
</code>```

It will quickly run out of file descriptors, though; this can be overcome with:

<s>45</s>, 43 bytes

```<code>main(f){for(f=open("a",1);;)write(f,"",1);}
</code>```

Title: Shortest code for infinite disk I/O

Body:
C, 40 bytes

main(){for(;;)write(open("a",1)," ",1);}

It will quickly run out of file descriptors, though; this can be overcome with:

<s>45</s>, 43 bytes

main(f){for(f=open("a",1);;)write(f,"",1);}


问:
Open the browser to http://codegolf.stackexchange.com
Your job is to open a browser window of the default browser to http://codegolf.stackexchange.com.

Your code must open the browser itself, and cannot rely on an open one.

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

Moderator note: A large number of answers to this challenge use the URLs http://ppcg.lol or http://ppcg.ga. These URLs did direct to https://codegolf.stackexchange.com at the time, but have since expired. By this meta discussion, they have been allowed to stay, with the note that they are currently invalid.

答:
Python, 44 bytes

```<code>from webbrowser import*;open('http:ppcg.ga')
</code>```

<s>URL from this comment</s>

Edit: ppcg.ga seems to become more popular now (but it WAS available when I posted this answer).

Ungolfed:

```<code>from webbrowser import * # Loads everything in the webbrowser module
open("http://ppcg.ga/") # Opens default browser to http://ppcg.ga/
</code>```

Python, 44 bytes

```<code>from webbrowser import*;open('http:gfa1.tk')
</code>```

URL from this answer

Ungolfed:

```<code>from webbrowser import * # Loads everything in the webbrowser module
open("http://gfa1.tk/") # Opens default browser to http://gfa1.tk/
</code>```

Python, 45 bytes

```<code>from webbrowser import*;open('http:ppcg.lol')
</code>```

Ungolfed:

```<code>from webbrowser import * # Loads everything in the webbrowser module
open('http://ppcg.lol/') # Opens default browser to http://ppcg.lol/
</code>```

Take that, ppcg.lol! (1 byte shorter)

Note: I added a separate answer leading to ppcg.lol, 'cause I've noticed the other sites doesn't work for me in Internet explorer 11, and I saw other users having this problem too.

Both are non-non-competing (read that right?)

ContentLicense: CC BY-SA 4.0

Body:
Python, 44 bytes

from webbrowser import*;open('http:ppcg.ga')

<s>URL from this comment</s>

Edit: ppcg.ga seems to become more popular now (but it WAS available when I posted this answer).

Ungolfed:

from webbrowser import * # Loads everything in the webbrowser module
open("http://ppcg.ga/") # Opens default browser to http://ppcg.ga/

Python, 44 bytes

from webbrowser import*;open('http:gfa1.tk')

URL from this answer

Ungolfed:

from webbrowser import * # Loads everything in the webbrowser module
open("http://gfa1.tk/") # Opens default browser to http://gfa1.tk/

Python, 45 bytes

from webbrowser import*;open('http:ppcg.lol')

Ungolfed:

from webbrowser import * # Loads everything in the webbrowser module
open('http://ppcg.lol/') # Opens default browser to http://ppcg.lol/

Take that, ppcg.lol! (1 byte shorter)

Note: I added a separate answer leading to ppcg.lol, 'cause I've noticed the other sites doesn't work for me in Internet explorer 11, and I saw other users having this problem too.

Both are non-non-competing (read that right?)


问:
Find the treasure in a 2D dungeon
You are in a one-floor dungeon. There is a treasure which is protected by locked doors. Doors can be opened by finding the corresponding keys. Your goal is to find the shortest path to the treasure.

Input

Input will be a two-dimensional grid representing the initial layout of the dungeon.

```<code>###########
#$   #   g#
#    # ####
###G##    #
#    ####C#
#c  @     #
###########
</code>```

This is you: @

These are walls: #

This is the treasure: $

Locked doors are capital letters: A...Z

Each door has a corresponding lower-case key: a...z

There will always be one @ and one $.

The dungeon will always be rectangular.

It is not guaranteed that the outside edge of the dungeon is a wall. This is a valid dungeon:

```<code>  $
A##
@ a
</code>```

It is not guaranteed that the treasure is reachable. Some dungeons may not be solvable.

There may be doors without a key, and there may be keys that do not open any doors.

There will never be duplicate doors or keys.

Output

Your program should print a sequence of R, L, U, D (or 4 other distinct symbols) to represent the shortest possible path to the treasure. Here, RLUD stands for right, left, up, and down, respectively. If there are multiple shortest paths, your program only needs to print one of them.

You cannot move onto a wall.

You cannot move outside of the dungeon boundaries.

You cannot move onto a door without picking up it's key.

Move onto a key to pick it up.

It is not necessary to open every single door.

If it is not possible to reach the treasure through a valid sequence of moves, then your program must terminate without printing anything. (A trailing newline is allowed.)

Scoring

This is code-golf so the answer with the lowest byte count wins.

Test Cases

Each test case will have the height and width of the dungeon on the first line, and one possible path, with the optimal number of moves, on the last line.

```<code>1 2
@$
R (1)

3 3
  $
#Z#
@ z
RRLUUR (6)

3 5
c#d#$
 #C#D
@
UUDDRRUUDDRRUU (14)

7 16
c   # b #  ###@
###     #
  A #####  ####
d #           e
  B    ## #####
###    C   ##
       # a DE $
RDDDDDDL (8)

16 37
#####################################
#    #ijk #a M   ##m##   #    #  R  #
#    #    #  #           #       ####
###J#### ############# ###    #  P b#
#e                       N  h #  ####
##########  ###########  ######     #
#        #  #    $    #  #    #  ####
#  D     H  #         #  #       Q f#
# EcF    #  #####A#####  ######  ####
#  G     #  #####B#####  #          #
#        K  #####C#####  ############
#        #                          #
########### #         #### ##### ####
#     # p   #         # n    #      #
# d         #    @    #     o#   r  #
#################Z###################
UUULLLLLLDDLLLDLLLLLLRRRRRRRRRUUURRRRRRRRRRRRRRRDDLLRRUULLUUUUUUURRRRRUURRRDRRRLLLLULLLLLDDLLLLUULLLUDLLLLLULLLRRRRRDRRRRRRDDLLLLLLLLLLLLDDDLLLLLLLDURRRRRRRRDDDDRRRRRRUUUUU (172)
</code>```

It is not possible to reach the treasure in the following dungeons. For these test cases, there should be no output.

```<code>1 3
@#$

7 11
#a#j#$#i#f#
# #E#F#c#H#
# #K#D#A#G#
#         #
#C#J# #I#B#
#h#d# #L#g#
#l#e#@#b#k#

10 25
#########################
   # fgh  #  # c B b #  #
 $ #      #  #   #   #  #
   ###### #  ##H###E##  #
   #                    #
   #     #########  ##e##
   Z @   D     y #  #   #
   #     #########  F  C#
   #     G          # Ad#
#########################
</code>```

The following snippet can be used to validate answers.

function run() {var dungeonText = document.getElementById("dungeon").value;var dungeonLines = dungeonText.split("\n");var height = dungeonLines.length;var width = dungeonLines[0].length;var dungeon = new Array(height);for (i = 0; i < dungeon.length; i++) {var dungeonLine = dungeonLines[i];if (dungeonLine.length != width) {return error("The dungeon is not rectangular");} dungeon[i] = dungeonLines[i].split("");} var movesText = document.getElementById("moves").value;var moves = movesText.trim().split("");var moveCount = moves.length;var rowAt, colAt;for (r = 0; r < dungeon.length; r++) {for (c = 0; c < dungeon[r].length; c++) {if (dungeon[r][c] == '@') {rowAt = r;colAt = c;}}} var treasure = false;while (moves.length > 0) {var move = moves[0];var row = rowAt,col = colAt;switch (move) {case 'R':col++;break;case 'L':col--;break;case 'U':row--;break;case 'D':row++;break;default:return print(dungeon, moves, "Invalid move");} if (row < 0 || col < 0 || row >= height || col >= width) {return print(dungeon, moves, "Out of bounds");} var target = dungeon[row][col];if (target.match(/[A-Z#]/)) {return print(dungeon, moves, "Path blocked");} if (target.match(/[a-z]/)) {var door = target.toUpperCase();for (r = 0; r < dungeon.length; r++) {for (c = 0; c < dungeon[r].length; c++) {if (dungeon[r][c] == door) {dungeon[r][c] = ' ';}}}} if (target == '$') {treasure = true;} dungeon[row][col] = '@';dungeon[rowAt][colAt] = '.';rowAt = row;colAt = col;moves.shift();} if (treasure) {print(dungeon, moves, "Got the treasure in " + moveCount + " moves!");} else {print(dungeon, moves, "Failed to reach treasure");}} function error(message) {var result = document.getElementById("result");result.innerHTML = message;} function print(dungeon, moves, message) {var output = message + "\n";for (r = 0; r < dungeon.length; r++) {for (c = 0; c < dungeon[r].length; c++) {output += dungeon[r][c];} output += "\n";} for (i = 0; i < moves.length; i++) {output += moves[i];} var result = document.getElementById("result");result.innerHTML = output;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Dungeon:<br/><textarea id="dungeon" name="dungeon" rows="20" cols="40"></textarea><br/>Moves:<br/><textarea id="moves" name="moves" cols="40"></textarea><br/><button id="run" name="run" onclick="run();">Start</button><br/><br/>Result:<br/><textarea id="result" name="result" rows="20" cols="40" disabled></textarea><br/></code>```

答:
Java 8 - <s>1282</s> <s>1277</s> <s>1268</s> <s>1259</s> 1257 bytes

This passes all the tests. However, for some of them it gives some slightly different results (when there is more than one optimal way, which isn't a problem).

For the 4th test, it gives this:

RDDDDDLD
```

<p>Instead of this:</p>

<pre class="lang-none prettyprint-override"><code>RDDDDDDL
</code>```

For the 5th test, it gives this:

LLLLUUULLDDLLLLDLLLLLRRRRRRURRRUURRRRRRRRRRRRRRRDDLLRRUULLUUUUUUURRRRRUURRRDRRRLLLLULLLDDLLLLLLUULLLUDLLLLLULLLRRRRRDRRRRRRDDLLLLLLLLLLLLDDDLLLLLLLDURRRRRRRRDDDDRRRRRRUUUUU
```

<p>Instead of this:</p>

<pre class="lang-none prettyprint-override"><code>UUULLLLLLDDLLLDLLLLLLRRRRRRRRRUUURRRRRRRRRRRRRRRDDLLRRUULLUUUUUUURRRRRUURRRDRRRLLLLULLLLLDDLLLLUULLLUDLLLLLULLLRRRRRDRRRRRRDDLLLLLLLLLLLLDDDLLLLLLLDURRRRRRRRDDDDRRRRRRUUUUU
</code>```

Golfed version:

import java.util.*;class G{int y,w,h,p;String C="",S,o,v;Map m=new HashMap();String q(int a){return a<1?"":"#"+q(a-1);}public static void main(String[]a)throws Exception{new G(new String(java.nio.file.Files.readAllBytes(new java.io.File(a[0]).toPath())));}G(String a){w=(a+"\n").indexOf(10)+3;String t=q(w)+a.replace("\n","##")+q(w);for(char j=65,k=97;j<91;j++,k++){if(t.indexOf(j)*t.indexOf(k)<0)t=t.replace(j,'#').replace(k,' ');}h=t.length()/--w;S=v=q(w*h);t=g(t);if(t!=v)System.out.print(t);}String g(String t){o=(String)m.get(t);if(o!=null)return o;if(t.indexOf(36)<0){if(S.length()>C.length())S=C;return"";}String d="";int f=t.indexOf(64),M[]=new int[w*h],N[]=new int[w*h];Queue<Integer>s=new ArrayDeque();s.add(f);while(!s.isEmpty()){y=s.poll();int[]P={y+1,y-1,y+w,y-w};for(int v:P){char j=t.replaceAll("[A-Z]","#").charAt(v);if(v!=f&j!=35&(N[v]<1|M[y]+1<M[v])){M[v]=M[y]+1;N[v]=y;s.add(v);if(j>32)d+=j;}}}o=d.chars().distinct().mapToObj(e->{String z="",c=C;for(y=t.indexOf(e);y!=f;y=N[y]){p=y-N[y];z=(p==w?"D":p==-w?"U":p==1?"R":"L")+z;}if(S.length()<=(C+z).length())return v;C+=z;String u=g(t.replace('@',' ').replace((char)e,'@').replace((char)(e-32),' '));C=c;return u==v?v:z+u;}).reduce(v,(a,b)->a.length()<b.length()?a:b);m.put(t,o);return o;}}
```

<h1>Ungolfed version</h1>

<p>Features:</p>

<ul>
<li>Informative variable names;</li>
<li>Explicative and detailed comments;</li>
<li>Proper identation.</li>
</ul>

<pre class="lang-java prettyprint-override"><code>import java.util.*;

/**
 * @author Victor Stafusa
 */
class TreasureHunt {

    // Note: on normal (non-golfing programming) those variables should have been scoped properly.
    // They are instance variables just for golfing purposes.
    // On the golfed version, nextCellIndex and waypointCellIndex are the same variable. The same also happens to cachedValue and result. This happens is for golfing purposes.

    int nextCellIndex,
            width,
            height,
            waypointCellIndex,
            cellIndexDifference;

    String previousPath = "",
            bestSolutionSoFar,
            cachedValue,
            result,
            failureFlag;

    // This should be Map<String, String>, but the generics were omitted for golfing.
    // It is needed to avoid recomputing long partial dungeons (i.e. dynamic programming).
    Map cachedResults = new HashMap();

    // Returns a lot of hashes. Like aLotOfHashes(7) will return "#######".
    String aLotOfHashes(int howMany) {
        return howMany < 1 ? "" : "#" + aLotOfHashes(howMany - 1);
    }

    // Here is where our program starts.
    public static void main(String[] args) throws Exception {
        // Read all the content of the file from args[0] and put it into a string.
        // Pass that string as a parameter to the constructor.
        // The instance itself is useless - it is just a golfing trick.
        new TreasureHunt(new String(java.nio.file.Files.readAllBytes(new java.io.File(args[0]).toPath())));
    }

    // Pre-processs the source in order to format it in the way that we want:
    // * No separators between rows. It uses the (row * width + column) formula, so no separators are needed.
    // * An extra layer of wall is added in all sides. This naturally fix up problems about walking out of the edges of the board, wrapping-around or acessing invalid array indexes.
    // This is a constructor just for golfing purposes. Its instances are worthless.
    TreasureHunt(String originalSource) {

        // Finds the width by searching the first line-feed.
        // If there is just one line and no line-feed, the [+ "\n"] will ensure that it will not break.
        // The [+ 3] is because we will add a layer of walls around, so it will be widen by one cell in the left and one in the right (which is +2).
        // We still get one more in the width that will be decremented later to use that in the aLotOfHashes method below.
        // 10 == '\n'.
        width = (originalSource + "\n").indexOf(10) + 3;

        // Add a layer of walls in the top and in the bottom (using a lot of hashes for that).
        // Replaces the line-feed by a pair of walls, representing the rightmost wall of a row and the leftmost row of the following row.
        // Since there is no line-feed before the first line nor after the last line, we add more two walls to fill those.
        String newSource = aLotOfHashes(width) + originalSource.replace("\n", "##") + aLotOfHashes(width);

        // Remove the keys without door (replaces them as blank spaces) and the doors without keys (replaces them with walls.
        // This way, the resulting dungeon will always have matching keys and doors.
        // 65 == 'A', 97 == 'a', 91 == 'z'+1
        for (char door = 65, key = 97; door < 91; door++, key++) {

            // Now a little math trick. For each key or door, we find an index. If the key or door exist, it will be a positive number. Otherwise it will be negative.
            // The result will never be zero, because the zeroey position is filled with part of the layer of wall that we added.
            // If only one of the key and the door exist, the multiplication will be the product of two numbers with opposite signals, i.e. a negative number.
            // Otherwise (both exists or both don't), then the product will be positive.
            // So, if the product is negative, we just remove the key and the door (only one of them will be removed of course, but we don't need to care about which one).
            if (newSource.indexOf(door) * newSource.indexOf(key) < 0) {
                newSource = newSource.replace(door, '#').replace(key, ' ');
            }
        }

        // Knowing the source length and the width (which we fix now), we can easily find out the height.
        height = newSource.length() / --width;

        // Creates a special value for signaling a non-existence of a path. Since they are sorted by length, this must be a sufficiently large string to always be unfavoured.
        bestSolutionSoFar = failureFlag = aLotOfHashes(width * height);

        // Now, do the hard work to solve the dungeon...
        // Note: On the golfed version, newSource and solution are the same variable.
        String solution = solvingRound(newSource);

        // If a solution is found, then show it. Otherwise, we just finish without printing anything.
        // Note: It is unsafe and a bad practice to compare strings in java using == or != instead of the equals method. However, this code manages the trickery.
        if (solution != failureFlag) System.out.print(solution);
    }

    // This does the hard work, finding a solution for a specific dungeon. This is recursive, so the solution of a dungeon involves the partial solution of the dungeon partially solved.
    String solvingRound(String dungeon) {
        // To avoid many redundant computations, check if this particular dungeon was already solved before. If it was, return its cached solution.
        cachedValue = (String) cachedResults.get(dungeon);
        if (cachedValue != null) return cachedValue;

        // If there is no treasure in the dungeon (36 == '$'), this should be because the adventurer reached it, so there is no further moves.
        if (dungeon.indexOf(36) < 0) {
            if (bestSolutionSoFar.length() > previousPath.length()) bestSolutionSoFar = previousPath;
            return "";
        }

        String keysOrTreasureFound = ""; // Initially, we didn't found anything useful.
        int adventurerSpot = dungeon.indexOf(64), // 64 == '@', find the cell index of the adventurer.
                cellDistance[] = new int[width * height],
                previousWaypoint[] = new int[width * height];

        // Use a queue to enqueue cell indexes in order to floodfill all the reachable area starting from the adventurer. Again, screw up the proper user of generics.
        Queue<Integer> floodFillQueue = new ArrayDeque();
        floodFillQueue.add(adventurerSpot); // Seed the queue with the adventurer himself.

        // Each cell thies to populate its neighbours to the queue. However no cell will enter the queue more than once if it is not featuring a better path than before.
        // This way, all the reachable cells will be reached eventually.
        while (!floodFillQueue.isEmpty()) {
            nextCellIndex = floodFillQueue.poll();

            // Locate the four neighbours of this cell.
            // We don't need to bother of checking for wrapping-around or walking into an invalid cell indexes because we added a layer of walls in the beggining,
            // and this layer of wall will ensure that there is always something in each direction from any reachable cell.
            int[] neighbourCells = {nextCellIndex + 1, nextCellIndex - 1, nextCellIndex + width, nextCellIndex - width};

            // For each neighbouring cell...
            for (int neighbourCellIndex : neighbourCells) {
                // Find the cell content. Considers doors as walls.
                char neighbourCellContent = dungeon.replaceAll("[A-Z]", "#").charAt(neighbourCellIndex);

                if (neighbourCellIndex != adventurerSpot // If we are not going back to the start ...
                        & neighbourCellContent != 35 // ... nor walking into a wall or a door that can't be opened (35 == '#') ...
                        & (previousWaypoint[neighbourCellIndex] < 1 // ... and the neighbour cell is either unvisited ...
                            | cellDistance[nextCellIndex] + 1 < cellDistance[neighbourCellIndex])) //  ... or it was visited before but now we found a better path ...
                { // ... then:
                    cellDistance[neighbourCellIndex] = cellDistance[nextCellIndex] + 1; // Update the cell distance.
                    previousWaypoint[neighbourCellIndex] = nextCellIndex; // Update the waypoint so we can track the way from this cell back to the adventurer.
                    floodFillQueue.add(neighbourCellIndex); // Enqueue the cell once again.
                    if (neighbourCellContent > 32) keysOrTreasureFound += neighbourCellContent; // If we found something in this cell (32 == space), take a note about that.
                }
            }
        }

        // Brute force solutions chosing each one of the interesting things that we found and recursively solving the problem as going to that interesting thing.
        // Warning: This has an exponential complexity. Also, if we found something interesting by more than one path, it will compute that redundantly.
        result = keysOrTreasureFound.chars().distinct().mapToObj(keyOrTreasure -> {
            String tracingWay = "", savedPreviousPath = previousPath;

            // From our keyOrTreasure, trace back the path until the adventurer is reached, adding (in reverse order) the steps needed to reach it.
            for (waypointCellIndex = dungeon.indexOf(keyOrTreasure); waypointCellIndex != adventurerSpot; waypointCellIndex = previousWaypoint[waypointCellIndex]) {

                // Use the difference in cell indexes to see if it is going up, down, right or left.
                cellIndexDifference = waypointCellIndex - previousWaypoint[waypointCellIndex];
                tracingWay = (cellIndexDifference == width ? "D" : cellIndexDifference == -width ? "U" : cellIndexDifference == 1 ? "R" : "L") + tracingWay;
            }

            // If this path is going to surely be longer than some other path already found before, prune the search and fail this path.
            if (bestSolutionSoFar.length() <= (previousPath + tracingWay).length()) return failureFlag;

            // Prepare for recursion, recording the current path as part of the next level recursion's previous path.
            previousPath += tracingWay;

            // Now that we traced our way from the adventurer to something interesting, we need to continue our jorney through the remaining items.
            // For that, create a copy of the dungeon, delete the door of the key that we found (if it was a key),
            // move the adventurer to the thing that we just found and recursively solve the resulting simpler problem.
            String nextRoundPartialSolution = solvingRound(dungeon
                        .replace('@', ' ') // Remove the adventurer from where he was...
                        .replace((char) keyOrTreasure, '@') // ... and put him in the spot of the key or treasure.
                        .replace((char) (keyOrTreasure - 32), ' ')); // ... and if it was a key, delete the corresponding door ([- 32] converts lowercase to uppercase, won't do anything in the case of the treasure).

            // Recursion finished. Now, get back the previous path of the previous recursion level.
            previousPath = savedPreviousPath;

            // If the subproblem resulted in a failure, then it is unsolvable. Otherwise, concatenates the subproblem solution to the steps that we took.
            return nextRoundPartialSolution == failureFlag ? failureFlag : tracingWay + nextRoundPartialSolution;

        // From all the paths we took, choose the shorter one.
        }).reduce(failureFlag, (a, b) -> a.length() < b.length() ? a : b);

        // Now that we have the result of this recursion level and solved this particular dungeon instance,
        // cache it to avoid recomputing it all again if the same instance of the dungeon is produced again.
        cachedResults.put(dungeon, result);
        return result;
    }
}
</code>```

Taking input

To run it, try this:

javac G.java
java G ./path/to/file/with/dungeon.txt
```

Or if you are running the ungolfed version, replace the G's with TreasureHunt.

The file should contain the dungeon. The input should not end with a line-feed. Further, it only accepts line-ends in the \n format. It won't work with \r\n or with \r.

Also, it does not validates or sanitizes the input. If the input is malformed, then the behaviour is undefined (likely to throw an exception). If the file can't be found, then an exception will be thrown.

Remarks

My first implementation somewhere near 1100 bytes could not solve the 5th test case in reasonable time. The reason for that is because my implementation it brute-forces all the possible permutations of collectible items (i.e. the keys and the treasure) that are acessible (i.e. not locked in an inacessible room).

In the worst case, with all the 26 keys and the treasure, this would be 27! = 10,888,869,450,418,352,160,768,000,000 different permutations.

The OP did not specified that the answer should be something that runned in reasonable time. However, I consider that this is a loophole that I would not like to exploit. So, I decided to make it run in acceptable time for all the test cases. In order to achieve that, my revised program features pruning in search paths that are proved to be worse than some already know solution. Further, it also caches subsolutions (i.e. dynamic programming) to avoid recomputing many identical dungeons that might arise. With that, it is able to solve the 5th test case in just over one minute in my computer.

The solution is recursive. The idea is first to get the adventurer to some item (a key or the treasure). In case of a key, after the adventurer reaches it, a new similar dungeon is generated with both the key and the door deleted and the adventurer moved to where the key was. With that, the generated simpler dungeon is solved recursively until the point when the treasure is reached or the algorithm concludes that there isn't any reachable item. The order of the items to be visited is brute-forced with pruning and caching as explained above.

The path-finding between the adventurer and the items is made with an algorithm that resembles both floodfill and Dijkstra.

Finally, I suspect that this problem is NP-complete (well, the generalized version of it without a limitation on the number of doors/keys). If this is true, don't expect solutions that optimally solve very large dungeons with miryads of doors and keys in reasonable time. If sub-optimal paths were allowed, then it would be easily tractable with some heuristics (just go to the treasure if possible, otherwise go to the nearest key).

Title: Find the treasure in a 2D dungeon

Body:
Java 8 - <s>1282</s> <s>1277</s> <s>1268</s> <s>1259</s> 1257 bytes

This passes all the tests. However, for some of them it gives some slightly different results (when there is more than one optimal way, which isn't a problem).

For the 4th test, it gives this:

RDDDDDLD

Instead of this:

RDDDDDDL

For the 5th test, it gives this:

LLLLUUULLDDLLLLDLLLLLRRRRRRURRRUURRRRRRRRRRRRRRRDDLLRRUULLUUUUUUURRRRRUURRRDRRRLLLLULLLDDLLLLLLUULLLUDLLLLLULLLRRRRRDRRRRRRDDLLLLLLLLLLLLDDDLLLLLLLDURRRRRRRRDDDDRRRRRRUUUUU

Instead of this:

UUULLLLLLDDLLLDLLLLLLRRRRRRRRRUUURRRRRRRRRRRRRRRDDLLRRUULLUUUUUUURRRRRUURRRDRRRLLLLULLLLLDDLLLLUULLLUDLLLLLULLLRRRRRDRRRRRRDDLLLLLLLLLLLLDDDLLLLLLLDURRRRRRRRDDDDRRRRRRUUUUU

Golfed version:

import java.util.*;class G{int y,w,h,p;String C="",S,o,v;Map m=new HashMap();String q(int a){return a<1?"":"#"+q(a-1);}public static void main(String[]a)throws Exception{new G(new String(java.nio.file.Files.readAllBytes(new java.io.File(a[0]).toPath())));}G(String a){w=(a+"\n").indexOf(10)+3;String t=q(w)+a.replace("\n","##")+q(w);for(char j=65,k=97;j<91;j++,k++){if(t.indexOf(j)*t.indexOf(k)<0)t=t.replace(j,'#').replace(k,' ');}h=t.length()/--w;S=v=q(w*h);t=g(t);if(t!=v)System.out.print(t);}String g(String t){o=(String)m.get(t);if(o!=null)return o;if(t.indexOf(36)<0){if(S.length()>C.length())S=C;return"";}String d="";int f=t.indexOf(64),M[]=new int[w*h],N[]=new int[w*h];Queue<Integer>s=new ArrayDeque();s.add(f);while(!s.isEmpty()){y=s.poll();int[]P={y+1,y-1,y+w,y-w};for(int v:P){char j=t.replaceAll("[A-Z]","#").charAt(v);if(v!=f&j!=35&(N[v]<1|M[y]+1<M[v])){M[v]=M[y]+1;N[v]=y;s.add(v);if(j>32)d+=j;}}}o=d.chars().distinct().mapToObj(e->{String z="",c=C;for(y=t.indexOf(e);y!=f;y=N[y]){p=y-N[y];z=(p==w?"D":p==-w?"U":p==1?"R":"L")+z;}if(S.length()<=(C+z).length())return v;C+=z;String u=g(t.replace('@',' ').replace((char)e,'@').replace((char)(e-32),' '));C=c;return u==v?v:z+u;}).reduce(v,(a,b)->a.length()<b.length()?a:b);m.put(t,o);return o;}}

Ungolfed version

Features:

Informative variable names;

Explicative and detailed comments;

Proper identation.

import java.util.*;

/**
 * @author Victor Stafusa
 */
class TreasureHunt {

    // Note: on normal (non-golfing programming) those variables should have been scoped properly.
    // They are instance variables just for golfing purposes.
    // On the golfed version, nextCellIndex and waypointCellIndex are the same variable. The same also happens to cachedValue and result. This happens is for golfing purposes.

    int nextCellIndex,
            width,
            height,
            waypointCellIndex,
            cellIndexDifference;

    String previousPath = "",
            bestSolutionSoFar,
            cachedValue,
            result,
            failureFlag;

    // This should be Map<String, String>, but the generics were omitted for golfing.
    // It is needed to avoid recomputing long partial dungeons (i.e. dynamic programming).
    Map cachedResults = new HashMap();

    // Returns a lot of hashes. Like aLotOfHashes(7) will return "#######".
    String aLotOfHashes(int howMany) {
        return howMany < 1 ? "" : "#" + aLotOfHashes(howMany - 1);
    }

    // Here is where our program starts.
    public static void main(String[] args) throws Exception {
        // Read all the content of the file from args[0] and put it into a string.
        // Pass that string as a parameter to the constructor.
        // The instance itself is useless - it is just a golfing trick.
        new TreasureHunt(new String(java.nio.file.Files.readAllBytes(new java.io.File(args[0]).toPath())));
    }

    // Pre-processs the source in order to format it in the way that we want:
    // * No separators between rows. It uses the (row * width + column) formula, so no separators are needed.
    // * An extra layer of wall is added in all sides. This naturally fix up problems about walking out of the edges of the board, wrapping-around or acessing invalid array indexes.
    // This is a constructor just for golfing purposes. Its instances are worthless.
    TreasureHunt(String originalSource) {

        // Finds the width by searching the first line-feed.
        // If there is just one line and no line-feed, the [+ "\n"] will ensure that it will not break.
        // The [+ 3] is because we will add a layer of walls around, so it will be widen by one cell in the left and one in the right (which is +2).
        // We still get one more in the width that will be decremented later to use that in the aLotOfHashes method below.
        // 10 == '\n'.
        width = (originalSource + "\n").indexOf(10) + 3;

        // Add a layer of walls in the top and in the bottom (using a lot of hashes for that).
        // Replaces the line-feed by a pair of walls, representing the rightmost wall of a row and the leftmost row of the following row.
        // Since there is no line-feed before the first line nor after the last line, we add more two walls to fill those.
        String newSource = aLotOfHashes(width) + originalSource.replace("\n", "##") + aLotOfHashes(width);

        // Remove the keys without door (replaces them as blank spaces) and the doors without keys (replaces them with walls.
        // This way, the resulting dungeon will always have matching keys and doors.
        // 65 == 'A', 97 == 'a', 91 == 'z'+1
        for (char door = 65, key = 97; door < 91; door++, key++) {

            // Now a little math trick. For each key or door, we find an index. If the key or door exist, it will be a positive number. Otherwise it will be negative.
            // The result will never be zero, because the zeroey position is filled with part of the layer of wall that we added.
            // If only one of the key and the door exist, the multiplication will be the product of two numbers with opposite signals, i.e. a negative number.
            // Otherwise (both exists or both don't), then the product will be positive.
            // So, if the product is negative, we just remove the key and the door (only one of them will be removed of course, but we don't need to care about which one).
            if (newSource.indexOf(door) * newSource.indexOf(key) < 0) {
                newSource = newSource.replace(door, '#').replace(key, ' ');
            }
        }

        // Knowing the source length and the width (which we fix now), we can easily find out the height.
        height = newSource.length() / --width;

        // Creates a special value for signaling a non-existence of a path. Since they are sorted by length, this must be a sufficiently large string to always be unfavoured.
        bestSolutionSoFar = failureFlag = aLotOfHashes(width * height);

        // Now, do the hard work to solve the dungeon...
        // Note: On the golfed version, newSource and solution are the same variable.
        String solution = solvingRound(newSource);

        // If a solution is found, then show it. Otherwise, we just finish without printing anything.
        // Note: It is unsafe and a bad practice to compare strings in java using == or != instead of the equals method. However, this code manages the trickery.
        if (solution != failureFlag) System.out.print(solution);
    }

    // This does the hard work, finding a solution for a specific dungeon. This is recursive, so the solution of a dungeon involves the partial solution of the dungeon partially solved.
    String solvingRound(String dungeon) {
        // To avoid many redundant computations, check if this particular dungeon was already solved before. If it was, return its cached solution.
        cachedValue = (String) cachedResults.get(dungeon);
        if (cachedValue != null) return cachedValue;

        // If there is no treasure in the dungeon (36 == '$'), this should be because the adventurer reached it, so there is no further moves.
        if (dungeon.indexOf(36) < 0) {
            if (bestSolutionSoFar.length() > previousPath.length()) bestSolutionSoFar = previousPath;
            return "";
        }

        String keysOrTreasureFound = ""; // Initially, we didn't found anything useful.
        int adventurerSpot = dungeon.indexOf(64), // 64 == '@', find the cell index of the adventurer.
                cellDistance[] = new int[width * height],
                previousWaypoint[] = new int[width * height];

        // Use a queue to enqueue cell indexes in order to floodfill all the reachable area starting from the adventurer. Again, screw up the proper user of generics.
        Queue<Integer> floodFillQueue = new ArrayDeque();
        floodFillQueue.add(adventurerSpot); // Seed the queue with the adventurer himself.

        // Each cell thies to populate its neighbours to the queue. However no cell will enter the queue more than once if it is not featuring a better path than before.
        // This way, all the reachable cells will be reached eventually.
        while (!floodFillQueue.isEmpty()) {
            nextCellIndex = floodFillQueue.poll();

            // Locate the four neighbours of this cell.
            // We don't need to bother of checking for wrapping-around or walking into an invalid cell indexes because we added a layer of walls in the beggining,
            // and this layer of wall will ensure that there is always something in each direction from any reachable cell.
            int[] neighbourCells = {nextCellIndex + 1, nextCellIndex - 1, nextCellIndex + width, nextCellIndex - width};

            // For each neighbouring cell...
            for (int neighbourCellIndex : neighbourCells) {
                // Find the cell content. Considers doors as walls.
                char neighbourCellContent = dungeon.replaceAll("[A-Z]", "#").charAt(neighbourCellIndex);

                if (neighbourCellIndex != adventurerSpot // If we are not going back to the start ...
                        & neighbourCellContent != 35 // ... nor walking into a wall or a door that can't be opened (35 == '#') ...
                        & (previousWaypoint[neighbourCellIndex] < 1 // ... and the neighbour cell is either unvisited ...
                            | cellDistance[nextCellIndex] + 1 < cellDistance[neighbourCellIndex])) //  ... or it was visited before but now we found a better path ...
                { // ... then:
                    cellDistance[neighbourCellIndex] = cellDistance[nextCellIndex] + 1; // Update the cell distance.
                    previousWaypoint[neighbourCellIndex] = nextCellIndex; // Update the waypoint so we can track the way from this cell back to the adventurer.
                    floodFillQueue.add(neighbourCellIndex); // Enqueue the cell once again.
                    if (neighbourCellContent > 32) keysOrTreasureFound += neighbourCellContent; // If we found something in this cell (32 == space), take a note about that.
                }
            }
        }

        // Brute force solutions chosing each one of the interesting things that we found and recursively solving the problem as going to that interesting thing.
        // Warning: This has an exponential complexity. Also, if we found something interesting by more than one path, it will compute that redundantly.
        result = keysOrTreasureFound.chars().distinct().mapToObj(keyOrTreasure -> {
            String tracingWay = "", savedPreviousPath = previousPath;

            // From our keyOrTreasure, trace back the path until the adventurer is reached, adding (in reverse order) the steps needed to reach it.
            for (waypointCellIndex = dungeon.indexOf(keyOrTreasure); waypointCellIndex != adventurerSpot; waypointCellIndex = previousWaypoint[waypointCellIndex]) {

                // Use the difference in cell indexes to see if it is going up, down, right or left.
                cellIndexDifference = waypointCellIndex - previousWaypoint[waypointCellIndex];
                tracingWay = (cellIndexDifference == width ? "D" : cellIndexDifference == -width ? "U" : cellIndexDifference == 1 ? "R" : "L") + tracingWay;
            }

            // If this path is going to surely be longer than some other path already found before, prune the search and fail this path.
            if (bestSolutionSoFar.length() <= (previousPath + tracingWay).length()) return failureFlag;

            // Prepare for recursion, recording the current path as part of the next level recursion's previous path.
            previousPath += tracingWay;

            // Now that we traced our way from the adventurer to something interesting, we need to continue our jorney through the remaining items.
            // For that, create a copy of the dungeon, delete the door of the key that we found (if it was a key),
            // move the adventurer to the thing that we just found and recursively solve the resulting simpler problem.
            String nextRoundPartialSolution = solvingRound(dungeon
                        .replace('@', ' ') // Remove the adventurer from where he was...
                        .replace((char) keyOrTreasure, '@') // ... and put him in the spot of the key or treasure.
                        .replace((char) (keyOrTreasure - 32), ' ')); // ... and if it was a key, delete the corresponding door ([- 32] converts lowercase to uppercase, won't do anything in the case of the treasure).

            // Recursion finished. Now, get back the previous path of the previous recursion level.
            previousPath = savedPreviousPath;

            // If the subproblem resulted in a failure, then it is unsolvable. Otherwise, concatenates the subproblem solution to the steps that we took.
            return nextRoundPartialSolution == failureFlag ? failureFlag : tracingWay + nextRoundPartialSolution;

        // From all the paths we took, choose the shorter one.
        }).reduce(failureFlag, (a, b) -> a.length() < b.length() ? a : b);

        // Now that we have the result of this recursion level and solved this particular dungeon instance,
        // cache it to avoid recomputing it all again if the same instance of the dungeon is produced again.
        cachedResults.put(dungeon, result);
        return result;
    }
}

Taking input

To run it, try this:

javac G.java
java G ./path/to/file/with/dungeon.txt

Or if you are running the ungolfed version, replace the G's with TreasureHunt.

The file should contain the dungeon. The input should not end with a line-feed. Further, it only accepts line-ends in the \n format. It won't work with \r\n or with \r.

Also, it does not validates or sanitizes the input. If the input is malformed, then the behaviour is undefined (likely to throw an exception). If the file can't be found, then an exception will be thrown.

Remarks

My first implementation somewhere near 1100 bytes could not solve the 5th test case in reasonable time. The reason for that is because my implementation it brute-forces all the possible permutations of collectible items (i.e. the keys and the treasure) that are acessible (i.e. not locked in an inacessible room).

In the worst case, with all the 26 keys and the treasure, this would be 27! = 10,888,869,450,418,352,160,768,000,000 different permutations.

The OP did not specified that the answer should be something that runned in reasonable time. However, I consider that this is a loophole that I would not like to exploit. So, I decided to make it run in acceptable time for all the test cases. In order to achieve that, my revised program features pruning in search paths that are proved to be worse than some already know solution. Further, it also caches subsolutions (i.e. dynamic programming) to avoid recomputing many identical dungeons that might arise. With that, it is able to solve the 5th test case in just over one minute in my computer.

The solution is recursive. The idea is first to get the adventurer to some item (a key or the treasure). In case of a key, after the adventurer reaches it, a new similar dungeon is generated with both the key and the door deleted and the adventurer moved to where the key was. With that, the generated simpler dungeon is solved recursively until the point when the treasure is reached or the algorithm concludes that there isn't any reachable item. The order of the items to be visited is brute-forced with pruning and caching as explained above.

The path-finding between the adventurer and the items is made with an algorithm that resembles both floodfill and Dijkstra.

Finally, I suspect that this problem is NP-complete (well, the generalized version of it without a limitation on the number of doors/keys). If this is true, don't expect solutions that optimally solve very large dungeons with miryads of doors and keys in reasonable time. If sub-optimal paths were allowed, then it would be easily tractable with some heuristics (just go to the treasure if possible, otherwise go to the nearest key).


问:
Optimal solution to go to opposite corner of a rectangle
Your job is to write a program that finds the optimal number of moves it takes to get from the lower-left corner of a rectangle to the upper-right corner directly opposite.

Your program will accept input as an ordered pair (width, height). These will be the dimensions of the rectangle you will work with. Your program will create an ASCII-art of the solution (use . for empty square and # for part of the solution, X for starting square) and count the number of moves it takes to reach the endpoint. Diagonal moves are not allowed. If there are multiple solutions, choose one to output.

The shortest program in bytes wins.

Example

Input: (4, 5)

Output:

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

Move count: 7

答:
CJam, <s>35</s> 33 bytes

```<code>q~\(_2$(+p'.*a*'#f+)W%_"X#"era+N*
</code>```

Takes input in the form width height and outputs the move count on the first line, followed by the solution grid.

Test it here.

This also works for the same byte count:

```<code>q~\('.*a*'#f+)W%_"X#"era+N*_'#e=p
</code>```

Body:
CJam, <s>35</s> 33 bytes

q~\(_2$(+p'.*a*'#f+)W%_"X#"era+N*

Takes input in the form width height and outputs the move count on the first line, followed by the solution grid.

Test it here.

This also works for the same byte count:

q~\('.*a*'#f+)W%_"X#"era+N*_'#e=p


答:
Retina, <s>54</s> 53 bytes

```<code>\d+
$*.
S_`(?<=(.+)¶.*).|\D
T`.`#`.¶|.*$
:m-1=`^#
X
#
</code>```

Takes input separated by a linefeed and outputs the solution grid followed by the move count.

Try it online!

Explanation

```<code>\d+
$*.
</code>```

Turn both integers into that many .s, i.e. convert them to unary.

```<code>S_`(?<=(.+)¶.*).|\D
</code>```

This builds a grid of .s, by matching each . in the unary height and capturing the unary representation of the width. The S activates split mode which returns the captured strings, and the |\D and _ together ensure that everything else is removed from the string.

```<code>T`.`#`.¶|.*$
</code>```

This turns the last character of each line as well as the entire last line into #s.

```<code>:m-1=`^#
X
</code>```

This uses a ton of options to convert only the first # on the last row to X (we need to make sure that only the last row is affected because of width-1 inputs). m activates multi-line mode which makes ^ match the beginning of lines. -1= tells Retina to perform the substitution only on the last match. Finally, : switches off the default silent mode such that the grid is printed to STDOUT as an intermediate result.

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

Finally, we simply count the number # in the string, which corresponds to the number of moves.

Title: Optimal solution to go to opposite corner of a rectangle

Body:
Your job is to write a program that finds the optimal number of moves it takes to get from the lower-left corner of a rectangle to the upper-right corner directly opposite.

Your program will accept input as an ordered pair (width, height). These will be the dimensions of the rectangle you will work with. Your program will create an ASCII-art of the solution (use . for empty square and # for part of the solution, X for starting square) and count the number of moves it takes to reach the endpoint. Diagonal moves are not allowed. If there are multiple solutions, choose one to output.

The shortest program in bytes wins.

Example

Input: (4, 5)

Output:

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

Move count: 7

Body:
Retina, <s>54</s> 53 bytes

\d+
$*.
S_`(?<=(.+)¶.*).|\D
T`.`#`.¶|.*$
:m-1=`^#
X
#

Takes input separated by a linefeed and outputs the solution grid followed by the move count.

Try it online!

Explanation

\d+
$*.

Turn both integers into that many .s, i.e. convert them to unary.

S_`(?<=(.+)¶.*).|\D

This builds a grid of .s, by matching each . in the unary height and capturing the unary representation of the width. The S activates split mode which returns the captured strings, and the |\D and _ together ensure that everything else is removed from the string.

T`.`#`.¶|.*$

This turns the last character of each line as well as the entire last line into #s.

:m-1=`^#
X

This uses a ton of options to convert only the first # on the last row to X (we need to make sure that only the last row is affected because of width-1 inputs). m activates multi-line mode which makes ^ match the beginning of lines. -1= tells Retina to perform the substitution only on the last match. Finally, : switches off the default silent mode such that the grid is printed to STDOUT as an intermediate result.

#

Finally, we simply count the number # in the string, which corresponds to the number of moves.


答:
Pyth, <s>32</s> <s>29</s> 24 bytes

```<code>AtMQVH+*\.G\#;+\X*\#G+GH
</code>```

Try it online!

Sample input:

```<code>(4, 5)
</code>```

Sample output:

```<code>...#
...#
...#
...#
X###
7
</code>```

How it works:

```<code>AtMQVH+*\.G\#;+\X*\#G+GH
                           assign('Q',eval_input())
AtMQ                       assign('[G,H]',Pmap(lambda d:tail(d),Q))
    VH       ;             for N in range(H):
      +*\.G\#                  implicit_print(plus(times(".",G),"#"))
              +\X*\#G      implicit_print(plus("X",times("#",G)))
                     +GH   implicit_print(plus(G,H))
</code>```

Previous attempt:

```<code>JthQK@Q1+*++*\.J\#btK+\X*\#Jt+JK
</code>```

Try it online!

Sample input:

```<code>(4, 5)
</code>```

Sample output:

```<code>...#
...#
...#
...#
X###
7
</code>```

How it works:

```<code>JthQK@Q1+*++*\.J\#btK+\X*\#Jt+JK
                                 assign('Q',eval_input())        --Q is now an official pair of numbers (4, 5)
JthQ                             assign("J",decrement(first(Q))) --gets the first element, and then take 1 from it, and assign it to J
    K@Q1                         assign("K",lookup(Q,1))         --K is now the second element (count from 0) of the pair.
        +            +\X*\#J     concat(-----------------------------------------------------------,concat("X",times("#",J)))
         *         tK                   repeat(--------------------------------------,decrement(K))
          +       b                            concat(-------------------------,"\n")
           +    \#                                    concat(-------------,"#")
            *\.J                                             repeat(".",J)
                            t+JK decrement(add(J,K)) <--- auto-print
</code>```

Body:
Pyth, <s>32</s> <s>29</s> 24 bytes

AtMQVH+*\.G\#;+\X*\#G+GH

Try it online!

Sample input:

(4, 5)

Sample output:

...#
...#
...#
...#
X###
7

How it works:

AtMQVH+*\.G\#;+\X*\#G+GH
                           assign('Q',eval_input())
AtMQ                       assign('[G,H]',Pmap(lambda d:tail(d),Q))
    VH       ;             for N in range(H):
      +*\.G\#                  implicit_print(plus(times(".",G),"#"))
              +\X*\#G      implicit_print(plus("X",times("#",G)))
                     +GH   implicit_print(plus(G,H))

Previous attempt:

JthQK@Q1+*++*\.J\#btK+\X*\#Jt+JK

Try it online!

Sample input:

(4, 5)

Sample output:

...#
...#
...#
...#
X###
7

How it works:

JthQK@Q1+*++*\.J\#btK+\X*\#Jt+JK
                                 assign('Q',eval_input())        --Q is now an official pair of numbers (4, 5)
JthQ                             assign("J",decrement(first(Q))) --gets the first element, and then take 1 from it, and assign it to J
    K@Q1                         assign("K",lookup(Q,1))         --K is now the second element (count from 0) of the pair.
        +            +\X*\#J     concat(-----------------------------------------------------------,concat("X",times("#",J)))
         *         tK                   repeat(--------------------------------------,decrement(K))
          +       b                            concat(-------------------------,"\n")
           +    \#                                    concat(-------------,"#")
            *\.J                                             repeat(".",J)
                            t+JK decrement(add(J,K)) <--- auto-print


答:
05AB1E, <s>27</s> 24 bytes

Code:

```<code>+Í,¹<'.×'#¶J²<×'X'#¹<×J,
</code>```

Explanation:

```<code>+                         # Add the length and the height.
 Í                        # Decrease by two.
  ,                       # Print this value with a newline.
   ¹<'.×                  # Take the first input, decrease by 1 and multiply with ".".
        '#¶               # Push a "#"-character and a newline character.
           J              # Join the string.
            ²<            # Take the second input and decrease by 1.
              ×           # Multiply the joined string with this value.
               'X         # Push the "X"-character.
                 '#¹<×J   # Multiply the "#"-character with (first input - 1).
                       ,  # Pop and print with a newline.
</code>```

Try it online!. Uses CP-1252 encoding.

Body:
05AB1E, <s>27</s> 24 bytes

Code:

+Í,¹<'.×'#¶J²<×'X'#¹<×J,

Explanation:

+                         # Add the length and the height.
 Í                        # Decrease by two.
  ,                       # Print this value with a newline.
   ¹<'.×                  # Take the first input, decrease by 1 and multiply with ".".
        '#¶               # Push a "#"-character and a newline character.
           J              # Join the string.
            ²<            # Take the second input and decrease by 1.
              ×           # Multiply the joined string with this value.
               'X         # Push the "X"-character.
                 '#¹<×J   # Multiply the "#"-character with (first input - 1).
                       ,  # Pop and print with a newline.

Try it online!. Uses CP-1252 encoding.


答:
Ruby, 48 bytes

This is an anonymous function, which according to this meta post is acceptable unless the question states "full program." I wouldn't normally be pedantic about this but the problem is very simple and doing a program would be a significant % increase to the score.

Input is two arguments. Return value is an array containing the ASCII art string and the number of # in the path.

```<code>->w,h{[(?.*(w-=1)+'#
')*(h-=1)+?X+?#*w,w+h]}
</code>```

In test program

```<code>f=->w,h{[(?.*(w-=1)+'#
')*(h-=1)+?X+?#*w,w+h]}

puts f[4,5]
</code>```

Output

```<code>...#
...#
...#
...#
X###
7
</code>```

It's just a string of h-1 rows of w-1 dots, followed by a # and newline. I put the # at the end in order to use a single #\n literal for both # and newline (the code contains an actual newline rather than an escape sequence.) The final row is then an X followed by w-1 #'s.

It was shorter to decrement the values of w and h during the ASCII art generation, so that the final calculation is simply w+h.

Body:
Ruby, 48 bytes

This is an anonymous function, which according to this meta post is acceptable unless the question states "full program." I wouldn't normally be pedantic about this but the problem is very simple and doing a program would be a significant % increase to the score.

Input is two arguments. Return value is an array containing the ASCII art string and the number of # in the path.

->w,h{[(?.*(w-=1)+'#
')*(h-=1)+?X+?#*w,w+h]}

In test program

f=->w,h{[(?.*(w-=1)+'#
')*(h-=1)+?X+?#*w,w+h]}

puts f[4,5]

Output

...#
...#
...#
...#
X###
7

It's just a string of h-1 rows of w-1 dots, followed by a # and newline. I put the # at the end in order to use a single #\n literal for both # and newline (the code contains an actual newline rather than an escape sequence.) The final row is then an X followed by w-1 #'s.

It was shorter to decrement the values of w and h during the ASCII art generation, so that the final calculation is simply w+h.


答:
MATL, <s>28</s> <s>26</s> 25 bytes

```<code>+qq35IMwX"46 5Lt4$(88HG(c
</code>```

EDIT (June 10, 2016): the link below includes a modification ( 5L is replaced by IL) to adapt to changes in the language

Try it online!

Explanation

```<code>+       % take two inputs. Add them
qq      % subtract 2
35      % push ASCII for '#'
IMw     % push the two inputs again. Swap them
X"      % 2D char array of '#'  repeated as indicated by inputs
46      % push ASCII for '.'
5Lt4$(  % fill all but last and row columns with that
88HG(   % fill 88 (ASCII for 'X') at linear index given by second input
c       % convert to char
</code>```

Body:
MATL, <s>28</s> <s>26</s> 25 bytes

+qq35IMwX"46 5Lt4$(88HG(c

EDIT (June 10, 2016): the link below includes a modification ( 5L is replaced by IL) to adapt to changes in the language

Try it online!

Explanation

+       % take two inputs. Add them
qq      % subtract 2
35      % push ASCII for '#'
IMw     % push the two inputs again. Swap them
X"      % 2D char array of '#'  repeated as indicated by inputs
46      % push ASCII for '.'
5Lt4$(  % fill all but last and row columns with that
88HG(   % fill 88 (ASCII for 'X') at linear index given by second input
c       % convert to char


答:
Pyke, 26 bytes

```<code>DtQ+RtF; Q\.*t\#+)\X\#Qt*+
</code>```

Try it here

Or a noncompetitive 34 bytes, add apply node with an ast)

```<code>jUa]Dm!X|RZjht]q+".#X"R@)Fs
);jmts
</code>```

Try it here!

Or 30 bytes if allowed spaces as padding

```<code>jUa]Dm!X|RZjht]q+".#X"R@)Pjmts
</code>```

Body:
Pyke, 26 bytes

DtQ+RtF; Q\.*t\#+)\X\#Qt*+

Try it here

Or a noncompetitive 34 bytes, add apply node with an ast)

jUa]Dm!X|RZjht]q+".#X"R@)Fs
);jmts

Try it here!

Or 30 bytes if allowed spaces as padding

jUa]Dm!X|RZjht]q+".#X"R@)Pjmts


答:
JavaScript (Node.js), <s>43</s> 41 bytes

```<code>(c=x=>require("fs").writeFile("a",x,c))()
</code>```

Writes null to a file named a, then repeat.

Title: Shortest code for infinite disk I/O

Body:
(Just open 50 tabs in Google Chrome :D (just kidding, no you can't))

Shortest code for infinite disk I/O any language, C# example:

using System.IO;

namespace FileApp {
    static class Program {
        public static void Main() {
            do {
                File.WriteAllText("a", "a");
                File.Delete("a");
            } while (true);
        }
    }
}
```

You can't just fill the entire disk though, as then it would halt in the end and would be finite.

And you can't do reading only, infinite writing has to happen. (It has to kill my SSD after enough runtime.)

Get cracking! :)

Body:
JavaScript (Node.js), <s>43</s> 41 bytes

(c=x=>require("fs").writeFile("a",x,c))()

Writes null to a file named a, then repeat.


问:
Making an acronym

Objective

Your goal is to make a program that converts an input to its acronym. Your input is guaranteed to have only letters and spaces. The input will have exactly one space between words. You must output the acronym of the input.

Rules

Your code cannot be case-sensitive(e.g. foo and Foo are the same)

Your code must ignore the following words and not put them in the acronym:
and or by of

You cannot assume that the words are all lowercase.

The output must be entirely capitalised, with no separation between characters.

A trailing newline is accepted but not necessary.

If your language has an acronym function builtin, you may not use it.

Examples

(inputs/outputs grouped)

```<code>United States of America
USA

Light Amplification by Stimulation of Emitted Radiation
LASER

united states of america
USA

Jordan Of the World
JTW
</code>```

Scoring

This is a code-golf challenge so the shortest code wins.

Leaderboard

var QUESTION_ID=75448,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Pylongolf2, 14 bytes (UTF-8)

```<code>c| l1╨3♀~
</code>```

Pylongolf2 has many non-ASCII characters that count as 2 bytes.

```<code>c| l1╨3♀~
c         read input
 |        split by space (note the space after |)
   l1     substring(0, 1)
     ╨3   convert to uppercase
       ♀~ pop the array into the stack and print it.
</code>```

Title: Making an acronym

Body:
Pylongolf2, 14 bytes (UTF-8)

c| l1╨3♀~

Pylongolf2 has many non-ASCII characters that count as 2 bytes.

c| l1╨3♀~
c         read input
 |        split by space (note the space after |)
   l1     substring(0, 1)
     ╨3   convert to uppercase
       ♀~ pop the array into the stack and print it.


Body:
Java, <s>137</s> 132 bytes

w->h->{String s="";int i=0,j;for(;i<h;i++){for(j=1;j<w;j++)s+=".";s+="#\n";}s+="X";for(j=1;j<w;j++)s+=".";s+="\n"+(w+h-2);return s;}


问:
Ordering words to fit in a given string
Given a string of letters and a set of words, output an ordering of the words so
that they can be found in the string by dropping letters that are not needed.
Words may occur more than once in the word set. The input string and all words
will consist of 1 to 1000 lower case letters each. The letters to be dropped may occur inside words or between words.

Your program or function can accept the letter string and words as lists, a string, or from STDIN, and must output all words in a correct order as a list
or string output. If there is more than one correct solution, only output one of
them. If there is no possible correct solution, output an empty list or an empty
string.

Examples:

```<code>dogcatfrog cat frog dog
-> dog cat frog

xxcatfixsxhingonxgrapexxxfishingcxat cat grape catfish fishing
-> catfish grape fishing cat

dababbabadbaccbcbaaacdacdbdd aa bb cc dd ba ba ba ab ac da db dc
-> da ab ba ba ba cc bb aa ac dc db dd

flea antelope
->
(no solution)
</code>```

This is code golf. Lowest number of bytes wins.

Edit: Explained that extra characters can be inside words.

答:
JavaScript (ES6), 119 bytes

```<code>(s,a,t=``,...r)=>a[0]?a.find((w,i)=>(b=[...a],b.splice(i,1),f(s,b,w+t,w,...r)))&&q:~s.search(t.split``.join`.*`)&&(q=r)
</code>```

Accepts a string and an array of words and returns an array of words or undefined on failure. Add 2 bytes if it must return the empty string on failure (?q:``), in which case this alternative version is only 120 bytes and returns the empty string on failure, and can even save 2 bytes if it's allowed to return 0 on failure:

```<code>(s,a,t=``,...r)=>a[0]?a.reduce((q,w,i)=>q||(b=[...a],b.splice(i,1),f(s,b,w+t,w,...r)),0):~s.search([...t].join`.*`)?r:``
</code>```

(After writing this I noticed that the algorithm is basically the same as @KennyLau's Pyth answer.)

Edited edit: updated after clarification of question, but is now really slow on the third test case; I set it off the night before last and this morning I've just noticed that it has actually found the solution, somewhere between 30 and 40 hours later. I was really mean though and fed the solution to it (it works best with the reversed solution, which it will verify instantly).

Title: Ordering words to fit in a given string

Body:
JavaScript (ES6), 119 bytes

(s,a,t=``,...r)=>a[0]?a.find((w,i)=>(b=[...a],b.splice(i,1),f(s,b,w+t,w,...r)))&&q:~s.search(t.split``.join`.*`)&&(q=r)

Accepts a string and an array of words and returns an array of words or undefined on failure. Add 2 bytes if it must return the empty string on failure (?q:``), in which case this alternative version is only 120 bytes and returns the empty string on failure, and can even save 2 bytes if it's allowed to return 0 on failure:

(s,a,t=``,...r)=>a[0]?a.reduce((q,w,i)=>q||(b=[...a],b.splice(i,1),f(s,b,w+t,w,...r)),0):~s.search([...t].join`.*`)?r:``

(After writing this I noticed that the algorithm is basically the same as @KennyLau's Pyth answer.)

Edited edit: updated after clarification of question, but is now really slow on the third test case; I set it off the night before last and this morning I've just noticed that it has actually found the solution, somewhere between 30 and 40 hours later. I was really mean though and fed the solution to it (it works best with the reversed solution, which it will verify instantly).


问:
Palindrome Hello, World
Your task is to create a program that prints "Greetings, Planet!" exactly to the console. Seems simple enough, right? Well, here's the trick. The code must be a palindrome, meaning it reads from right to left the same as in left to right.
Standard loopholes are NOT allowed.

答:
05AB1E, 16 bytes

Code:

```<code>”!º¥,ÁÙ””ÙÁ,¥º!”
</code>```

Explanation:

```<code>”!º¥,ÁÙ”          # Compressed string which results in "! Crm, Everywhere".
        ”ÙÁ,¥º!”  # Compressed string which results in "Greetings, Planet!".
                  # Top of stack is implicitly outputted.
</code>```

Try it online!

Title: Palindrome Hello, World

Body:
05AB1E, 16 bytes

Code:

”!º¥,ÁÙ””ÙÁ,¥º!”

Explanation:

”!º¥,ÁÙ”          # Compressed string which results in "! Crm, Everywhere".
        ”ÙÁ,¥º!”  # Compressed string which results in "Greetings, Planet!".
                  # Top of stack is implicitly outputted.

Try it online!


问:
A simple TCP server
Write a program or function that listens for incoming TCP traffic on port N. It offers a simple service: it calculates sum of IP address fields of incoming connection and returns.

Program or function reads integer N from arguments or stdin. It listens to incoming TCP connections on port N. When someone connects to that port, the program calculates sum of its IP address fields and sends it back to the client with trailing newline and closes connection.

Port number N is a valid port, and 210 < N < 215

Trailing newline can be either \nor \r\n

You can use either IPv4 or IPv6. Since IPv6 addresses are written in hexadecimal form, you must also provide result in same format, for example 2001:0db8:0000:0042:0000:8a2e:0370:7334 => 12ecd.

This is code-golf. Standard rules and loopholes apply.

Example

You run your server with ./server 1234. The server is now running and waiting for connections on port 1234. Then a client from 127.0.0.1 connects to your server. Your server performs a simple calculation: 127+0+0+1 => 128 and sends the result to the client (with trailing newline): 128\n. Then server closes connection and waits for next client.

Leaderboard

var QUESTION_ID=76379,OVERRIDE_USER=20569;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
8086 machine code (16-bit DOS), <s>163 156 148 148</s> 142 bytes

```<code>00000000  31 c0 bb 0a 00 31 c9 be  81 00 bf 80 00 8a 0d 01  |1....1..........|
00000010  cf 46 8a 0c 80 e9 30 f7  e3 00 c8 39 fe 72 f2 89  |.F....0....9.r..|
00000020  c3 89 c1 b8 01 10 ba ff  ff 31 f6 31 ff cd 61 53  |.........1.1..aS|
00000030  b8 00 12 bf 80 00 b9 01  00 ba ff ff cd 61 b8 00  |.............a..|
00000040  14 cd 61 31 c0 bb 0a 00  83 c7 06 8d 4d 04 26 02  |..a1........M.&.|
00000050  05 80 d4 00 47 39 cf 72  f5 bf 84 00 b9 80 00 bb  |....G9.r........|
00000060  0a 00 4f 31 d2 f7 f3 80  c2 30 88 15 39 cf 77 f2  |..O1.....0..9.w.|
00000070  1e 07 b8 0e 13 5b bf 80  00 b9 04 00 ba ff ff cd  |.....[..........|
00000080  61 b8 00 11 ba 01 00 cd  61 b8 00 4c cd 21        |a.......a..L.!|
0000008e
</code>```

Equivalent assembly code:

```<code>org 0x100
tcp equ 0x61    ; NTCPDRV interrupt

    xor ax,ax
    mov bx,10
    xor cx,cx
    mov si,0x81     ; [ds:81]-[ds:FF] = command line args
    mov di,0x80     ; [ds:80] = strlen(args)
    mov cl,[di]
    add di,cx

@@: inc si
    mov cl,[si]     ; get character
    sub cl,'0'      ; convert char to int
    mul bx          ; ax *= 10
    add al,cl
    cmp si,di
    jb @b
    ; now ax = port number

    mov bx,ax       ; source port (leaving this 0 doesn't work?)
    mov cx,ax       ; dest port
    mov ax,0x1001   ; open TCP socket for listening
    mov dx,-1       ; infinite timeout
    xor si,si       ; any dest IP
    xor di,di
    int tcp
    ; ^ I think this call should block until a connection is established, but apparently it doesn't.

    push bx         ; bx = socket handle, save it for later

    mov ax,0x1200   ; read from socket
    mov di,0x80     ; es:di = buffer (just reuse argument area to save space)
    mov cx,1        ; one byte
    mov dx,-1
    int tcp         ; this will block until a client connects and sends one byte

    mov ax,0x1400   ; get TCP session status, bx=handle
    int tcp
    ; now es:di points to a struct containing the source/dest IP addresses and ports
    ; the docs say it's two dwords for each IP address, then two bytes for "ip_prot" and "active" (whatever that means)
    ; ...but actually each IP address is followed by the port number (one word)

    xor ax,ax
    mov bx,10
    add di,6        ; [es:di+6] = client IP
    lea cx,[di+4]
@@: add al,[es:di]  ; add all bytes together
    adc ah,0
    inc di
    cmp di,cx
    jb @b
    ; now ax contains the IP address sum

    mov di,0x84     ; recycle arguments area again
    mov cx,0x80
    mov bx,10
@@: dec di
    xor dx,dx
    div bx          ; dl = ax mod 10
    add dl,'0'      ; convert int to char
    mov [di],dl
    cmp di,cx
    ja @b
    ; now [ds:80]-[ds:83] contains an ascii representation of the IP address sum

    push ds
    pop es
    mov ax,0x130e   ; send data with newline, wait for ack
    pop bx          ; socket handle
    mov di,0x80     ; es:di = data
    mov cx,4        ; sizeof data
    mov dx,-1
    int tcp

    mov ax,0x1100   ; close TCP socket
    mov dx,1
    int tcp

    mov ax,0x4c00
    int 0x21
</code>```

This assumes ntcpdrv is loaded at INT 0x61 (and any suitable packet driver at 0x60). Compile with fasm tcpserv.asm.

It has some issues though:

It doesn't check if the argument is a valid port number, or if it's even a number at all.

The client must send at least one byte, since I can't seem to find any other way to tell if a client has connected.

It only works once, and hangs on a second attempt. Works again after a reboot.

The returned value is left-padded with zeroes.

This is my very first code golf entry, and also my very first 8086 asm program. I'm sure there are ways to improve this further.

Title: A simple TCP server

Body:
8086 machine code (16-bit DOS), <s>163 156 148 148</s> 142 bytes

00000000  31 c0 bb 0a 00 31 c9 be  81 00 bf 80 00 8a 0d 01  |1....1..........|
00000010  cf 46 8a 0c 80 e9 30 f7  e3 00 c8 39 fe 72 f2 89  |.F....0....9.r..|
00000020  c3 89 c1 b8 01 10 ba ff  ff 31 f6 31 ff cd 61 53  |.........1.1..aS|
00000030  b8 00 12 bf 80 00 b9 01  00 ba ff ff cd 61 b8 00  |.............a..|
00000040  14 cd 61 31 c0 bb 0a 00  83 c7 06 8d 4d 04 26 02  |..a1........M.&.|
00000050  05 80 d4 00 47 39 cf 72  f5 bf 84 00 b9 80 00 bb  |....G9.r........|
00000060  0a 00 4f 31 d2 f7 f3 80  c2 30 88 15 39 cf 77 f2  |..O1.....0..9.w.|
00000070  1e 07 b8 0e 13 5b bf 80  00 b9 04 00 ba ff ff cd  |.....[..........|
00000080  61 b8 00 11 ba 01 00 cd  61 b8 00 4c cd 21        |a.......a..L.!|
0000008e

Equivalent assembly code:

org 0x100
tcp equ 0x61    ; NTCPDRV interrupt

    xor ax,ax
    mov bx,10
    xor cx,cx
    mov si,0x81     ; [ds:81]-[ds:FF] = command line args
    mov di,0x80     ; [ds:80] = strlen(args)
    mov cl,[di]
    add di,cx

@@: inc si
    mov cl,[si]     ; get character
    sub cl,'0'      ; convert char to int
    mul bx          ; ax *= 10
    add al,cl
    cmp si,di
    jb @b
    ; now ax = port number

    mov bx,ax       ; source port (leaving this 0 doesn't work?)
    mov cx,ax       ; dest port
    mov ax,0x1001   ; open TCP socket for listening
    mov dx,-1       ; infinite timeout
    xor si,si       ; any dest IP
    xor di,di
    int tcp
    ; ^ I think this call should block until a connection is established, but apparently it doesn't.

    push bx         ; bx = socket handle, save it for later

    mov ax,0x1200   ; read from socket
    mov di,0x80     ; es:di = buffer (just reuse argument area to save space)
    mov cx,1        ; one byte
    mov dx,-1
    int tcp         ; this will block until a client connects and sends one byte

    mov ax,0x1400   ; get TCP session status, bx=handle
    int tcp
    ; now es:di points to a struct containing the source/dest IP addresses and ports
    ; the docs say it's two dwords for each IP address, then two bytes for "ip_prot" and "active" (whatever that means)
    ; ...but actually each IP address is followed by the port number (one word)

    xor ax,ax
    mov bx,10
    add di,6        ; [es:di+6] = client IP
    lea cx,[di+4]
@@: add al,[es:di]  ; add all bytes together
    adc ah,0
    inc di
    cmp di,cx
    jb @b
    ; now ax contains the IP address sum

    mov di,0x84     ; recycle arguments area again
    mov cx,0x80
    mov bx,10
@@: dec di
    xor dx,dx
    div bx          ; dl = ax mod 10
    add dl,'0'      ; convert int to char
    mov [di],dl
    cmp di,cx
    ja @b
    ; now [ds:80]-[ds:83] contains an ascii representation of the IP address sum

    push ds
    pop es
    mov ax,0x130e   ; send data with newline, wait for ack
    pop bx          ; socket handle
    mov di,0x80     ; es:di = data
    mov cx,4        ; sizeof data
    mov dx,-1
    int tcp

    mov ax,0x1100   ; close TCP socket
    mov dx,1
    int tcp

    mov ax,0x4c00
    int 0x21

This assumes ntcpdrv is loaded at INT 0x61 (and any suitable packet driver at 0x60). Compile with fasm tcpserv.asm.

It has some issues though:

It doesn't check if the argument is a valid port number, or if it's even a number at all.

The client must send at least one byte, since I can't seem to find any other way to tell if a client has connected.

It only works once, and hangs on a second attempt. Works again after a reboot.

The returned value is left-padded with zeroes.

This is my very first code golf entry, and also my very first 8086 asm program. I'm sure there are ways to improve this further.