[Question]
      [
You are a space tourist on your way to planet Flooptonia! The flight is going to take another 47,315 years, so to pass the time before you're cryogenically frozen you decide to write a program to help you understand the Flooptonian calendar.
Here is the 208-day long Flooptonian calendar:
```
Month       Days    Input Range
Qupu        22      [0-22)
Blinkorp    17      [22-39)
Paas        24      [39-63)
Karpasus    17      [63-80)
Floopdoor   1       [80]
Dumaflop    28      [81-109)
Lindilo     32      [109-141)
Fwup        67      [141-208)
```
## Challenge
Your program, given an integer day in the year (range `[0-208)`) is to output the corresponding day of the month and name of the month (e.g. `13 Dumaflop`).
There is an exception, however: Floopdoor a special time for Flooptonians that apparently deserves its own calendar page. For that reason, Floopdoor isn't written with a day (i.e. the output is `Floopdoor`, not `1 Floopdoor`).
## Test Cases
```
0   => 1 Qupu
32  => 11 Blinkorp
62  => 24 Paas
77  => 15 Karpasus
80  => Floopdoor
99  => 19 Dumaflop
128 => 20 Lindilo
207 => 67 Fwup
```
## Rules
* You must write a complete program.
* You can assume that the input is always valid.
* Your output may have a trailing newline but must otherwise be free of any extra characters. The case should also match the provided examples.
* You may use date/time functions.
* Code length is to be measured in bytes.

[Answer]
# Python 3, ~~159~~ ~~156~~ ~~152~~ ~~151~~ ~~150~~ 148 bytes
```
n=int(input())+1
for c,x in zip(b" C","Qupu Blinkorp Paas Karpasus Floopdoor Dumaflop Lindilo Fwup".split()):c>=n>0and print(*[n,x][-c:]);n-=c
```
The bytes object in the `zip` contains unprintable characters:
```
for c,x in zip(b"\x16\x11\x18\x11\x01\x1c C", ...): ...
```
*(Thanks to @xnor for suggesting a `for/zip` loop for -3 bytes)*
[Answer]
# Pyth - 105 103 90 88 bytes
Uses base conversion. Two simple lookup tables, with one for the names and one for start dates, and a ternary at the end for Floopdoor.
```
KhfgQhTC,aCM"mQP?'"Zcs@LGjC"îºBüÏl}W\"p%åtml-¢pTÇÉ(°±`"23\c+?nQ80+-hQhKdkreK3
```
Compresses the string not as base 128, but as base 23. First, it translates it to indices of the alphabet. This required the separator to be `c` which doesn't appear in any of the month names. Then it encodes that to base ten from a base 23 number (the highest value that appeared was `w`), then converts to base 256.
The start dates are their unicode codepoints, no base conversion.
```
K                       K =
 hf                     First that matches the filter
  gQ                    >= Q
   hT                   First element of filter var
  C,                    Zip two sequences
   a       Z            Append 0 (I could save a byte here but don't want to mess with null bytes)
    CM"..."             Map the string to its codepoints
   c          \c        Split by "c"
    s                   Sum by string concatenation
     @LG                Map to location in alphabet
      j     23          Base 10 -> Base 23
      C"..."            Base 256 -> Base 10
+                       String concatenation
 ?nQ80                  Ternary if input != 80
  +-hQhK                Input - start date + 1
  k                     Else empty string
 r  3                   Capitalize first letter
  eK                    Of month name
```
[Try it online here](http://pyth.herokuapp.com/?code=KhfgQhTC%2CaCM%22%C2%8DmQP%3F%27%16%22Zcs%40LGjC%22%01%C3%AE%C2%BAB%C3%BC%C3%8Fl%7DW%5C%22p%25%C3%A5tml-%C2%9A%1F%C2%A2pT%C3%87%C2%94%C3%89%C2%97(%C2%96%C2%B0%18%C2%8F%C2%B1%15%60%2223%5Cc%2B%3FnQ80%2B-hQhKdkreK3&input=128&debug=1).
[Test Suite](http://pyth.herokuapp.com/?code=V.QKhfgNhTC%2CaCM%22%C2%8DmQP%3F%27%16%22Zcs%40LGjC%22%01%C3%AE%C2%BAB%C3%BC%C3%8Fl%7DW%5C%22p%25%C3%A5tml-%C2%9A%1F%C2%A2pT%C3%87%C2%94%C3%89%C2%97(%C2%96%C2%B0%18%C2%8F%C2%B1%15%60%2223%5Cc%2B%3FnN80%2B-hNhKdkreK3&input=0%0A32%0A62%0A77%0A80%0A99%0A128%0A207&debug=0).
[Answer]
# Piet 2125 bytes
It's by no means the shortest, but it's pretty and colorful...
Each pixel is placed by myself by hand. To run it go [here](http://www.rapapaing.com/piet/index.php) in FireFox (Chrome won't work) and load it with a codel width of 1 (it'll appear black, don't worry), enter the number and hit the run button!
Small Program:
[![Small Version](https://i.stack.imgur.com/UYzGl.png)](https://i.stack.imgur.com/UYzGl.png)

Enlarged (Codel width of 10):
[![enter image description here](https://i.stack.imgur.com/rvR7t.png)](https://i.stack.imgur.com/rvR7t.png)
[Answer]
# Pyth 178 156 153 147 bytes
```
J?<Q22,_1"Qupu"?<Q39,21"Blinkorp"?<Q63,38"Paas"?<Q80,62"Karpasus"?<Q81,k"Floopdoor"?<Q109,80"Dumaflop"?<Q141,108"Lindilo",140"Fwup"?nhJkjd,-QhJeJeJ
```
[Permalink](https://pyth.herokuapp.com/?code=J%3F%3CQ22%2C_1%22Qupu%22%3F%3CQ39%2C21%22Blinkorp%22%3F%3CQ63%2C38%22Paas%22%3F%3CQ80%2C62%22Karpasus%22%3F%3CQ81%2Ck%22Floopdoor%22%3F%3CQ109%2C80%22Dumaflop%22%3F%3CQ141%2C108%22Lindilo%22%2C140%22Fwup%22%3FnhJkjd%2C-QhJeJeJ&input=0&debug=0)
Second golf ever, any Pyth feedback will be very helpful.
## Explanation
```
J                       (Auto)Assign J a tuple of the first day & month name
 ?<Q22,_1"Qupu"         Recall that Q auto-initialized to raw_input()
 ?<Q39,21"Blinkorp"     ? is ternary
 ?<Q63,38"Paas"         , is a two-pair tuple
 ?<Q80,62"Karpasus"
 ?<Q81,k"Floopdoor"     Special case handled by empty string as first day
 ?<Q109,80"Dumaflop"
 ?<Q141,108"Lindilo"
 ,140"Fwup"             Since input assumed valid, no need to test for Fwup
?nhJk                   Is day not an empty string?
jd,                     join on space
   -QhJ                 Q-(first day or -1 on first month) + 1
   eJ                   The month itself
eJ                      Else print only the month name on Floopdoor
```
[Answer]
# CJam, ~~98~~ ~~96~~ 93 bytes
```
0000000: 72 69 63 22 00 16 27 3f 50 51 6d 8d d0 22 66 2d  ric"..'?PQm.."f-
0000010: 5f 7b 30 3c 7d 23 28 5f 40 3d 29 53 40 22 06 32  _{0<}#(_@=)S@".2
0000020: 88 b2 ce d2 87 2f 1e 79 62 1b 7a 11 53 a6 cc 02  ...../.yb.z.S...
0000030: 40 c5 c6 82 d0 dd b7 4b ed ee 1c dc 4f f5 ec 67  @......K....O..g
0000040: 22 32 35 35 62 32 33 62 27 61 66 2b 27 63 2f 3d  "255b23b'af+'c/=
0000050: 5f 2c 39 3d 7b 5c 3f 7d 26 28 65 75 5c           _,9={\?}&(eu\
```
The above is a reversible hexdump, since the source code contains unprintable characters.
Most unprintable characters are no problem for the online interpreter, but the null byte in the first string is a deal breaker.
At the cost of one byte, we can fix this by adding 1 to the input and 1 to each code point of the first string. You can try this version in the [CJam interpreter](http://cjam.aditsu.net/#code=ric)%22%01%17(%40QRn%C2%8E%C3%91%22f-_%7B0%3C%7D%23(_%40%3D)S%40%22%062%C2%88%C2%B2%C3%8E%C3%92%C2%87%2F%1Eyb%1Bz%11S%C2%A6%C3%8C%02%40%C3%85%C3%86%C2%82%C3%90%C3%9D%C2%B7K%C3%AD%C3%AE%1C%C3%9CO%C3%B5%C3%ACg%22255b23b'af%2B'c%2F%3D_%2C9%3D%7B%5C%3F%7D%26(eu%5C&input=80).
If the permalink doesn't work in your browser, you can copy the code from [this paste](http://pastebin.com/iWCtf4ae).
### Test cases
```
$ LANG=en_US
$ xxd -ps -r > flooptonia.cjam <<< 726963220016273f50516d8dd022662d5f7b303c7d23285f403d29534022063288b2ced2872f1e79621b7a1153a6cc0240c5c682d0ddb74bedee1cdc4ff5ec6722323535623233622761662b27632f3d5f2c393d7b5c3f7d262865755c
$ wc -c flooptonia.cjam
96 flooptonia.cjam
$ for d in 0 32 62 77 80 99 128 207; do cjam flooptonia.cjam <<< $d; echo; done
1 Qupu
11 Blinkorp
24 Paas
15 Karpasus
Floopdoor
19 Dumaflop
20 Lindilo
67 Fwup
```
### How it works
```
ric     e# Read a Long from STDIN and cast to Character.
"…"     e# Push the string that corresponds to [0 22 39 63 80 81 109 141 208].
f-      e# Subtract each character from the input char.
        e# Character Character - -> Long
_{0<}#  e# Find the index of the first negative integer.
(_      e# Subtract 1 from the index and push a copy.
@=)     e# Select the last non-negative integer from the array and add 1.
S@      e# Push a space and rotate the decremented index on top of it.
"…"     e# Push a string that encodes the months' names.
255b23b e# Convert from base 255 to 23.
'af+    e# Add the resulting digits to the character 'a'.
'c/     e# Split at occurrences of 'c' (used as separator).
=       e# Select the chunk that corresponds to the index.
_,9=    e# Check if its length is 9 (Floopdoor).
{\?}&   e# If so, swap and execute ternary if.
        e# Since the string " " is truthy, S Month Day ? -> Month.
(eu\    e# Shift out the first char, convert it to uppercase and swap.
```
[Answer]
# SWI-Prolog, ~~237~~ ~~232~~ 213 bytes
```
a(X):-L=[22:"Qupu",39:"Blinkorp",63:"Paas",80:"Karpasus",81:"Floopdoor",109:"Dumaflop",141:"Lindilo",208:"Fwup"],nth1(I,L,A:B),X<A,J is I-1,(nth1(J,L,Z:_),Y=X-Z;Y=X),R is Y+1,(X=80,write(B);writef("%w %w",[R,B])).
```
Here we use Prolog's backtracking mechanism to repeatedly apply `nth1/3` to the list `L`, to get the first element `LastDay+1:MonthName` of `L` for which `X < LastDay+1` holds. We then look for the month immediately before this one in the list to evaluate the day of the month.
[Answer]
# Q, ~~134~~ 146 Bytes
### second cut -- program (146 bytes)
```
v:bin[l:0 22 39 63 80 81 109 141 208;x:(*)"I"$.z.x];1(,/)($)$[v=4;`;(1+x-l v)," "],`Qupu`Blinkorp`Paas`Karpasus`Floopdoor`Dumaflop`Lindilo`Fwup v;
```
### first cut -- function (134 bytes)
```
{v:bin[l:0 22 39 63 80 81 109 141 208;x];(,/)($)$[v=4;`;(1+x-l v)," "],`Qupu`Blinkorp`Paas`Karpasus`Floopdoor`Dumaflop`Lindilo`Fwup v}
```
### testing
```
q){v:bin[l:0 22 39 63 80 81 109 141 208;x];(,/)($)$[v=4;`;(1+x-l v)," "],`Qupu`Blinkorp`Paas`Karpasus`Floopdoor`Dumaflop`Lindilo`Fwup v} each 0 32 62 77 80 99 128 207
"1 Qupu"
"11 Blinkorp"
"24 Paas"
"15 Karpasus"
"Floopdoor"
"19 Dumaflop"
"20 Lindilo"
"67 Fwup"
```
[Answer]
# Julia, ~~231~~ ~~216~~ ~~184~~ 175 bytes
```
r=readline()|>int
l=[141,109,81,80,63,39,22,0]
m=split("Qupu Blinkorp Paas Karpasus Floopdoor Dumaflop Lindilo Fwup")
i=findfirst(j->r>=j,l)
print(i==4?"":r-l[i]+1," ",m[9-i])
```
This reads a line from STDIN and converts it to an integer, finds the first element of a reversed list of month start days where the input is greater than or equal to the start, then prints accordingly.
[Answer]
# Swift 1.2, 256 bytes
```
var d=Process.arguments[1].toInt()!,f="Floopdoor",n=[("Qupu",22),("Blinkorp",17),("Paas",24),("Karpasus",17),(f,1),("Dumaflop",28),("Lindilo",32),("Fwup",67)]
for i in 0..<n.count{let m=n[i]
if d>=m.1{d-=m.1}else{println((m.0==f ?"":"\(d+1) ")+m.0)
break}}
```
To run put the code alone in a `.swift` file and run it using `swift <filename> <inputNumber>`
[Answer]
# Java, ~~357~~ 339 bytes
It's not the most efficient, but I do like how it works. It creates the entire Flooptonia calendar and then looks up what date the number is.
```
class X{public static void main(String[]q){String n[]={"Qupu","Blinkorp","Paas","Karpasus","Floopdoor","Dumaflop","Lindilo","Fwup"},l[]=new String[209];int m=0,d=0,i,b[]={0,22,39,63,80,81,109,141,208};for(i=0;i++<208;d++){l[i]=(m==4?"":d+" ")+n[m];if(i>b[m+1]){m++;d=0;}}System.out.print(l[new java.util.Scanner(System.in).nextInt()+2]);}}
```
Input/Output:
`77 --> 15 Karpasus
 80 --> Floopdoor`
Spaced and tabbed out:
```
class X {
    public static void main(String[] q) {
        String n[] = { "Qupu", "Blinkorp", "Paas", "Karpasus", "Floopdoor", "Dumaflop", "Lindilo", "Fwup" },
          l[]=new String[209];
        int m = 0,
          d = 0,
          i,
          b[] = { 0, 22, 39, 63, 80, 81, 109, 141, 208 };
        for(i = 0; i++ < 208; d++) {
            l[i]=(m == 4 ? "" : d + " ") + n[m];
            if(i > b[m+1]){
                m++;
                d = 0;
            }
        }
        System.out.print(l[ new java.util.Scanner(System.in).nextInt() + 2 ]);
    }
}
```
[Answer]
# Java, ~~275~~ ~~269~~ ~~266~~ ~~257~~ ~~256~~ ~~252~~ ~~246~~ ~~244~~ 243 bytes
```
class X{public static void main(String[]w){int x=new Short(w[0]),i=1,a[]={-1,21,38,62,79,80,108,140,207};w="Qupu,Blinkorp,Paas,Karpasus,Floopdoor,Dumaflop,Lindilo,Fwup".split(",");while(x>a[i++]);System.out.print((i==6?"":x-a[i-=2]+" ")+w[i]);}}
```
Formatted:
```
class X {
    public static void main(String[] w) {
        int x = new Short(w[0]),
            i = 1,
            a[] = { -1, 21, 38, 62, 79, 80, 108, 140, 207 };
            w = "Qupu,Blinkorp,Paas,Karpasus,,Dumaflop,Lindilo,Fwup".split(",");
        while (x > a[i++]);
        System.out.print(i == 6 ? "Floopdoor" : x - a[i-=2] + " " + w[i]);
    }
}
```
Interestingly, it's a few bytes shorter than this
```
class X {
    public static void main(String[] w) {
        int x = new Short(w[0]);
        System.out.print(x < 22 ? x + 1 + " Qupu" : x < 39 ? x - 21
                + " Blinkorp" : x < 63 ? x - 38 + " Paas" : x < 80 ? x - 62
                + " Karpasus" : x < 81 ? "Floopdoor" : x < 109 ? x - 80
                + " Dumaflop" : x < 141 ? x - 108 + " Lindilo" : x < 208 ? x
                - 140 + " Fwup" : "");
    }
}
```
[Answer]
**JavaScript using ES6 ~~171~~ ~~164~~ 163 bytes**
I'm not the best JavaScript programmer but I tried my best and ended up with the following code
```
f=(n)=>[0,22,39,63,80,81,109,141,208].some((e,j,a)=>n<a[j+1]&&(r=(j-4?n-e+1+' ':'')+"Qupu0Blinkorp0Paas0Karpasus0Floopdoor0Dumaflop0Lindilo0Fwup".split(0)[j]))&&r;
```
To see the result you need to refer above code in a html file and use similar to the code below
```
<html><body><p id="o"></p><script src="Fp.js"></script><script>t=[0,32,62,77,80,99,128,207];for(i=0;i<t.length;i++)document.getElementById('o').innerHTML+=f(t[i])+'<br/>';</script></body></html>
```
In the above code fp.js is the file that contains the javascript code.
Combined HTML and JavaScript code with indent is
```
        f=(n)=>[0,22,39,63,80,81,109,141,208].some(
          (e,j,a)=>n<a[j+1]&&(r=(j-4?n-e+1+' ':'')+"Qupu0Blinkorp0Paas0Karpasus0Floopdoor0Dumaflop0Lindilo0Fwup".split(0)[j]))
        &&r;

        t = [0, 32, 62, 77, 80, 99, 128, 207];
        for (i = 0; i < t.length; i++)
            document.getElementById('o').innerHTML += f(t[i]) + '<br/>';

```
```
<html>
<body>
    <p id="o"></p>
</body>
</html>
```
**Edit:**
I'd like to thank Vihan for helping me remove the return statement and reduce my code by 17bytes
@ipi, thanks for helping me save 7 bytes
>
> Note: You can see the result only in browsers Firefox version 22+ and
>  Google Chrome 45+ because of using ES6 arrow functions
>
>
>
[Answer]
# Python 2, 168 bytes
```
n=input();e=[-1,21,38,62,80,108,140,207];m=1
while n>e[m]:m+=1
print[`n-e[m-1]`+' '+'Qupu Blinkorp Paas Karpasus Dumaflop Lindilo Fwup'.split()[m-1],'Floopdoor'][n==80]
```
This treats day `80` internally as `18 Karpasus`, but then ignores it when called to print. Also, Python 2's `input()` function (as opposed to `raw_input()`) was convenient here.
[Answer]
# Perl 5, 140
Requires running via `perl -E`:
```
$i=<>+1;$i-=$b=(22,17,24,17,1,28,32,67)[$c++]while$i>0;say$b>1&&$i+$b.$",(x,Qupu,Blinkorp,Paas,Karpasus,Floopdoor,Dumaflop,Lindilo,Fwup)[$c]
```
Test output (stolen test code from @Dennis):
```
$for d in 0 32 62 77 80 99 128 207; do perl -E '$i=<>+1;$i-=$b=(22,17,24,17,1,28,32,67)[$c++]while$i>0;say$b>1&&$i+$b.$",(x,Qupu,Blinkorp,Paas,Karpasus,Floopdoor,Dumaflop,Lindilo,Fwup)[$c]' <<< $d; echo; done
1 Qupu
11 Blinkorp
24 Paas
15 Karpasus
Floopdoor
19 Dumaflop
20 Lindilo
67 Fwup
```
[Answer]
# Haskell, ~~171~~ 167 bytes
```
main=interact$f.read
f 80="Floopdoor"
f n=(g=<<zip[22,17,24,18,28,32,67](words"Qupu Blinkorp Paas Karpasus Dumaflop Lindilo Fwup"))!!n
g(n,s)=map((++' ':s).show)[1..n]
```
The program reads it's input from stdin which must not end in NL. Terminate input with EOF/^D or use something like `echo -n 80 | ./what-day-is-it`. (Some `echo`s don't understand the `-n` switch and omit the NL by default).
How it works: The `main` function reads the input, converts it to an `Integer` and calls `f` which returns a literal `Floopdoor` in case of an input of `80` or builds up a list of all possible dates, i.e. `["1 Qupu", "2 Qupu", ... "1 Blinkorp", ... "67 Fwup"]` from which it picks the `n`th element. I make `Karpasus` is one day longer. `18 Karpasus` is at position `80` and fixes the missing `Floopdoor` in the list.
Edit: @MtnViewMark had the idea of the `18 Karpasus` trick and saved 4 bytes.
[Answer]
## Swift 2.0, 220 bytes
Nothing clever, just filters from a collection of tuples...
```
func d(n:Int)->String{return n==80 ?"Floopdoor":[("Qupu",21,0),("Blinkorp",38,22),("Paas",62,39),("Karpasus",79,63),("Dumaflop",108,81),("Lindilo",140,109),("Fwup",208,141)].filter{$0.1>=n}.map{"\($0.0) \(n-$0.2+1)"}[0]}
```
Edited to correct bug, removed a space
[Answer]
## JavaScript (ES6 on Node.js), 196 bytes
Takes one command line argument:
```
a=+process.argv[2];for(d of['22Qupu','17Blinkorp','24Paas','17Karpasus','01Floopdoor','28Dumaflop','32Lindilo','67Fwup']){if(a<(z=parseInt(d)))return console.log((z>1?a+1+' ':'')+d.slice(2));a-=z}
```
### Demo
As there is no command-line argument ([`process.argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv)) in the browser, the code in the snippet has been placed in a function that accepts an argument:
```
// Snippet stuff
console.log = function(x){O.innerHTML += x + '\n'};
// Flooptonia function
function flooptonia(a) {
  a = +a;
  for (d in y=['22Qupu', '17Blinkorp', '24Paas', '17Karpasus', '01Floopdoor', '28Dumaflop', '32Lindilo', '67Fwup']) {
    if (a < (z = parseInt(y[d]))) return console.log((z > 1 ? a + 1 + ' ' : '') + y[d].slice(2));
    a -= z
  }
}
// Test
['0', '32', '62', '77', '80', '99', '128', '207'].map(flooptonia);
```
```
Test values: [0, 32, 62, 77, 80, 99, 128, 207]
<pre id=O></pre>
```
[Answer]
# Swift 2.0, 215 204
```
let(n,t)=(Int(readLine()!)!,[(141,"Fwup"),(109,"Lindilo"),(81,"Dumaflop"),(63,"Karpasus"),(39,"Paas"),(22,"Blinkorp"),(0,"Qupu")])
print({(n==80 ?"Floopdoor":"\(n-$0.0+1) "+$0.1)}(t[t.indexOf{$0.0<=n}!]))
```
This is a full program which asks the user to input the number in STDIN.
[Answer]
## Matlab, 187 bytes
```
d=input('');l=[141 109 81 80 63 39 22 0];t=find(d>=l,1);m=strsplit('Fwup Lindilo Dumaflop Floopdoor Karpasus Paas Blinkorp Qupu');f='%d %s';if t==4;f='%d\b%s';end;fprintf(f,d-l(t)+1,m{t})
```
Expanded version:
```
d=input('');
l=[141 109 81 80 63 39 22 0];
t=find(d>=l,1);
m=strsplit('Fwup Lindilo Dumaflop Floopdoor Karpasus Paas Blinkorp Qupu');
f='%d %s';
if t==4;
    f='%d\b%s';
end
fprintf(f,d-l(t)+1,m{t})
```
Reads a line from the console (`stdin`), finds the first element of a reversed list of month start days where the input is greater than or equal to the array element, then prints accordingly.
This is almost identical to the `Julia` answer, except for the display stage. (*We can't beat their ternary operator, unavailable in Matlab*). To make up having to explicit a full `if` statement, we use a little trick (a `Backspace` character in the print format) to "erase" the number 1 for the special day/month `Floopdoor`
---
*In collaboration with the [Matlab and Octave](http://chat.stackoverflow.com/rooms/81987/matlab-and-octave) chat participants.*
[Answer]
# Javascript ES5 using 168 bytes
```
m=[-1,21,38,62,79,80,108,140];for(n=prompt(i=0);n>m[i+1]&&i++<8;);alert((i-4?n-m[i]+" ":"")+"Qupu0Blinkorp0Paas0Karpasus0Floopdoor0Dumaflop0Lindilo0Fwup".split(0)[i])
```
Ungolfed:
```
m=[-1,21,38,62,79,80,108,140];   // create range of starting indexes - 1
for(                             // begin for loop
  n=prompt(i=0);                 // initialize i to zero and prompt user
  n>m[i+1] && i++ < 8;           // exit if n>0; increment i; exit if i was < 8
  );                             // end for loop
alert(
  (i-4 ? n-m[i]+" ":"") + // special floopdoor case
  "Qupu0Blinkorp0Paas0Karpasus0Floopdoor0Dumaflop0Lindilo0Fwup".split(0)[i]);
  //^  create an array of strings by splitting at zero. Then, select element i
```
[Answer]
# C, 241 bytes
Nothing too exciting. Could have shaved 27 bytes had it require to be a complete program.
```
main(c,s)char**s;{c=atoi(s[1]);c-80?printf("%d ",c<22?c+1:c<39?c-21:c<63?c-38:c<80?c-62:c<109?c-80:c<141?c-108:c-140):0;puts(c<22?"Qupu":c<39?"Blinkorp":c<63?"Paas":c<80?"Karpasus":c<81?"Floopdoor":c<109?"Dumaflop":c<141?"Lindilo":"Fwup");}
```
]


[Question]
      [
[NetHack](https://en.wikipedia.org/wiki/NetHack) is a roguelike game where a player must retrieve the Amulet of Yendor from the lowest level of the dungeon. Commonly played via telnet, the entire game is represented with ASCII graphics. The game is extremely challenging and requires knowledge of many game mechanics in order to succeed.
For the purposes of this challenge, assume that the entire dungeon is a single level and only 5×16 characters. Furthermore, assume that this is a "safe" dungeon or that you are only implementing a prototype—there will be no monsters, concerns about hunger, etc. In fact, you must only track the location of the character and the amulet and the game will effectively end when the player arrives at the same location as the amulet.
# Challenge requirements
* There will be a 5×16 dungeon (single level).
* Give the player a starting location (optionally random) and the amulet a separate random (different each time the program is run) starting square inside the dungeon. That is, the amulet is not allowed to start on the same square as the player.
* Accept four input keys which move the player one square at a time (four cardinal directions). Reading/processing other input is allowed (a readline() function that requires pressing 'enter', etc).
* Travelling outside the bounds of the dungeon is not allowed. E.g., if the player is on the right edge of the dungeon pressing right should do nothing.
* After initial generation and after each movement, print the state of the game. As this is code golf and printing is rather uninteresting, ignore the character count for the print function and function call *assuming no state changes*. Empty cells should be shown as period (`.`), amulet as double quote (`"`) and character as at symbol (`@`).
* The game is over when the player "discovers" the amulet (arrives at the same square)
# Winning
This is a code golf challenege, the shortest code to meet the requirements one week from today will be declared winner.
# Example
Here is an example solution in C# (ungolfed) to show basic requirements and sample output.
```
using System;
namespace nh
{
    class Program
    {
        static Random random = new Random();

        // player x/y, amulet x/y
        static int px, py, ax, ay;

        static void Main(string[] args)
        {
            px = random.Next(0, 16);
            py = random.Next(0, 5);

            // amulet starts on a position different from the player
            do { ax = random.Next(0, 16); } while (px == ax);
            do { ay = random.Next(0, 5); } while (py == ay);
            print();
            do
            {
                // reads a single keypress (no need to press enter)
                // result is cast to int to compare with character literals
                var m = (int)Console.ReadKey(true).Key;
                // Move the player. Here standard WASD keys are used.
                // Boundary checks for edge of dungeon as well.
                if (m == 'W')
                    py = (py > 0) ? py - 1 : py;
                if (m == 'S')
                    py = (py < 5) ? py + 1 : py;
                if (m == 'A')
                    px = (px > 0) ? px - 1 : px;
                if (m == 'D')
                    px = (px < 16) ? px + 1 : px;
                // print state after each keypress. If the player doesn't
                // move this is redundant but oh well.
                print();
            // game ends when player is on same square as amulet
            } while (px != ax || py != ay);
        }
        static void print()
        {
            Console.Write('\n');
            for (int y=0; y<5; y++)
            {
                for (int x = 0; x < 16; x++)
                {
                    if (x == px && y == py)
                        Console.Write('@');
                    else if (x == ax && y == ay)
                        Console.Write('"');
                    else
                        Console.Write('.');
                }
                Console.Write('\n');
            }
        }
    }
}
```
Total character count is 1474, but ignoring calls to the print function and its definition the final character count is `896`.
Output when the program is run:
```
................
...."...........
..........@.....
................
................
```
Output (including above) after the 'a' key is pressed twice:
```
................
...."...........
..........@.....
................
................
................
...."...........
.........@......
................
................
................
...."...........
........@.......
................
................
```

[Answer]
# [CHIP-8](https://en.wikipedia.org/wiki/CHIP-8), 48 bytes
This may not be considered legal, but why the hell not. I wrote my program in CHIP-8, a bytecode-based programming language for a virtual game console. You can try the complete program (99 bytes) in your browser using an emulator/debugger I wrote called Octo:
![Screenshot](https://i.stack.imgur.com/uMI59.png)
<http://johnearnest.github.io/Octo/index.html?gist=1318903acdc1dd266469>
A hex dump of that complete program is as follows:
```
0x60 0x14 0x61 0x04 0xC4 0x3C 0xC5 0x08
0x22 0x36 0xF6 0x0A 0x22 0x52 0x40 0x00
0x12 0x16 0x46 0x07 0x70 0xFC 0x40 0x3C
0x12 0x1E 0x46 0x09 0x70 0x04 0x41 0x00
0x12 0x26 0x46 0x05 0x71 0xFC 0x41 0x10
0x12 0x2E 0x46 0x08 0x71 0x04 0x22 0x52
0x3F 0x01 0x12 0x0A 0x00 0xFD 0xA2 0x58
0xD4 0x54 0x22 0x52 0x62 0xFF 0xA2 0x5B
0xD2 0x34 0x72 0x04 0x32 0x3F 0x12 0x40
0x62 0xFF 0x73 0x04 0x33 0x14 0x12 0x40
0x00 0xEE 0xA2 0x5F 0xD0 0x14 0x00 0xEE
0xA0 0xA0 0x40 0x00 0x00 0x20 0x00 0xF0
0x90 0x90 0xD0
```
You can move the player with the ASWD keys, or the 7589 keys on the original CHIP-8 keypad. If I remove all the code and data for drawing the background and the player, I instead get this 48 byte dump:
```
0x60 0x14 0x61 0x04 0xC4 0x3C 0xC5 0x08
0xF6 0x0A 0x40 0x00 0x12 0x12 0x46 0x07
0x70 0xFC 0x40 0x3C 0x12 0x1A 0x46 0x09
0x70 0x04 0x41 0x00 0x12 0x22 0x46 0x05
0x71 0xFC 0x41 0x10 0x12 0x2A 0x46 0x08
0x71 0x04 0x3F 0x01 0x12 0x08 0x00 0xFD
```
The ungolfed, complete form of the program was written in a high level assembly language as follows:
```
:alias px v0
:alias py v1
:alias tx v2
:alias ty v3
:alias ax v4
:alias ay v5
:alias in v6
: main
    px := 20
    py := 4
    ax := random 0b111100
    ay := random 0b001000
    draw-board
    loop
        in := key
        draw-player
        if px != 0 begin
            if in == 7 then px += -4
        end
        if px != 0x3C begin
            if in == 9 then px +=  4
        end
        if py != 0 begin
            if in == 5 then py += -4
        end
        if py != 16 begin
            if in == 8 then py +=  4
        end
        draw-player
        if vf != 1 then
    again
    exit
: draw-board
    i := amulet
    sprite ax ay 4
    draw-player
    tx := -1
    i := ground
    : draw
    loop
        sprite tx ty 4
        tx += 4
        if tx != 63 then jump draw
        tx := -1
        ty += 4
        if ty != 20 then
    again
;
: draw-player
    i := player
    sprite px py 4
;
: amulet  0xA0 0xA0 0x40
: ground  0x00 0x00 0x20 0x00
: player  0xF0 0x90 0x90 0xD0
```
Note that the compiled bytes *themselves* are the CHIP-8 programming language; the assembler is simply a more convenient means of composing such programs.
[Answer]
# TI-BASIC, ~~42~~ ~~41~~ ~~38~~ ~~36~~ 35 bytes
For your TI-83 or 84+ series graphing calculator.
```
int(5irand→A                          //Randomize amulet position
6log(ie^(6→C                          //15.635 + 4.093i
Repeat Ans=A                          //Ans holds the player pos. (starts bottom right)
iPart(C-iPart(C-Ans-e^(igetKey-i      //Boundary check, after adjusting player position
prgmDISPLAY
End
----------
PROGRAM:DISPLAY
For(X,0,15
For(Y,0,4
Output(Y+1,X+1,".
If A=X+Yi
Output(Y+1,X+1,"¨
If Ans=X+Yi
Output(Y+1,X+1,"@
End
End
```
Which direction the player will go is a function of the [key code](http://tibasicdev.wikidot.com/key-codes) of the key pressed, but four keys that definitely work are these on the top row:
```
Key        [Y=]  [WINDOW]  [ZOOM]  [TRACE]  [GRAPH]
           -------------------------------------------
Key code    11      12       13               15
Direction  Left     Up     Right             Down
```
The amulet starts on one of the five squares in the first column, and the player starts at the bottom right square. For example, a possible arrangement is:
```
................
¨...............
................
................
...............@
```
## Explanation
The player's position is stored as a complex number from `0+0i` to `15+4i`, where the real part goes to the right and the imaginary part goes down. This facilitates easy boundary checking on the top and left: we simply offset the number slightly and round towards zero. For example, if the offset is `0.5` and our position is `-1+3i` (off the screen to the left), then the position will be corrected to `iPart(-0.5+3.5i)=0+3i`, where it should be. Checking for the bottom and right boundaries is slightly more complicated; we need to subtract the number from a constant `C`, which is about `15.635 + 4.093i` (it's the shortest one I could find between `15+4i` and `16+5i`), round, subtract from `C` again to flip the number back, and round again.
When a key is pressed, the unadjusted player position will move by 1 unit in some direction, but the integer part only changes when certain keys are pressed. Luckily, the keys that work are all on the top row. Below is a graph of the offsets in cases where keys 11, 12, 13, and 15 are pressed, and when no key is pressed (No press is the point inside the center square, causing the integer parts to be unchanged; the four keypresses' offsets have different integer parts). `C` is the red cross at the center of the circle.
![enter image description here](https://i.stack.imgur.com/BBrom.png)
## Old code (42 bytes):
```
int(9irand→A                     // 0≤rand≤1, so int(9irand) = i*x where 0≤x≤8
1                                //set "Ans"wer variable to 1+0i
Repeat Ans=A
Ans-iPart(i^int(48ln(getKey-1    //add -i,-1,i,1 for WASD respectively (see rev. history)
Ans-int(Ans/16+real(Ans/7        //ensure player is inside dungeon
prgmDISPLAY                      //display on top 5 rows of the homescreen
                                 //(for this version switch X+Yi with Y=Xi in prgmDISPLAY)
End
```
### Limitations
There is no way to escape a `"` character, so strings with a `"` cannot be generated inside a program. Therefore, this uses the umlaut mark `¨` instead of a quote (if there were an already-existing string with a quote mark, I could display that). To get `¨` and `@` in a program, an outside tool is required; however, it is valid TI-BASIC.
[Answer]
# Python 3, 86 bytes
```
def d():
    import sys
    for y in range(5):
        line = []
        for x in range(16):
            line.append('@' if y*16+x == p else \
                        '"' if y*16+x == a else \
                        '.')
        print(''.join(line))
    print()
    sys.stdout.flush()
p=79;a=id(9)%p
while p-a:d();p+=[p%16<15,16*(p<64),-(p%16>0),-16*(p>15)][ord(input())%7%5]
```
Only counting the bottom two lines, and dropping `d();`.
[Answer]
# C, ~~122~~ ~~121~~ ~~115~~ ~~104~~ ~~102~~ 101 bytes
```
#define o ({for(int t=0;t<80;++t)t%16||putchar(10),putchar(t^p?t^a?46:34:64);})
p;main(a){for(a=1+time(0)%79;p^a;o,p+=(int[]){-16*(p>15),16*(p<64),-!!(p%16),p%16<15}[3&getchar()/2]);}
```
First time posting here ! I hope you like it :)
`o` is the printing, erm, function. Our brave hero can be moved around with 2, 4, 6 and 8, but beware of not sending any other input (no newlines !).
**Update 1 :** brought `a` and `i` into `main`'s parameters.
**Update 2 :** OP having [confirmed](https://codegolf.stackexchange.com/questions/52547/minimal-nethack/52565#comment125400_52547) that a single string of input is OK, I got rid of `scanf` (which I used to skip the newline).
**Update 3 :** Used a compound array literal and modified the input layout. Program now goes haywire if you enter an invalid direction ;)
**Update 4 :** Noticed that the call to the printing function does not count. Took note to read rules more carefully.
**Update 5 :** one byte saved, thanks to Mikkel Alan Stokkebye Christia.
[Answer]
# CJam, ~~46~~ ~~45~~ ~~44~~ ~~40~~ ~~39~~ 37 bytes
```
{'.80*W$Gb'"t1$Gb'@tG/W%N*oNo}:P;
5,G,m*:Dmr~{P_l~4b2fm.+_aD&!$_W$=!}gP];
```
The first line (defines a function that prints the current game state) and the **P**'s on the second line (call that function) do not contribute to the byte count.
Both the starting position and the amulet's position are selected pseudo-randomly. The distribution is as uniform and the underlying PRNG allows.
Input is `E`, `6`, `9` and `B` for **Up**, **Down**, **Left** and **Right**, with `Caps Lock` activated, followed by `Enter`.
### Alternate version
```
{'.80*W$Gb'"t1$Gb'@tG/W%N*oNo}:P;
5,G,m*:Dmr~{P_ZYm*l~(=:(.+_aD&!$_W$=!}gP];
```
At the cost of four more bytes, the input format is improved significantly:
* This version accepts `8`, `2`, `4` and `6` for **Up**, **Down**, **Left** and **Right**, which matches the corresponding arrow keys on the numpad.
* It also accepts `7`, `9`, `1` and `3` for the corresponding diagonal moves.
### Testing
Since the I/O is interactive, you should try this code with the [Java interpreter](https://sourceforge.net/projects/cjam/files/).
Download the latest version and run the program like this:
```
java -jar cjam-0.6.5.jar nethack.cjam
```
To avoid pressing `Enter` after each key, and for in-place updates of the output, you can use this wrapper:
```
#!/bin/bash
lines=5
wait=0.05
coproc "$@"
pid=$!
head -$lines <&${COPROC[0]}
while true; do
    kill -0 $pid 2>&- || break
    read -n 1 -s
    echo $REPLY >&${COPROC[1]}
    printf "\e[${lines}A"
    head -$lines <&${COPROC[0]}
    sleep $wait
done
printf "\e[${lines}B"
```
Invoke like this:
```
./wrapper java -jar cjam-0.6.5.jar nethack.cjam
```
### Main version
```
5,G,   e# Push [0 1 2 3 4] and [0 ... 15].
m*:D   e# Take the Cartesian product and save in D.
mr~    e# Shuffle and dump the array on the stack.
       e# This pushes 80 elements. We'll consider the bottommost the amulet's
       e# position and the topmost the player's.
{      e# Do:
  P    e#   Call P.
  _    e#   Copy the player's position.
  l~   e#   Read and evaluate one line of input.
       e#      "6" -> 6, "9" -> 9, "B" -> 11, "E" -> 14
  4b   e#   Convert to base 4.
       e#     6 -> [1 2], 9 -> [2 1], 11 -> [2 3], 14 -> [3 2]
  2f-  e#   Subtract 2 from each coordinate.
       e#     [1 2] -> [-1 0], [2 1] -> [0 -1], [2 3] -> [0 1], [3 2] -> [1 0]
  .+   e#   Add the result to the copy of player's position.
  _aD& e#   Push a copy, wrap it in an array and intersect with D.
  !    e#   Logical NOT. This pushes 1 iff the intersection was empty.
  $    e#   Copy the corresponding item from the stack.
       e#     If the intersection was empty, the new position is invalid
       e#     and 1$ copies the old position.
       e#     If the intersection was non-empty, the new position is valid
       e#     and 0$ copies the new position.
  _W$  e#   Push copies of the new position and the amulet's position.
  =!   e#   Push 1 iff the positions are different.
}g     e# While =! pushes 1.
P      e# Call P.
];     e# Clear the stack.
```
### Alternate version
```
ZYm*   e# Push the Cartesian product of 3 and 2, i.e.,
       e#   [[0 0] [0 1] [0 2] [1 0] [1 1] [1 2] [2 0] [2 1] [2 2]].
l~     e#   Read and evaluate one line of input.
(=     e# Subtract 1 and fetch the corresponding element of the array.
:(     e# Subtract 1 from each coordinate.
```
### Function P
```
'.80*  e# Push a string of 80 dots.
W$Gb   e# Copy the amulet's position and convert from base 16 to integer.
'"t    e# Set the corresponding character of the string to '"'.
1$Gb   e# Copy the player's position and convert from base 16 to integer.
'@t    e# Set the corresponding character of the string to '@'.
G/     e# Split into chunks of length 16.
W%     e# Reverse the chunks (only needed for the alternate program).
N*     e# Join the chunks, separating by linefeeds.
oNo    e# Print the resulting string and an additional linefeed.
```
[Answer]
# Java, 231 bytes (196 if function)
Here's the full program code at 342:
```
class H{public static void main(String[]a){int p=0,y=79,c;y*=Math.random();y++;p(p,y);do p((p=(c=new java.util.Scanner(System.in).next().charAt(0))<66&p%16>0?p-1:c==68&p%16<15?p+1:c>86&p>15?p-16:c==83&p<64?p+16:p),y);while(p!=y);}static void p(int p,int y){for(int i=0;i<80;i++){System.out.print((i==p?'@':i==y?'"':'.')+(i%16>14?"\n":""));}}}
```
Without the print function, 231:
```
class H{public static void main(String[]a){int p=0,y=79,c;y*=Math.random();y++;p(p,y);do p((p=(c=new java.util.Scanner(System.in).next().charAt(0))<66&p%16>0?p-1:c==68&p%16<15?p+1:c>86&p>15?p-16:c==83&p<64?p+16:p),y);while(p!=y);}}
```
If just a function is okay (I'm unclear from the spec), then I can cut this down a bit further to 196:
```
void m(){int p=0,y=79,c;y*=Math.random();y++;p(p,y);do p((p=(c=new java.util.Scanner(System.in).next().charAt(0))<66&p%16>0?p-1:c==68&p%16<15?p+1:c>86&p>15?p-16:c==83&p<64?p+16:p),y);while(p!=y);}
```
And with some line breaks for a bit of clarity...
```
class H{
    public static void main(String[]a){
        int p=0,y=79,c;
        y*=Math.random();
        y++;p(p,y);
        do
            p(
                (p=(c=new java.util.Scanner(System.in).next().charAt(0))<66&p%16>0?
                    p-1:
                    c==68&p%16<15?
                        p+1:
                        c>86&p>15?
                            p-16:
                            c==83&p<64?
                                p+16:
                                p)
                ,y);
        while(p!=y);
    }
    static void p(int p,int y){
        for(int i=0;i<80;i++){
            System.out.print((i==p?'@':i==y?'"':'.')+(i%16>14?"\n":""));
        }
    }
}
```
Note that I'm not counting the print function `p(p,y)` itself, but I *am* counting the call to it, since I have stuff changing inside the call statement.
It works with capital letters `ASDW`. Due to the way it checks for those, some other letters might also work, but the spec doesn't really say anything about what should happen if I press different keys.
[Answer]
# Java, 574 bytes
```
import java.util.*;public class N{static Random r=new Random();static int v,b,n,m;public static void main(String[] a){v=r.nextInt(16);b=r.nextInt(5);n=r.nextInt(16);m=r.nextInt(5);p();do{Scanner e=new Scanner(System.in);char m=e.next().charAt(0);if(m=='w')b=b>0?b-1:b;if(m=='s')b=b<5?b+1:b;if(m=='a')v=v>0?v-1:v;if(m=='d')v=v<16?v+1:v;p();}while(v!=n || b!=m);}static void p(){System.out.println();for(int y=0;y<5;y++){for(int x=0;x<16;x++){if(x==z && y==x)System.out.print('@');else if(x==n && y==m)System.out.print('"');else System.out.print('.');}System.out.println();}}}
```
Basically the same as the C# version, except obfuscated & minimized.
[Answer]
# Julia, 161 bytes
Uses `w`, `a`, `s`, and `d` to move up, left, down, and right, respectively.
Full code, including printing (330 bytes):
```
B=fill('.',5,16)
a=[rand(1:5),rand(1:16)]
B[a[1],a[2]]='"'
c=[1,a==[1,1]?2:1]
B[c[1],c[2]]='@'
for i=1:5 println(join(B[i,:]))end
while c!=a
B[c[1],c[2]]='.'
m=readline()[1]
c[2]+=m=='a'&&c[2]>1?-1:m=='d'&&c[2]<16?1:0
c[1]+=m=='w'&&c[1]>1?-1:m=='s'&&c[1]<5?1:0
m∈"wasd"&&(B[c[1],c[2]]='@')
for i=1:5 println(join(B[i,:]))end
end
```
---
Scored code, excludes printing (161 bytes):
```
a=[rand(1:5),rand(1:16)]
c=[1,a==[1,1]?2:1]
while c!=a
m=readline()[1]
c[2]+=m=='a'&&c[2]>1?-1:m=='d'&&c[2]<16?1:0
c[1]+=m=='w'&&c[1]>1?-1:m=='s'&&c[1]<5?1:0
end
```
The difference here is that we don't save the game state as a matrix; all relevant information is contained in the arrays `c` and `a`. And, of course, nothing is printed. The user will no longer be prompted for input once the player reaches the amulet.
---
Ungolfed + explanation (full code):
```
# Initialize a 5x16 matrix of dots
B = fill('.', 5, 16)
# Get a random location for the amulet
a = [rand(1:5), rand(1:16)]
# Put the amulet in B
B[a[1], a[2]] = '"'
# Start the player in the upper left unless the amulet is there
c = [1, a == [1,1] ? 2 : 1]
# Put the player in B
B[c[1], c[2]] = '@'
# Print the initial game state
for i = 1:5 println(join(B[i,:])) end
# Loop until the player gets the amulet
while c != a
    # Put a dot in the player's previous location
    B[c[1], c[2]] = '.'
    # Read a line from STDIN, take the first character
    m = readline()[1]
    # Move the player horizontally within the bounds
    if m == 'a' && c[2] > 1
        c[2] -= 1
    elseif m == 'd' && c[2] < 16
        c[2] += 1
    end
    # Move the player vertically within the bounds
    if m == 'w' && c[1] > 1
        c[1] -= 1
    elseif m == 's' && c[1] < 5
        c[1] += 1
    end
    # Set the player's new location in B
    if m ∈ "wasd"
        B[c[1], c[2]] = '@'
    end
    # Print the game state
    for i = 1:5 println(join(B[i,:])) end
end
```
[Answer]
# Batch, 329 Bytes
```
@echo off
set e=goto e
set f= set/a
%f%a=0
%f%b=0
%f%c=%random%*3/32768+1
%f%d=%random%*16/32768+1
:et
call:p %a% %b% %c% %d%
if %a%%b% EQU %c%%d% exit/b
choice/C "wasd"
goto %errorlevel%
:1
%f%a-=1
%e%
:2
%f%b-=1
%e%
:3
%f%a+=1
%e%
:4
%f%b+=1
:e
if %a% GTR 4%f%a=4
if %a% LSS 0%f%a=0
if %b% GTR 15%f%b=15
if %b% LSS 0%f%b=0
%e%t
:p
setlocal enabledelayedexpansion
::creating a new line variable for multi line strings
set NL=^
:: Two empty lines are required here
cls
set "display="
for /l %%r in (0,1,4) do (
    set "line="
    for /l %%c in (0,1,15) do (
        set "char=."
        if %3 EQU %%r (
            if %4 EQU %%c (
                set char="
            )
        )
        if %1 EQU %%r (
            if %2 EQU %%c (
                set "char=@"
            )
        )
        set "line=!line!!char!"
    )
    set "display=!display!!line!!NL!"
)
echo !display!
exit /b
```
[Answer]
# Perl, ~~228~~ 222 characters (not counting the newlines that are not integral to the working of the code) — 207 if not counting the `print` and `print if` statement parts which are used for printing, but don't add to the game logic; 144 if also considering the field representation generation code as part of printing, as suggested by Yakk in the comments)
This code uses lowercase wasd for control; input must be confirmed with Enter. Tested with Perl 5.14.2.
```
($a=$==rand(79))+=($a>=($==rand(80)));
print $_=("."x80)=~s/(.{$=})./\1@/r=~s/(.{$a})./\1"/r=~s/(.{16})/\1\n/gr;
%r=qw(w s/.(.{16})@/@\1./s a s/.@/@./ s s/@(.{16})./.\1@/s d s/@./.@/);
while(/"/){print if eval $r{getc STDIN}}
```
Note that for this code, it is impossible to separate calculation and printing, since the operations are done directly on the printed representation using regular expressions.
Explanation:
```
($a=$==rand(79))+=($a>=($==rand(80)));
```
This line determines the position of the player and the amulet. The player position is determined by `$==rand(80)` and is actually easy to understand: On a 5×16 board, there are 80 distinct positions where the player can be. The position is stored in the `$=` variable which forces the stored value into integer; this saves a few bytes for not needing to explicitly cast the result to integer (`rand` delivers a floating point value).
Since one of the positions is already occupied by the player, there are only 79 positions left for the amulet, therefore for the amulet's position, `$a=$==rand(79)` is used. Again, the assignment to `$=` forces a conversion to integer, however I further assign it to `$a` in order to reuse `$=` for the player's position.
Now to avoid the amulet to occupy the same position as the player, it is advanced by one position if its position is at least as large as the player's, giving an uniform distribution on the places not occupied by the player. This is achieved by `$a = ($a >= $=)` where `$=` here holds the player's position. Now the first line is generated by inserting the two initial assignments instead of the first `$a$ and the only`$=` in this expression.
```
print $_=("."x80)=~s/(.{$=})./\1@/r=~s/(.{$a})./\1"/r=~s/(.{16})/\1\n/gr;
```
This generates the initial field, and afterwards prints is. `("."x80)` just generates a string of 80 dots. `=~s/(.{$=})./\1@/r` then replaces the `$=`th character with `@`, and `=~s/(.{$=})./\1@/r` the `$a`th character with `"`. Due to the `r` modifier they don't try to modify in place, but return the modified string, that's why they can be applied to the previous expressions. Finally, `=~s/(.{16})/\1\n/gr` inserts a newline every 16 characters. Note that the field is stored in the special variable `$_` which can be used implicitly in later statements.
```
%r=qw(w s/.(.{16})@/@\1./s a s/.@/@./ s s/@(.{16})./.\1@/s d s/@./.@/);
```
This creates a hash containing the replacement rules for the different moves. A more readable version of this is
```
%r = ( 'w' => 's/.(.{16})@/@\1./s',
       'a' => 's/.@/@./',
       's' => 's/@(.{16})./.\1@/s',
       'd' => 's/@./.@/' );
```
The keys are the characters for the moves, and the values are strings containing the corresponding replacement rule.
```
while(/"/){print if eval"\$_=~$r{getc STDIN}"}
```
This is the main loop. `while(/"/)` checks if there is still a `"` character in `$_` (that is, in the field). If we move onto the amulet, its character gets replaced with the player character so it disappears from the field.
`eval $r{getc STDIN}` reads a character from standard input, looks up the corresponding replacement rule from the has `%r` and applies it to `$_`, that is, the field. This evaluates to true if a replacement was actually made (that is, the key was found in the hash *and* the move was possible; an impossible move won't match in the replacement rule). In that case `print` is executed. Since it is called without argument, it prints `$_`, that is, the modified field.
[Answer]
## C#, 256 248 234 227 226 225 bytes
Uses the NumPad arrows with NumLock turned on to move.
Indented and commented for clarity:
```
using System;
class P{
    static void Main(){
        int a=0,b=0,c,d,e;
        var r=new Random();
        while(0<((c=r.Next(16))&(d=r.Next(5))));
        Draw(a,b,c,d); // Excluded from the score.
        while(a!=c|b!=d){
            e=Console.ReadKey().KeyChar-48;
            a+=e==4&a>0?-1:e==6&a<15?1:0;
            b+=e==8&b>0?-1:e==2&b<4?1:0;
            Draw(a,b,c,d); // Excluded from the score.
        }
    }
    // The following method is excluded from the score.
    static void Draw(int a, int b, int c, int d){
        Console.Clear();
        for (int y = 0; y < 5; y++)
        {
            for (int x = 0; x < 16; x++)
            {
                Console.Write(
                    x == a && y == b ? '@' :
                    x == c && y == d ? '"' :
                                       '.'
                );
            }
            Console.WriteLine();
        }
    }
}
```
[Answer]
# Html+JavaScript(ES6), score maybe 217
Too looong, but playable online in the snippets below.
Line 6 (T.value ...) is for output and not counted (but for simplicity I counted the textarea open and close tags, even if it's output too)
As for randomness: the amulet is always in the right half of the grid and the player always start in the left half.
Click on the textArea (after enlarging it) to start and restart the game.
```
<textarea id=T onclick='s()' onkeyup='m(event.keyCode)'></textarea>
<script>
R=n=>Math.random()*n|0,
s=e=>m(y=R(5),x=R(8),a=R(5)*17+R(8)+8),
m=k=>(x+=(x<15&k==39)-(x>0&k==37),y+=(y<4&k==40)-(y>0&k==38),p=y*17+x,
T.value=p-a?(t=[...('.'.repeat(16)+'\n').repeat(5)],t[a]='X',t[p]='@',t.join('')):t='Well done!'
)
</script>
```
EcmaScript 6 Snippet (Firefox only)
```
R=n=>Math.random()*n|0
s=e=>m(y=R(5),x=R(8),a=R(5)*17+R(8)+8)
m=k=>(
  x+=(x<15&k==39)-(x>0&k==37),
  y+=(y<4&k==40)-(y>0&k==38),
  p=y*17+x,
  T.value=p-a?(t=[...('.'.repeat(16)+'\n').repeat(5)],t[a]='"',t[p]='@',t.join('')):t='Well done!'
)
```
```
<textarea id=T onclick='s()' onkeyup='m(event.keyCode)'></textarea>
```
EcmaScript 5 snippet (tested in Chrome)
```
function R(n) { return Math.random()*n|0 }
function s() { m(y=R(5),x=R(8),a=R(5)*17+R(8)+8) }
function m(k) {
  x+=(x<15&k==39)-(x>0&k==37)
  y+=(y<4&k==40)-(y>0&k==38)
  p=y*17+x
  T.value=p-a?(t=('.'.repeat(16)+'\n').repeat(5).split(''),t[a]='"',t[p]='@',t.join('')):t='Well done!'
}
```
```
<textarea id=T onclick='s()' onkeyup='m(event.keyCode)'></textarea>
```
[Answer]
# Actionscript 3: 267 bytes
A working example is [online](http://www.fastswf.com/iZ2UH4U)
`var a:int,p:int,t;function g(){var r=Math.random;while(p==a){a=r()*80;p=r()*80}addEventListener("keyDown",function(e){if(a==p)return;if(e.keyCode==87&&p>15)p-=16if(e.keyCode==83&&p<64)p+=16if(e.keyCode==65&&p%16>0)p--if(e.keyCode==68&&(p+1)%16>0)p++print()});print()}`
Here's a complete (whitespaces included for readability) program using the game function:
```
package
{
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFormat;
    public class MiniRogue extends Sprite
    {
        var a:int, p:int, t;
        public function MiniRogue()
        {
            g();
        }
        function g(){
            var r=Math.random;
            while(p==a){
                a=r()*80;
                p=r()*80
            }
            addEventListener("keyDown",function(e){
                if(a==p)
                    return;
                if(e.keyCode==87&&p>15)
                    p-=16
                if(e.keyCode==83&&p<64)
                    p+=16
                if(e.keyCode==65&&p%16>0)
                    p--
                if(e.keyCode==68&&(p+1)%16>0)
                p++
                print()
            });
            print()
        }
        var old:int = -1;
        private function print():void {
            if (!t) {
                t = new TextField()
                t.defaultTextFormat = new TextFormat("_typewriter", 8)
                t.width=500;
                t.height=375;
                addChild(t)
            }
            var board:String = "";
            for (var i:int=0; i<80;i++) {
                if (i == p) {
                    board += "@";
                } else if (i == a) {
                    board += '"';
                } else {
                    board += ".";
                }
                if ((i + 1) % 16 == 0) {
                    board += "\n";
                }
            }
            if (a==p) {
                board += "Win!";
            }
            if (p == old) {
                board += "Bump!";
            }
            old = p;
            t.text = board;
        }
    }
}
```
[Answer]
# Javascript: 307 216
You can play in the snippet below!
The numbers on the left are just so the console (chrome one at least) doesn't merge the rows.
To run the code:
1. hit "run code snippet"
2. hit ctrl-shift-j to open the console
3. click in the result section
4. use arrow keys and play
```
var x=y=2,m=Math,b=m.floor(m.random()*5),a=14,i,j,t,c=console,onload=d;function d(){c.clear();for(i=0;i<5;i++){t=i;for(j=0;j<16;j++){t+=(i==y&&j==x)?"@":(i==b&&j==a)?'"':".";if(a==x&&b==y)t=":)";}c.log(t);}}onkeydown=function(){switch(window.event.keyCode){case 37:if(x>0)x--;break;case 38:if(y>0)y--;break;case 39:if(x<15)x++;break;case 40:if(y<4)y++;break;}d();};
```
Un-golfed:
```
var px=py=2,m=Math,ay=m.floor(m.random()*5),ax=14,i,j,t,c=console,onload=draw;
function draw() {
  c.clear();
  for(i=0;i<5;i++) {
    t=i;
    for(j=0;j<16;j++) {
      t+=(i==py&&j==px)?"@":
         (i==ay&&j==ax)?'"':".";
      if(ax==px&&ay==py)t=":)";
    }
    c.log(t);
  }
}
onkeydown=function() {
  switch (window.event.keyCode) {
    case 37:
      if(px>0)px--;
      break;
    case 38:
      if(py>0)py--;
      break;
    case 39:
      if(px<15)px++;
      break;
    case 40:
      if(py<4)py++;
      break;
  }
  draw();
};
```
**Edit 1:** Read rules more carefully and rewrote my code accordingly
* amulet y value is now randomized
* player can no longer escape room
* I no longer count the characters in the draw function or calls to it
[Answer]
# SpecBAS - ~~428~~ 402 (excluding printing, ~~466~~ 425 when counted)
Uses Q/A/O/P to move up/down/left/right respectively.
The line to print the dungeon at line 1 is the only line that can be ignored, but have golfed that down a bit as well.
```
1 PRINT ("."*16+#13)*5
2 LET px=8: LET py=3
3 LET ax=INT(RND*16): LET ay=INT(RND*5): IF ax=px AND ay=py THEN GO TO 3
4 PRINT AT ay,ax;#34;AT py,px;"@": LET ox=px: LET oy=py: PAUSE 0: LET k$=INKEY$
5 LET px=px+(k$="p")-(k$="o")
6 IF px<0 THEN LET px=0
7 IF px>15 THEN LET px=15
8 LET py=py+(k$="a")-(k$="q")
9 IF py<0 THEN LET py=0
10 IF py>4 THEN LET py=4
11 PRINT AT oy,ox;"."
12 IF SCREEN$(px,py)<>#34 THEN GO TO 4
```
The reference to #34 is just a short-hand way of putting CHR$(34) in the code.
Thanks @Thomas Kwa, I hadn't noticed player start position being random was optional. Also used separate IF statements to shave off a few characters.
[Answer]
## Another C#, ~~221~~ ~~171~~ 170
Here is another way in C# with both positions random. Wanted to show this even if this part is 7 bytes longer than Hand-E-Food's solution.
Hand-E-Food's answer will be shorter of course as soon as he will use Console.Read().
The downside of Consol.Read is, that pressing the needed Enter causes the field to be printed 2 more times.
But I don't think there is a requirement to print just on (real) input.

Navigation is done by 8426 as in Hand-E-Foods solution.
```
using System;
class P
{
static void Main()
{
Func<int> n=new Random().Next;
int x=n()%16,y=n()%5,a=n()%16,b,m;
while(y==(b=n()%5));
while(x!=a|y!=b)
{
Printer.Print(a, b, x, y);  // Excluded from the score.
m=Console.Read()-48;
y+=m==8&y>0?-1:m==2&y<4?1:0;
x+=m==4&x>0?-1:m==6&x<15?1:0;
}
}
}
```

**Edit:** (added new solution and moved PrinterClass to the end)
**Edit2:** (changed a 14 to a 15 and saved the byte by starting on right-bottom)

Adapting the technique of Mauris it is possible to melt it down to 171 bytes in C# (of course now without both positions random):
```
using System;
class P
{
static void Main()
{
int p=79,a=new Random().Next()%p,m;
while(p!=a){
Printer.Print(p,a);  // Excluded from the score.
m=Console.Read()-48;
p+=m==4&p/5>0?-5:m==6&p/5<15?5:m==8&p%5>0?-1:m==2&p%5<4?1:0;
}
}
}
```
The Printer Class is nearly the same, just a new overload of print...
```
class Printer
{
    public static void Print(int ax, int ay, int px, int py)
    {
        Console.Write('\n');
        for (int y = 0; y < 5; y++)
        {
            for (int x = 0; x < 16; x++)
            {
                if (x == px && y == py)
                    Console.Write('@');
                else if (x == ax && y == ay)
                    Console.Write('"');
                else
                    Console.Write('.');
            }
            Console.Write('\n');
        }
    }
    public static void Print(int p, int a)
    {
        Print(p/5,p%5,a/5,a%5);
    }
}
```
[Answer]
## Ruby, 185
Here is a Ruby example too.
I'm very new to Ruby, maybe someone knows how to do that better :)
I have counted lineFeeds as 1 since the Program will crash otherwise...
Navigation is done by 8462. You need to send input each time with enter.
```
def display(ax,ay,px,py)
    puts
    for y in 0..4
        for x in 0..15
            if (x == px && y == py)
                print "@"
            elsif (x == ax && y == ay)
                print '"'
            else
                print '.'
            end
        end
        puts
    end
end
x=y=0
a=Random.rand(16) while y==(b=Random.rand(5))
while x!=a or y!=b
display(a,b,x,y)  # Excluded from the score.
m=gets.chomp.to_i
y-=m==8?1:0 if y>0
y+=m==2?1:0 if y<4
x-=m==4?1:0 if x>0
x+=m==6?1:0 if x<15
end
```
[Answer]
# QBasic, 103 bytes
Per the rules of the challenge, the `Show` subprogram is not included in the byte-count, nor is the `Show p, q, a, b` call (with the following newline).
```
b=1+TIMER MOD 9
1Show p, q, a, b
INPUT m
p=p-(m=2)*(p>0)+(m=4)*(p<4)
q=q-(m=1)*(q>0)+(m=3)*(q<15)
IF(p<>a)+(q<>b)GOTO 1
SUB Show (playerRow, playerCol, amuletRow, amuletCol)
CLS
FOR row = 0 TO 4
  FOR col = 0 TO 15
    IF row = playerRow AND col = playerCol THEN
      PRINT "@";
    ELSEIF row = amuletRow AND col = amuletCol THEN
      PRINT CHR$(34);    ' Double quote mark
    ELSE
      PRINT ".";
    END IF
  NEXT
  PRINT
NEXT
END SUB
```
To move, input a number and press Enter: `1` to go left, `2` to go up, `3` to go right, and `4` to go down.
This code does not output the game state at the end, when the player has found the amulet. To make it do so, add another `Show p, q, a, b` after the `IF` statement.
## Explanation
Let `a`, `b` represent the coordinates of the amulet and `p`, `q` the coordinates of the player. The player starts at (0, 0), and the amulet starts on row 0, with a column between 1 and 9, inclusive, based on the 1's digit of the current time.
The rest is just a bunch of math with conditionals. The important thing to remember is that conditionals in QBasic return `0` for false, `-1` for true. Let's look at the player row update statement:
```
p=p-(m=2)*(p>0)+(m=4)*(p<4)
```
If `m=2`, we want to move up by subtracting 1 from `p`, as long as `p>0`. Similarly, if `m=4`, we want to move down by adding 1 to `p`, as long as `p<4`. We can obtain the desired behavior by multiplying. If both factors are `-1`, their product will be `1`, which we can subtract from or add to `p`. If either conditional is `0`, the product will be `0`, with no effect.
Similarly, the condition to determine whether the player has found the amulet is:
```
IF(p<>a)+(q<>b)GOTO 1
```
If either of the conditionals is true, their sum will be nonzero (either `-1` or `-2`) and thus truthy, and the program returns to line 1. Once `p` equals `a` and `q` equals `b`, both conditionals will be `0`, so their sum will be `0` and control flow can reach the end of the program.
]


[Question]
      [
### Task
Write a program that reads three integers **m**, **n** either from STDIN or as command-line arguments, prints all possible tilings of a rectangle of dimensions **m × n** by **2 × 1** and **1 × 2** dominos and finally the number of valid tilings.
Dominos of an individual tiling have to be represented by two dashes (`-`) for **2 × 1** and two vertical bars (`|`) for **1 × 2** dominos. Each tiling (including the last one) has to be followed by a linefeed.
For scoring purposes, you also have to accept a flag from STDIN or as command line argument that makes your program print only the number of valid tilings, but not the tilings itself.
Your program may not be longer than 1024 bytes. It has to work for all inputs such that **m × n ≤ 64**.
(Inspired by [Print all domino tilings of 4x6 rectangle](https://codegolf.stackexchange.com/q/37988).)
### Example
```
$ sdt 4 2
----
----
||--
||--
|--|
|--|
--||
--||
||||
||||
5
$ sdt 4 2 scoring
5
```
### Scoring
Your score is determined by the execution time of your program for the input **8 8** with the flag set.
To make this a *fastest code* rather than a *fastest computer* challenge, I will run all submissions on my own computer (Intel Core i7-3770, 16 GiB PC3-12800 RAM) to determine the official score.
Please leave detailed instructions on how to compile and/or execute your code. If you require a specific version of your language's compiler/interpreter, make a statement to that effect.
I reserve the right to leave submissions unscored if:
* There is no free (as in beer) compiler/interpreter for my operating system (Fedora 21, 64 bits).
* Despite our efforts, your code doesn't work and/or produces incorrect output on my computer.
* Compilation or execution take longer than an hour.
* Your code or the only available compiler/interpreter contain a system call to `rm -rf ~` or something equally fishy.
### Leaderboard
I've re-scored all submissions, running both compilations and executions in a loop with 10,000 iterations for compilation and between 100 and 10,000 iterations for execution (depending on the speed of the code) and calculating the mean.
These were the results:
```
User          Compiler   Score                              Approach
jimmy23013    GCC (-O0)    46.11 ms =   1.46 ms + 44.65 ms  O(m*n*2^n) algorithm.
steveverrill  GCC (-O0)    51.76 ms =   5.09 ms + 46.67 ms  Enumeration over 8 x 4.
jimmy23013    GCC (-O1)   208.99 ms = 150.18 ms + 58.81 ms  Enumeration over 8 x 8.
Reto Koradi   GCC (-O2)   271.38 ms = 214.85 ms + 56.53 ms  Enumeration over 8 x 8.
```

[Answer]
# C
A straightforward implementation...
```
#include<stdio.h>
int a,b,c,s[65],l=0,countonly;
unsigned long long m=0;
char r[100130];
void w(i,x,o){
    int j,k;
    j=(1<<b)-1&~x;
    if(i<a-1){
        s[i+1]=j;
        w(i+1,j,1);
        for(k=j&j/2&-o;j=k&-k;k&=~j)
            w(i,x|3*j,j);
    }
    else if((j/3|j/3*2)==j)
        if(countonly)
            m++;
        else{
            if(c==b)
                for(k=0;k<b;r[k++,l++]=10)
                    for(j=0;j<a;j++)
                        r[l++]=45+79*!((s[j]|s[j+1])&(1<<k));
            else
                for(j=0;j<a;r[j++,l++]=10)
                    for(k=0;k<b;k++)
                        r[l++]=124-79*!((s[j]|s[j+1])&(1<<k));
            r[l++]=10;
            if(l>=100000){
                fwrite(r,l,1,stdout);
                l=0;
            }
        }
}
int main(){
    scanf("%d %d %d",&a,&b,&countonly);
    c=b;
    if(a<b){a^=b;b^=a;a^=b;}
    s[0]=s[a]=0;
    w(0,0,1);
    if(countonly)
        printf("%llu\n",m);
    else if(l)
        fwrite(r,l,1,stdout);
}
```
### The cheating version
```
#include<stdio.h>
#include<string.h>
int a,b,c,s[65],l=0,countonly;
unsigned long long m=0,d[256];
char r[100130];
void w2(){
    int i,j,k,x;
    memset(d,0,sizeof d);
    d[0]=1;
    j=0;
    for(i=0;i<a-1;i++){
        for(k=1;k<(1<<(b-1));k*=2)
            for(x=0;x<(1<<(b-2));x++)
                d[(x+x/k*k*3+k*3)^j]+=d[(x+x/k*k*3)^j];
        j^=(1<<b)-1;
    }
    for(x=0;x<(1<<b);x++)
        if((x/3|x/3*2)==x)
            m+=d[x^((1<<b)-1)^j];
    printf("%llu\n",m);
}
void w(i,x,o){
    int j,k;
    j=(1<<b)-1&~x;
    if(i<a-1){
        s[i+1]=j;
        w(i+1,j,1);
        for(k=j&j/2&-o;j=k&-k;k&=~j)
            w(i,x|3*j,j);
    }
    else if((j/3|j/3*2)==j){
        if(c==b)
            for(k=0;k<b;r[k++,l++]=10)
                for(j=0;j<a;j++)
                    r[l++]=45+79*!((s[j]|s[j+1])&(1<<k));
        else
            for(j=0;j<a;r[j++,l++]=10)
                for(k=0;k<b;k++)
                    r[l++]=124-79*!((s[j]|s[j+1])&(1<<k));
        r[l++]=10;
        if(l>=100000){
            fwrite(r,l,1,stdout);
            l=0;
        }
    }
}
int main(){
    scanf("%d %d %d",&a,&b,&countonly);
    c=b;
    if(a<b){a^=b;b^=a;a^=b;}
    s[0]=s[a]=0;
    if(countonly)
        w2();
    else{
        w(0,0,1);
        if(l)
            fwrite(r,l,1,stdout);
    }
}
```
### Explanation of the faster algorithm
It scans from left to right, and maintain the state `d[i][j]`, where:
* `i` is in `[0,m)`, which means the current column.
* `j` is a bit vector of size `n`, where the bit would be 1 if the corresponding position in column `i` is already occupied before starting working on this column. I.e. it is occupied by the right half of a `--`.
* `d[i][j]` is the total number of different tilings.
Then say `e[i][j]` = the sum of `d[i][k]` where you can put vertical dominoes base on `k` to form a `j`. `e[i][j]` would be the number of tilings where each 1 bit in `j` is occupied by anything but the left half of a `--`. Fill them with `--` and you'll get `d[i+1][~j]` = `e[i][j]`. `e[m-1][every bit being 1]` or `d[m][0]` is the final answer.
A naive implementation will get you the time complexity somewhere near `g[n]=2*g[n-1]+g[n-2] = O((sqrt(2)+1)^n)` (already fast enough if n=m=8). But you can instead firstly loop for each possible domino, and try to add it to every tiling that can have this domino added, and merge the result to the original array `d` (like the algorithm for the Knapsack problem). And this becomes O(n\*2^n). And everything else are implementation details. The whole code runs in O(m\*n\*2^n).
[Answer]
# C
After a round of optimizations, and adapted for the modified rules:
```
typedef unsigned long u64;
static int W, H, S;
static u64 RM, DM, NSol;
static char Out[64 * 2 + 1];
static void place(u64 cM, u64 vM, int n) {
  if (n) {
    u64 m = 1ul << __builtin_ctzl(cM); cM -= m;
    if (m & RM) {
      u64 nM = m << 1;
      if (cM & nM) place(cM - nM, vM, n - 1);
    }
    if (m & DM) {
      u64 nM = m << W;
      vM |= m; vM |= nM; place(cM - nM, vM, n - 1);
    }
  } else if (S) {
    ++NSol;
  } else {
    char* p = Out;
    for (int y = 0; y < H; ++y) {
      for (int x = 0; x < W; ++x) { *p++ = vM & 1 ? '|' : '-'; vM >>= 1; }
      *p++ = '\n';
    }
    *p++ = '\0';
    puts(Out);
    ++NSol;
  }
}
int main(int argc, char* argv[]) {
  W = atoi(argv[1]); H = atoi(argv[2]); S = (argc > 3);
  int n = W * H;
  if (n & 1) return 0;
  for (int y = 0; y < H; ++y) {
    RM <<= W; RM |= (1ul << (W - 1)) - 1;
  }
  DM = (1ul << (W * (H - 1))) - 1;
  place(-1, 0, n >> 1);
  printf("%lu\n", NSol);
  return 0;
}
```
I started bumping into the length limit of 1024 characters, so I had to reduce the readability somewhat. Much shorter variable names, etc.
Build instructions:
```
> gcc -O2 Code.c
```
Run with solution output enabled:
```
> ./a.out 8 8 >/dev/null
```
Run with only solution count:
```
> ./a.out 8 8 s
```
Some comments:
* With the larger test example, I do want optimization now. While my system is different (Mac), around `-O2` seems to be good.
* The code has gotten slower for the case where output is generated. This was a conscious sacrifice for optimizing the "count only" mode, and for reducing the code length.
* There will be a few compiler warnings because of missing includes and external declarations for system functions. It was the easiest way to get me to below 1024 characters in the end without making the code totally unreadable.
Also note that the code still generates the actual solutions, even in "count only" mode. Whenever a solution is found, the `vM` bitmask contains a `1` for the positions that have a vertical bar, and a `0` for positions with a horizontal bar. Only the conversion of this bitmask into ASCII format, and the actual output, is skipped.
[Answer]
# C
The concept is to first find all possible arrangements of horizontal dominoes in a row, store them in `r[]` and then organize them to give all possible arrangements of vertical dominoes.
The code for positioning the horizontal dominoes in a row is modified from this answer of mine: <https://codegolf.stackexchange.com/a/37888/15599>. It's slow for the wider grids but that isn't a problem for the 8x8 case.
The innovation is in the way the rows are assembled. If the board has an odd number of rows it is turned through 90 degrees in the input parsing, so it now has an even number of rows. Now I place some vertical dominoes across the centreline. Because of symmetry, if there are `c` ways of arranging the remaining dominoes in the bottom half, there must also be `c` ways of arranging the remaining dominoes in the top half, meaning that for a given arrangement of vertical dominoes on the centreline, there are `c*c` possible solutions. Therefore only the centreline plus one half of the board is analysed when the program is required to print only the number of solutions.
`f()` builds the table of possible arrangements of horizontal dominoes, and scans through the possible arrangements of vertical dominoes on the centreline. it then calls recursive function `g()` which fills in the rows. If printing is required, function `h()` is called to do this.
`g()` is called with 3 parameters. `y` is the current row and `d` is the direction (up or down) in which we are filling the board from the centre outwards. `x` contains a bitmap indicates the vertical dominoes that are incomplete from the previous row. All possible arrangements of dominoes in a row from r[] are tried. In this array, a 1 represents a vertical domino and a pair of zeroes a horizontal domino. A valid entry in the array must have at least enough 1's to finish any incomplete vertical dominoes from the last row: `(x&r[j])==x`. It may have more 1's which indicates that new vertical dominoes are being started. For the next row, then, we need only the new dominoes so we call the procedure again with `x^r[j]`.
If an end row has been reached and there are no incomplete vertical dominoes hanging of the top or bottom of the board `x^r[j]==0` then the half has been succesfully completed. If we are not printing, it is sufficient to complete the bottom half and use `c*c` to work out the total number of arrangements. If we are printing, it will be necessary to complete also the top half and then call the printing function `h()`.
**CODE**
```
unsigned int W,H,S,n,k,t,r[1<<22],p,q[64];
long long int i,c,C;
//output: ascii 45 - for 0, ascii 45+79=124 | for 1
h(){int a;
  for(a=n;a--;a%W||puts(""))putchar(45+(q[a/W]>>a%W)%2*79);
  puts("");
}
g(y,d,x){int j;
  for(j=0;j<p;j++)if((x&r[j])==x){
    q[y]=r[j];
    if(y%(H-1)==0){
       (x^r[j])==0?
        y?c++,S||g(H/2-1,-1,i):h()
       :0;
    }else{
      g(y+d,d,x^r[j]);
    }
  }
}
e(z){int d;
  for(d=0;z;d++)z&=z-1;return n/2+1+d&1;
}
f(){
  //k=a row full of 1's
  k=(1ULL<<W)-1;
  //build table of possible arrangements of horizontal dominoes in a row;
  //flip bits so that 1=a vertical domino and save to r[]
  for(i=0;i<=k;i++)(i/3|i/3<<1)==i?r[p++]=i^k:0;
  //for each arrangement of vertical dominoes on the centreline, call g()
  for(i=0;i<=k;i++)e(i)?c=0,g(H/2,1,i),C+=c*c:0;
  printf("%llu",C);
}
main(int argc, char* argv[]) {
  W = atoi(argv[1]); H = atoi(argv[2]); S = (argc > 3);
  1-(n=W*H)%2?
      H%2?W^=H,H^=W,W^=H,t=1:0,f()
    :puts("0");
}
```
Note that input with an odd number of rows and even number of columns is turned though 90 degrees in the parsing phase. If this is unacceptable, the printing function `h()` can be changed to accomodate it. (EDIT: not required, see comments.)
EDIT: A new function `e()` has been used to check the parity of `i` (i.e the number of dominoes straddling the centreline.) The parity of `i` (the number of half-dominoes on the centreline protruding into each half of the board) must be the same as the oddness of the total number of spaces in each half (given by `n/2`) because only then can the dominoes fill all available space. This edit eliminates half the values of i and therefore makes my program approximately twice as fast.
]


[Question]
      [
This problem is from [Five programming problems every Software Engineer should be able to solve in less than 1 hour](https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour) which itself is an interesting read. The first few problems are trivial, but the fourth one can be a bit more interesting.
>
> Given a list of integers separated by a single space on standard input, print out the largest and smallest values that can be obtained by concatenating the integers together on their own line.
>
>
>
For example:
Input:
```
5 56 50
```
Output:
```
50556
56550
```
Various points of order:
* The order of the results are smallest then largest.
* *Only* the smallest and largest values may be printed out (iterating over all the variations and printing them out isn't valid).
* There will always be two or more integers in the list.
* It is possible for the largest and smallest results to be the same. In the case of input `5 55`, the number `555` should be printed twice.
* The integers are not necessarily distinct. `5 5` is valid input.
* Leading `0`s on integers are ***not*** valid input. You will ***not*** need to account for `05 55`.
As this is code golf, shortest entry wins.

[Answer]
# CJam, ~~14~~ 13 bytes
```
qS/e!:s$(N@W=
```
Pretty straight forward. This is how it works:
```
qS/                  e# Split the input on spaces
   e!                e# Get all permutations of the input numbers
     :s              e# Join each permutation order into a single string
       $             e# Sort them. This sorts the strings based on each digit's value
        (N@W=        e# Choose the first and the last out of the array separated by '\n'
```
[Try it online here](http://cjam.aditsu.net/#code=qS%2Fe!%3As%24(N%40W%3D&input=5%2056%2050)
[Answer]
# Pyth, 14 13 bytes
```
hJSmsd.pcz)eJ
```
Generates all permutations and sorts them, printing the first and last element.
[Answer]
# Python 2, ~~104~~ 99 bytes
Yep.
```
from itertools import*;z=[''.join(x)for x in permutations(raw_input().split())];print min(z),max(z)
```
Edit: thanks to xnor for -5 bytes!
[Answer]
# Mathematica, ~~64~~ 58 bytes
```
Print/@Sort[""<>#&/@Permutations@StringSplit@#][[{1,-1}]]&
```
This defines an unnamed function taking a string and printing the two lines. It's pretty straightforward as the others: get all permutations, join them together, sort them and print the first and last result.
Six bytes saved thanks to alephalpha.
[Answer]
# JavaScript (ES6) ~~54 72~~ 85
~~That's easier than it seems. Just sort them lexicographically. The good news is: that's exactly how plain javascript sort works.~~Well ... no, that's wrong ... still a (more convoluted) lexicograph compare can do the job.
Note: having a and b numeric, a+[b] is a shortcut for a+''+b, as we need a string concatenation and not a sum.
Note 2: the newline inside `` is significant and must be counted
**Edit** Don't argue with a moderator (...just kidding)
**Edit2** Fixed I/O format using popups (see [Default for Code Golf: Input/Output methods](http://meta.codegolf.stackexchange.com/a/2459/21348))
```
// Complete program with I/O
// The sorting function is shorter as input are strings
alert((l=prompt().split(' ')).sort((a,b)=>a+b>b+a).join('')+`
`+l.reverse().join(''))
// Testable function (67 chars)
// With an integer array parameter, the sorting function must convert to string
F=l=>(l.sort((a,b)=>a+[b]>b+[a]).join('')+`
`+l.reverse().join(''))
```
**Test** In Firefox / FireBug console
```
F([50, 2, 1, 9])
F([5,56,50])
F([52,36,526])
F([52,36,525])
F([52,36,524]
```
>
> 12509
>
>  95021
>
>
> 50556
>
>  56550
>
>
> 3652526
>
>  5265236
>
>
> 3652525
>
>  5255236
>
>
> 3652452
>
>  5252436
>
>
>
[Answer]
## J, 34 ~~36~~, ~~42~~ bytes
simple brute force:
```
h=:3 :'0 _1{/:~;"1":&.>y A.~i.!#y'
h 5 50 56
50556
56550
h 50 2 1 9
12509
95021
```
[Answer]
# Haskell, 98 bytes
```
import Data.List
g=sort.map concat.permutations.words
h i=unlines[g i!!0,last$g i]
main=interact h
```
Split input string at spaces, concatenate every permutation and sort. Print first and last element.
[Answer]
# Julia, 77 bytes
```
v->(Q=extrema([int(join(x)) for x in permutations(v)]);print(Q[1],"\n",Q[2]))
```
This creates an unnamed function that accepts a vector as input and prints the minimum and maximum of the permutations of the joined elements. To call it, give it a name, e.g. `f=v->...`.
Ungolfed + explanation:
```
function f(v)
    # Create an integer vector of the joined permutations using comprehension,
    # then get the minimum and maximum as a tuple using extrema().
    Q = extrema([int(join(x)) for x in permutations(v)])
    # Print the minimum and the maximum, separated by a newline.
    print(Q[1], "\n", Q[2])
end
```
Suggestions are welcome!
[Answer]
# Javascript (*ES6*) 134
Sadly, there's no built-in permutation function in JS :(
```
f=(o,y,i,a)=>y?o.concat(a[1]?a.filter((k,j)=>j^i).reduce(f,[]).map(z=>y+z):y):(q=o.split(' ').reduce(f,[])).sort().shift()+`
`+q.pop()
```
```
<!-- Snippet Demo (Firefox only) -->
<input id="input" value="5 56 50" />
<input type="button" onclick="output.innerHTML=f(input.value)" value="Run" />
<pre id="output"></pre>
```
[Answer]
## R, 59 bytes
```
write(range(combinat:::permn(scan(),paste,collapse="")),"")
```
[Answer]
# Ruby 75
Not my 'native' language, but one I thought I'd give a try at... thus this could (possibly) use some golfing tips. Still, not a bad entrant.
```
puts STDIN.read.split(" ").permutation.map{|x|x.join}.sort.values_at(0,-1)
```
I wouldn't say it is *elegant* other that everything is built in to the language. It should be fairly obvious exactly how this works.
[Answer]
# Perl, ~~79~~ 70B (68+2)
`use Math::Combinatorics;say for(sort map{join'',@$_}permute@F)[0,-1]`
Call with `echo 13 42 532 3 6|perl -M5.10.0 -an scratch.pl`. There's a +2 byte penalty for `-an`. Shame about the length of the module name...
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#œJ{¬sθ»
```
[Try it online.](https://tio.run/##yy9OTMpM/f9f@ehkr@pDa4rP7Ti0@/9/UwVTMwVTAwA)
**Explanation:**
```
#         # Split the (implicit) input by spaces
 œ        # Get all permutations of this list
  J       # Join each permutation together to a single string
   {      # Sort this list
    ¬     # Push the first item (without popping the list)
     s    # Swap to get the list again
      θ   # Pop and push its last item
       »  # And join all (both) values on the stack by newlines
          # (after which the result is output implicitly)
```
[Answer]
# [Scala](http://www.scala-lang.org/), 90 bytes
```
val x=Console.in.readLine.split(" ").permutations.map(_.mkString).toSeq
print(x.min,x.max)
```
[Try it online!](https://tio.run/##DYrLCsIwEADvfsXSUwqy4NsePEiv3voBsjZrieZls0pA/PYYBgYGJo1kqYTbg0eBPmiegr0DZ2GvE5xjhG/5kIV86oNPwTIajzOTvhjPmKI1ohpoWow8u7eQmLqho6iu6J6DzMZPLUoY@LWINURldMYvqym35Vc6WG@2sIIdHI6wr3R/ "Scala – Try It Online")
[Answer]
# JavaScript (ES6), 85 bytes
```
F=a=>(c=a.split(" ").sort((b,a)=>b+a-(a+b)),`${c.join("")}
${c.reverse().join("")}`)
```
**usage:**
```
F("50 2 1 9")
/*
    12509
    95021
*/
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ú∙n90≤╣*.vâ
```
[Run and debug it](https://staxlang.xyz/#c=L%7CT%7B%24mc%7CmP%7CMp&i=5+56+50)
Link is to unpacked version of code.
## Explanation
```
L|T{$mc|MP|mp implicit input
L             put all inputs in a list
 |T           get the unique orders of the list of inputs
   {$m        convert each list to string
      c       duplicate the array of strings
       |mP    print the minimum element
          |mp print the maximum element
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
Œ!VṢ.ị
```
[Try it online!](https://tio.run/##y0rNyan8///oJMWwhzsX6T3c3f3/cPujpjX//0eb6iiYmgGxQawOAA "Jelly – Try It Online")
Input and output as lists of integers. [+3 bytes](https://tio.run/##ASkA1v9qZWxsef//4biyxZIhVlbhuaIu4buLWf/Dh@KCrP//IjUgNTYgNTAiLA) to input with spaces and output with newlines
## How it works
```
Œ!VṢ.ị - Main link. Takes a list L on the left e.g. [5, 56, 50]
Œ!     - All permutations of L                      [[5, 56, 50], [5, 50, 56], [56, 5, 50], [56, 50, 5], [50, 5, 56], [50, 56, 5]]
  V    - Concatenate each into numbers              [55650, 55056, 56550, 56505, 50556, 50565]
   Ṣ   - Sort                                       [50556, 50565, 55056, 55650, 56505, 56550]
    .ị - Take the first and last elements           [56550, 50556]
```
]