title: Display words using 7-segment display

text:
# Question
Title: Display words using 7-segment display
My first ever Programming Puzzles & Code Golf is the Seven-Slash Display. Here is my first Challenge, also based on 7-segment display.

I often think about, besides numbers, what kind of letters I can display using a simple 7 segment display. Turns out a lot of letters can be displayed. In fact, all but the letters K, M, V, W, X can be displayed using a single 7-segment display. This is because you can display either lower case or the upper case of a letter. e.g.

"abcdef" can be displayed as

```
 _     _     _  _
!_!!_ !   _!!_ !_
! !!_!!_ !_!!_ !

```

Note that each character is a 3x3 matrix made up of `!` and `_`.

Of course, the 7-segment display can be used to display numbers and symbols:

```
 _     _  _  _           _  _     _
  ! _ !_ !_ !      _!  !!_ !_!!  !_!!_!
  !    _!!_ !_!   !_!  ! _!!  !_ ! ! _!

```

Some letters can have both upper and lower case:

```
 _                 _
!   _ !_!!_   !   ! ! _ ! !
!_ !_ ! !! !  !  !!_!!_!!_!!_!

```

Here are the full set of characters:

```
 _     _  _     _  _  _  _  _                       _
! !  ! _! _!!_!!_ !_   !!_!!_!    _ !_     _     _  _!
!_!  !!_  _!  ! _!!_!  !!_! _!   !_ ! !  !!_!!_!   !

 _     _     _  _  _                 _  _  _     _           _
!_!!_ !   _!!_ !_ !  !_!  !  !!   _ ! !!_!!_! _ !_ !_ ! !!_! _!
! !!_!!_ !_!!_ !  !_!! !  !!_!!_ ! !!_!!    !!   _!!_ !_! _!!_

```

Pay attention that there are a white space(), a dash(`-`) and a question mark(`?`). The letter `I`, `O` and `Z` are the same as numbers `1`, `0` and `2` respectively.

In this challenge, you will write a program or a function to display a string using 7-segment display format above.

# Rules

1. You can write a program or a function
2. This is code-golf, the shortest code in bytes wins
3. Your program or function should take input from STDIN or as a parameter. And outputs a string to STDOUT or as a string in 3 lines without leading space but terminated with newline. Handle upper/lower case of `CHIOU` properly.
4. You may optionally print trailing white spaces
5. You must follow the format above. Using underscore `_` and exclamation mark `!` to form your 7-segment display.
6. You must support white space(), dash(`-`) and question mark (`?`)
7. If the string contain unsupported character (k, m, v, w, x), a single error character (3 horizon line, see example) is displayed. Besides the 5 unsupported characters, you can assume the input is made up of only supported character set.
8. I opted to not have a letter for lowercase L (`l`) due to confusions but if you are so inclined, you can display it like a `1` either to the right or left.

# Examples

```
$./a.out Start
 _     _
!_ !_ !_! _ !_
 _!!_ ! !!  !_
$./a.out "7-seg dIsplay"
 _     _  _  _           _  _     _
  ! _ !_ !_ !      _!  !!_ !_!!  !_!!_!
  !    _!!_ !_!   !_!  ! _!!  !_ ! ! _!
$./a.out "0123456789 chiou-?"
 _     _  _     _  _  _  _  _                       _
! !  ! _! _!!_!!_ !_   !!_!!_!    _ !_     _     _  _!
!_!  !!_  _!  ! _!!_!  !!_! _!   !_ ! !  !!_!!_!   !
$./a.out "ABCDEFGHIJLNOPQRSTUZ"
 _     _     _  _  _                 _  _  _     _        _
!_!!_ !   _!!_ !_ !  !_!  !  !!   _ ! !!_!!_! _ !_ !_ ! ! _!
! !!_!!_ !_!!_ !  !_!! !  !!_!!_ ! !!_!!    !!   _!!_ !_!!_
$./a.out "abcdefghijlnopqrstuz"
 _           _  _  _                    _  _     _        _
!_!!_  _  _!!_ !_ !  !_      !!   _  _ !_!!_! _ !_ !_     _!
! !!_!!_ !_!!_ !  !_!! !  !!_!!_ ! !!_!!    !!   _!!_ !_!!_
$./a.out "Bad Form"
 _
 _
 _
$./a.out "Hello"
    _
!_!!_ !  !   _
! !!_ !_ !_ !_!
$./a.out "World"
 _
 _
 _

```

# Answer
# CJam, ~~123~~ ~~114~~ ~~112~~ 110 bytes

```
Qq_eu";=KMVWX":T&"@"@?" -chiou"Tereu{i"^A^W^G;^Þ¯     ^Þ^Û9³·^É¿»
^@
^P
^Ü^Ò½7¦^_¶´§=   ^O^V&5^U¯¼¹^T³6/"=i2b9Ue[3/"!_!"f.{S?}.+}/N*

```

The above uses caret notation, since the code contains unprintable characters. One of them is a null byte (`^@`), which means that this code can only be executed from the command line.

At the cost of only two more bytes (for a total of **112**), we can fix this.

```
Qq_eu";=KMVWX":T&"@"@?" -chiou"Tereu{i"AWG{ÞïIÞÛyó÷Éÿû
@
P
ÜÒýwæ_öôç}IOVfuUïüùTóvo"=i448+2b1>3/"!_!"f.{S?}.+}/N*

```

This time, all characters are printable. Try it online in the CJam interpreter.

### Example run

```
$ LANG=en_US
$ xxd -ps -r > 7seg.cjam <<< 51715f6575223b3d4b4d565758223a5426224022403f22202d6368696f752254657265757b69220117073b9eaf099e9b39b3b789bfbb0a000a100a9c92bd37a61fb6b4a73d090f16263515afbcb914b3362f223d6932623955655b332f22215f2122662e7b533f7d2e2b7d2f4e2a
$ wc -c 7seg.cjam
110 7seg.cjam
$ echo -n '0123456789 chiou-?' | cjam 7seg.cjam; echo
 _     _  _     _  _  _  _  _                       _
! !  ! _! _!!_!!_ !_   !!_!!_!    _ !_     _     _  _!
!_!  !!_  _!  ! _!!_!  !!_! _!   !_ ! !  !!_!!_!   !
$ echo -n 'ABCDEFGHIJLNOPQRSTUYZ' | cjam 7seg.cjam; echo
 _     _     _  _  _                 _  _  _     _           _
!_!!_ !   _!!_ !_ !  !_!  !  !!   _ ! !!_!!_! _ !_ !_ ! !!_! _!
! !!_!!_ !_!!_ !  !_!! !  !!_!!_ ! !!_!!    !!   _!!_ !_! _!!_
$ echo -n 'World' | cjam 7seg.cjam; echo
 _
 _
 _

```

### Idea (printable version)

Each character can be shown on the 9-segment display

```
!_!
!_!
!_!

```

by replacing some of its characters characters with spaces.

We can turn a specific character into an integer by replacing each shown segment, in natural reading order, with a **1**, each not shown segment with a **0** and considering the result binary digits.

The first and third segment are never shown, so this will produce integers in the ranges **\[0,64)** and **\[128,192)**.

We can encode each of these integers as a single byte, but half of them will result in unprintable characters. Thus, we add **64** to each integer before casting to character, which makes sure the code points are in the ranges **\[64,128)** and **\[192,256)**.

The only unprintable character in these two ranges is DEL (code point 127), which corresponds to the following, unsued display configuration:

```
!_!
!_!

```

We can reverse the above encoding by adding **448 == 512 - 64** to each code point, converting to base 2 and removing the first binary digit.

All that's left to to find an efficient way of associating these encoded segmenets with their corresponding ASCII characters.

If we map the characters of `" -chiou"` to the characters of `";=KMVWX"` and convert the entire input to uppercase, we can simply store encoding for all characters between `0` (code point 48) and `Z` (code point 90), giving a range of 43.

Array indexing is modular in CJam, so if `A` is a string of length 43, `A86=`, `A43=` and `A0=` all yield the same results. The character with code point 86 is `V`, so we simply store the encoded segments of **V - Z** and **0 - U**, in order.

In the actual code, we select the at sign as "bad form" character, replace the entire input with the string `"@"` if it contains a forbidden letter and reverse the steps from above.

### Code (printable version)

```
Q            e# Push an empty array for posterior concatenation.
q            e# Read from STDIN.
_eu          e# Copy the input and convert is to uppercase.
";=KMVWX":T& e# Intersect the result with with T := ";=KMVWX".
"@"@?        e# Select "@" if truthy and the input if falsy.
" -chiou"Ter e# Perform transliteration.
eu           e# Convert everything to uppercase.
{            e# For each character in the modified input:
  i          e#   Push its code point.
  "…"=       e#   Select the corresponding character from the string.
  i448+      e#   Push that character's code point and add 448.
  2b1>       e#   Convert to base 2 and discard the first digit.
  3/         e#   Group into triplets of digits (rows).
  "!_!"      e#   Push that string.
  f.{        e#   For each group of digits:
    S?       e#     Select the corresponding char of "!_!" for 1 and " " for 0.
  }          e#
  .+         e#   Concatenate along the rows with the previous results.
}/           e#
N*           e# Join, separating by linefeeds.

```
> 7 votes

# Answer
# Perl, ~~475~~ ~~469~~ ~~424~~ ~~390~~ ~~280~~ 272 bytes

```
$_=<>;die" -
"x3if/[kmvwx]/i;y/chiou/kmvwx/;$_=lc;while(/(.)/g){$z=ord($1=~y/a-z0-9\-\? /{v\x17nWS7z(.F\x16rb?[yBuV> f&|O?(Omxuw)\x7f}@K\0/r);$i.=$z&1?' _ ':$"x3;$m.=($z&16?'!':$").($z&64?'_':$").($z&8?'!':$");$p.=substr("  !  _!_",$z&6,2).($z&32?'!':$")}print"$i
$m
$p
"

```

multi-line with comments:

```
$_=<>;   # accept input
die" -   # check for invalid chars
"x3if/[kmvwx]/i;
y/chiou/kmvwx/;$_=lc;   # substitute invalid chars, convert to lowercase
while(/(.)/g)   # loop over each character
    # lookup character from string using transliteration and convert to
    # number using ord() for bit checking:
    {$z=ord($1=~y/a-z0-9\-\? /{v\x17nWS7z(.F\x16rb?[yBuV> f&|O?(Omxuw)\x7f}@K\0/r);
    $i.=$z&1?' _ ':$"x3;    # first row
    $m.=($z&16?'!':$").($z&64?'_':$").($z&8?'!':$");   # second row
    $p.=substr("  !  _!_",$z&6,2).($z&32?'!':$")}    # third row
# print result:
print"$i
$m
$p
"

```

The bit patterns encoding the segments are stored in a string (escaping 3 unprintable chars using `\x` and using `\0` for space) and are mapped to the input characters using the Perl transliteration operator.

For 5 of the 7 segments, a bitwise and is used along with the ternary operator to output a space or the segment character. For the bottom left two segments (encoded by 2 and 4 in the bitset), a substring lookup into an 8 character string is used to save 2 bytes.

Thanks to Dom Hastings for his Perl golfing tips.

**Old version (using regexes to encode the patterns), 390 bytes:**

```
$_=<>;if(/[kmvwx]/i){print" -\n"x3;exit}y/chiou/kmvwx/;$_=lc;while(/(.)/g){$z=$1;$i.=($z=~/[acefgopqsz\?0235-9]/?' _ ':'   ');$m.=($z=~/[abce-hlmopqstuy045689]/?'!':' ').($z=~/[abdefhkmnp-twyz\-\?2-689]/?'_':' ').($z=~/[adhijopquyz\?0-4789]/?'!':' ');$p.=($z=~/[a-hj-prtuwxz\?0268]/?'!':' ').($z=~/[b-egjklostuw-z0235689]/?'_':' ').($z=~/[abdg-jmnoqsu-y013-9]/?'!':' ')}print"$i\n$m\n$p\n"

```

multi-line with comments:

```
$_=<>;   # accept input
if(/[kmvwx]/i){print" -\n"x3;exit}   # check for invalid chars
y/chiou/kmvwx/;$_=lc;   # substitute invalid chars, convert to lowercase
while(/(.)/g)
{$z=$1;$i.=($z=~/[acefgopqsz\?0235-9]/?' _ ':'   '); # first row
$m.=($z=~/[abce-hlmopqstuy045689]/?'!':' ').
($z=~/[abdefhkmnp-twyz\-\?2-689]/?'_':' ').
($z=~/[adhijopquyz\?0-4789]/?'!':' '); # second row
$p.=($z=~/[a-hj-prtuwxz\?0268]/?'!':' ').
($z=~/[b-egjklostuw-z0235689]/?'_':' ').
($z=~/[abdg-jmnoqsu-y013-9]/?'!':' ')} # third row
print"$i\n$m\n$p\n" # print result

```

The string is read in and checked for invalid chars using a regex, exiting if any are found. Then the allowed lowercase chars are substituted for the invalid chars and the entire string is converted to lowercase.

The rows are generated one at a time, with 1 segment per letter on the first row and 3 on the other two. For each row, the string is processed one character at a time and the character is matched against a regex for each segment to check if a ! or _ should be displayed. Using a regex means that for characters where the segment is not set it takes zero bits per segment per character to encode whether to set it, and for those where it is it takes a little less than 8 bits on average because regex character ranges can be used. So it works out to around 3 or 4 bits per segment per character in the set, or around 21-24 bits per character.

It doesn't handle line-wrapping.
> 2 votes

# Answer
# Common Lisp, ~~488~~ 416

```
(lambda(z)(dotimes(r 3)(map()(lambda(c)(do((i 0(+ 17 i))n)((or(and(> i 901)(setf n 146))(=(char-code c)(ldb(byte 8 9)(setf n(ldb(byte 17 i)#36RIL884OIVFXJY4DCQ0O8DPH8MOMR2DSLPP3O4ESYHS234A9HEQYSV8IBDBZI6Z3C3MCVR77OYD3QN5G6CX2UQWGL4UY5R9PKYI1JQ5Y6DC27MQQGUZSCGI8Q9JCYP9N1L4YYKRWM1ZNMSVTSB4792UUWV6Z3906VSP981WCCBMDNJ02)))))(loop for v from(* 3 r)for d across"!_!"do(format t"~:[ ~;~A~]"(logbitp v n)d)))))z)(terpri)))

```

### Example

With `"abcdefg'hijklnopqrstuz"`, prints:

```
 _           _  _  _  _           _           _  _     _        _
!_!!_  _  _!!_ !_ !   _ !_   !  ! _ !   _  _ !_!!_! _ !_ !_     _!
! !!_!!_ !_!!_ !  !_! _ ! !  !!_! _ !_ ! !!_!!    !!   _!!_ !_!!_

```

### Remarks

Characters and their representations are encoded in this number in base 36:

```
IL884OIVFXJY4DCQ0O8DPH8MOMR2DSLPP3O4ESYHS234A9HEQYSV8IBDBZI6Z3C3MCVR77OYD3QN5G6CX2UQWGL4UY5R9PKYI1JQ5Y6DC27MQQGUZSCGI8Q9JCYP9N1L4YYKRWM1ZNMSVTSB4792UUWV6Z3906VSP981WCCBMDNJ02

```

The binary representation of this digit is divided in groups of 17 bits.

For example, the last group of 17 bits is `110000111101010`, which is decomposed here in two parts:

1. `110000`, the char-code of character `0`
2. `111101010`, an encoding of the drawing, best represented as follows:

```
010 (bits 0-2)         _
101 (bits 3-5)   =>   ! !
111 (bits 6-8)        !_!

```

Bits in first and last "column" are for `!` characters, the ones in the middle column for the `_` character. When necessary, both uppercase and downcase versions of a character are stored.

The function iterates three times over the input string, one for each line of output, searches for a matching character in the table (or defaults to 146, a.k.a. three bars), and prints the representation at current row.
> 1 votes

# Answer
# JavaScript (ES6), ~~380~~ ~~352~~ 324 bytes

(**Note:** Code uses caret notation, as it contains some unprintable characters. To get original code, click here and select the raw data. And no, `h` is not a CJam program. ;)

```
d=s=>{a=' ',u=n=>r>>n&1?'!':a,v=n=>r>>n&1?'_':a,g='ABCDEFGHIJLNOPQRSTUYZabcdefghijlnopqrstuyz0123456789-? ÿ',h='{vUnWSuz(lTb}[;B7V|>O{vFnWSur lTbf[;B7Vd>O}(O/:7w)^??^BK^0^G',x=y=z='';for(i=0;i<s.length;x+=a+v(0)+a,y+=u(4)+v(1)+u(3),z+=u(6)+v(2)+u(5)){q=g.indexOf(s[i++]);if(q<0)return d`ÿ`;r=h.charCodeAt(q)}return x+`
${y}
`+z}

```

Called as `d("7-seg display")` or similar. Works in Firefox 40, but may not in other browsers. For some reason, the HTML/JS snippet does not save the non-printables, but you can copy-paste the raw data from over here.

# Ungolfed:

(**Note:** `g` and `h` have been padded with spaces to match `8`, `-`, `ÿ` and `space` with their corresponding Unicode values.)

```
d = function (s) {
  t = function (n) { return Math.floor(n) % 2; };
  g = 'ABCDEFGHIJLNOPQRSTUYZabcdefghijlnopqrstuyz012345679? 8      -      ÿ      space ';
  h = '{vUnWSuz(lTb}[;B7V|>O{vFnWSur lTbf[;B7Vd>O}(O/:7w)?K \u007f \u0002 \u0007 \u0000';
  x = y = z = '';
  for(var i = 0; i < s.length; i++) {
    q = g.indexOf(s.charAt(i));
    if (q < 0)          // if g does not contain the character
      return d('ÿ');    // ÿ is equivalent to the error character, '\u0007'
    r = h.charCodeAt(q);
    x += ' ' + (r % 2 === 1 ? '_' : ' ') + ' ';
    y += (t(r / 16) === 1 ? '!' : ' ') + (t(r / 2) === 1 ? '_' : ' ') + (t(r / 8) === 1 ? '!' : ' ');
    z += (t(r / 64) === 1 ? '!' : ' ') + (t(r / 4) === 1 ? '_' : ' ') + (t(r / 32) === 1 ? '!' : ' ');
  }
  return x + '\n' + y + '\n' + z;
}

```

# Explanation:

I immediately noticed that the 7 segments, converted into `0`/`1` bits, would go well with the first 128 Unicode characters. The problem with this idea is that 1/4 of these characters are non-printable control characters. Using them in my code would make it look look incredibly messy (or incredibly intelligent; I haven't decided which one). To solve this while keeping the rest of the code simple, I came up with this idea:

With the exception of `-`, **space**, and **error**, none of the characters were missing both of the lower vertical segments. So to make sure that all those characters stayed between `0020` and `007f`, I simply mapped the **64** and **32** bits to these segments, like **so:**

```
     1
    ---
16 |   | 8
  2 ---
64 |   | 32
    ---
     4

```

The other 5 segments' numbers aren't too important; they could be arranged in any other way and still have all the same characters "in-bounds".

As an example, here's the encoded version of **A**:

```
     1
    ---
16 |   | 8
  2 ---
64 |   | 32

Dec: 64 + 32 + 16 + 8 + 2 + 1 = 123
Hex: 40 + 20 + 10 + 8 + 2 + 1 = 7B = u+007B = {

```

I then stuffed the encoded version of each 7-seg character in `h`. However, `8` resulted in `007f` (the **delete** control code; constant no matter how the segments are arranged), **space** resulted in `0000` (the **null** code; also constant), `-` resulted in `0002`, and **error** resulted in `0007`. I copy-pasted the raw bytes into the correct position for `8`, `-`, and **error**; **space** was easily achieved with `\0`.

After all this encoding, all I had to do was use it to decode the string and output it in a 7-seg readable format. I used a **for** loop and three variables (`x`, `y`, and `z`, each corresponding to an output line) to go through each character in the string and add its 7-seg equivalent to the output. I chose `ÿ` for the **error** character because AFAIK, it's not on any keyboard, and it's the last character in the `u+0000-u+00ff` range. Perhaps I could have been witty and chosen `Ξ` (Greek letter xi) instead.... ;)

**Edit 1:** Saved a bunch of space by creating mini-functions to determine whether `!`, `_`, or  is needed.

**Edit 2:** Saved a bunch more space using the tricks I've learned since I last visited this post.

As usual, suggestions are greatly appreciated!
> 1 votes

---
Tags: code-golf, ascii-art
---


title: What day is it (on Flooptonia)?

text:
# Question
Title: What day is it (on Flooptonia)?
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
# 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.

Test Suite.
> 14 votes

# 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)*
> 19 votes

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

Enlarged (Codel width of 10):
> 13 votes

# 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

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

```
> 12 votes

# 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.

If the permalink doesn't work in your browser, you can copy the code from this paste.

### 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.

```
> 7 votes

# 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.
> 6 votes

# 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"

```
> 5 votes

# 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.
> 4 votes

# 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>`
> 3 votes

# 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 ]);
    }
}

```
> 3 votes

# 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
> 3 votes

# 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" : "");
    }
}

```
> 3 votes

# 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.
> 2 votes

# 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

```
> 2 votes

# 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.
> 2 votes

# 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
> 1 votes

# 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`) 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>
```
> 1 votes

# 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.
> 1 votes

# 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 chat participants.*
> 1 votes

# 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

```
> 1 votes

# 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");}

```
> 0 votes

---
Tags: code-golf, date
---


title: Retina or Trash?

text:
# Question
Title: Retina or Trash?
We live in a wonderful age of technology where we can have beautifully detailed 8K screens on our TVs, and even 2K displays on our phones for our mobile browsing pleasure. We've come a long way in recent years in terms of screen technology.

One of the products of this is a term that was made popular by Apple, *Retina*. This is referring to the pixel density of the display in question being so high, that at a viewing distance of 10-12 inches away, individual pixels cannot be easily picked out.

Steve Jobs said that the pixel density where this occurs is right around **300 pixels per inch**, and they started employing pixel densities in this range on their devices with the *Retina* buzzword used for advertising.

Pixel density can be calculated by the following formula:

Where `d` is the diagonal of the screen in inches, `w` is the number of pixels on the horizontal axis, and `h` is the number of pixels on the vertical axis.

# Your Task

For this task, you'll be using the *Retina* standard to decide what products are worth buying. Being the modern consumer that you are, when you shop for devices you want to make sure that you're getting a good product, not some device from the 90s! As such, you want to build a *program or function* that takes the screen width, height and diagonal length as **input or function parameters**, and tells you whether the particular screen qualifies as a retina screen (`D > 300`) by *printing to the screen or returning*.

Due to your contempt for non-Retina devices, your *program or function* will output `Retina!` when the device qualifies, and `Trash!` when it does not.

You may assume that all of the numbers will be greater than 0. Pixel values for width and height will always be whole numbers. Screen size may be interpreted in any way, as long as it supports decimals. The input may be in any order you choose, and may also be on up to 3 separate lines.

# Example I/O

```
1920 1080 4.95   -> Retina!
2560 1440 5.96   -> Retina!
1920 1080 10.5   -> Trash!
10 10 0.04       -> Retina!
4096 2160 19(.0) -> Trash!
8192 4320 100.00 -> Trash!
3000 1500 11.18  -> Retina!
180 240 1(.0)    -> Trash!

```

---

This is , so the fewest number of bytes wins.

---

Here's a Stuck solution, a stack based programming language I'm making:

```
r;`;/300>"Retina!""Trash!"?

```

# Answer
> 5 votes
# Pyth - 27 bytes

Uses ternary operator and `abs` to calculate pythagorean.

```
?>c.avzQ300"Retina!""Trash!

```

Takes input in two lines, first line `width, height`, second line `diag`.

The rules were relaxed so rolling back.

Try it online here.

# Answer
> 116 votes
# Retina, ~~530~~ ~~220~~ ~~210~~ ~~202~~ ~~201~~ ~~193~~ ~~191~~ ~~187~~ 185 (184) bytes

*Credits to randomra for saving 3 bytes!* (And paving the way for a couple more.)

```
+`\.(\d)(.+)( .+)
$1.$2_$3_
\b
#
+`(\d*)#((((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|\w)
$1$1$1$1$1$1$1$1$1$1$3$4$5$6$7$8$9$10$11#
\d
11
(?=(1*)\1)[^.]
$1
^(1+)\.\1{90000}1+
Retina!
1.+
Trash!

```

For byte-counting purposes, each line goes in a separate file, but you can run the above code as is from a single file by invoking Retina with the `-s` flag.

This expects the density first (which *must* contain a decimal point, even if it's a trailing one), followed by width and height, i.e. `d w h`.

This is a *bit* slow. I wouldn't try most of the given test cases, because it will run for ages. However, you can check that it works correctly with the test cases

```
19. 4096 2160     -> Trash!
1. 180 240        -> Trash!
1. 181 240        -> Retina!
1. 180 241        -> Retina!
0.04 10 10        -> Retina!

```

Basically, after multiplying all numbers through to make the density an integer, you don't want the width and height to have more than 4 digits.

While this is slow, it is completely exact... there are no floating point issues or anything like that. All arithmetic is using (unary) integers.

In principle, I could shave off one more byte: the `^` can be omitted, but it will make `Trash!` test cases horribly slow due to excessive amounts of backtracking.

## Explanation

First, let's rearrange the inequality to avoid floating point operations:

```
√(w<sup>2</sup> + h<sup>2</sup>) / d > 300
√(w<sup>2</sup> + h<sup>2</sup>) > 300 d
w<sup>2</sup> + h<sup>2</sup> > 90000 d<sup>2</sup>

```

We can also notice that this is invariant under multiplying `w`, `h` and `d` by the same number `x`:

```
w<sup>2</sup> + h<sup>2</sup> > 90000 d<sup>2</sup>
(x w)<sup>2</sup> + (x h)<sup>2</sup> > 90000 (x d)<sup>2</sup>
x<sup>2</sup> (w<sup>2</sup> + h<sup>2</sup>) > 90000 x<sup>2</sup> d<sup>2</sup>
w<sup>2</sup> + h<sup>2</sup> > 90000 d<sup>2</sup>

```

There are several ways to square a unary number, but we'll be making use of the identity

```
n<sup>2</sup> = Σ<sub>i=1..2n</sub> ⌊i/2⌋

```

This gives us a way to solve the problem using only integer arithmetic (representing integers in unary).

Let's go through the code. Each pair of lines is a regex substitution.

```
+`\.(\d)(.+)( .+)
$1.$2_$3_

```

This repeatedly moves the decimal point in the density to the right while multiplying width and height by 10 (the `x` above). This is to ensure that all numbers are integers. Instead of appending zeroes, I'm appending `_`, which I'll be treating as zero later on. (This is a golfing trick, because otherwise I'd need to write `...${3}0` to avoid ambiguity with `$30`.) The `+` in front of the regex tells Retina to repeat this substitution until the result stops changing (which is the case when the pattern no longer matches).

```
\b
#

```

We're preparing the three numbers for conversion to unary now. In principle, we need a marker (the `#`) in front of each number, but it's shorter to add one to the end of each number as well, which won't affect the conversion step.

```
+`(\d*)#((((((((((9)|8)|7)|6)|5)|4)|3)|2)|1)|\w)
$1$1$1$1$1$1$1$1$1$1$3$4$5$6$7$8$9$10$11#

```

This is the conversion to unary, using a trick that has been developed by dan1111. Essentially I'm translating each digit to a rep-digit of itself, while multiplying the existing digits by 10 (moving the `#` marker to the right in the process). This binary representation will be quite a jumble of different digits, but the total number will be equal to the value of the original integer. Note the `\w` at the end - normally this is just `0`, but we want to treat `_` as zero as well (which is considered a word character in regex).

```
\d
11

```

We turn each digit into two `1`s, thereby a) ensuring all digits are the same (which will be necessary later) and b) doubling each of the numbers.

```
(?=(1*)\1)[^.]
$1

```

This does two things: it squares all numbers (or rather half of each number, by computing a sum over `2n`), and adds the resulting squares of the width and the height. Notice that `[^.]` matches `1`s, `#` markers and spaces. If it's a `#` or a space, the lookahead won't capture anything, which means all of those are simply removed, i.e. the results for the width and height are concatenated/added. The decimal point `.` remains to separate the result for `d` from those. If `[^.]` matches a `1` instead, then the lookahead ensures that we capture half of the `1`s after it (rounded down) in group `1`. This computes the sum I mentioned above, which will then yield the square of the original number.

```
^(1+)\.\1{90000}1+
Retina!

```

The string is now `d<sup>2</sup>` (in unary), then `.`, then `w<sup>2</sup> + h<sup>2</sup>` (in unary). We want to know if the first unary number times `90000` is shorter than the second. We can easily do this multiplication using a capturing group and `{n}` repetition syntax. We use `1+` (instead of `1*`) afterwards to ensure that the second number is actually *greater* than that and not just equal. If so, we replace all of that by `Retina!`.

```
1.+
Trash!

```

If the second number wasn't big enough, then the previous step won't have changed anything and the string will still start with a `1`. If that's the case, we just replace the entire string by `Trash!` and are done.

# Answer
> 38 votes
## Python, 49

```
lambda w,h,d:"RTertaisnha!!"[w*w+h*h<=9e4*d*d::2]

```

Uses string interleaving.

It turned out shorter to square both sides than to use the complex norm.

```
w*w+h*h<=9e4*d*d
abs(w+1j*h)<=300*d

```

# Answer
> 14 votes
# CJam, ~~30 29~~ 27 bytes

```
q~mh300/<"Retina""Trash"?'!

```

Requires input to be in form of `diagonal width height`

*UPDATE: 1 byte saved thanks to Dennis!*

Try it online here

# Answer
> 14 votes
# Retina, 312 bytes

```
(\d+) (\d+) (\d+)(?:\.(\d+))?
a$1bc$2dj300ke$3fg$4h9iiiiiiiii8iiiiiiii7iiiiiii6iiiiii5iiiii4iiii3iii2ii1i0
+`(b.*)(d.*)fg(\d)
0$10$2$4fg
+`(a|c|e|j)(\d)(\d*)(i*)((?:b|d|f|k).*h.*\2(i*))
$1$3$4$4$4$4$4$4$4$4$4$4$6$5
g`(i+)
Q$1R$1
+`Q(i+)Ri
$1Q$1R
+`(j(i*).*e)i(.*f)
$1$3$2
a(i*).*c(i*).*f\1\2.*
Trash!
.*0
Retina!

```

This does take quite a while to run, but it seems to work.

Probably could be golfed a lot more...

## Explanation:

```
(\d+) (\d+) (\d+)(?:\.(\d+))?
a$1bc$2dj300ke$3fg$4h9iiiiiiiii8iiiiiiii7iiiiiii6iiiiii5iiiii4iiii3iii2ii1i0

```

Add tags to make the string more convenient to parse, and add some junk to make it easier to convert to base 1, and add a 300 to multiply by later

```
+`(b.*)(d.*)fg(\d)
0$10$2$4fg

```

Append `0`s to the width and height, while appending the decimal part of the diagonal to the integer part. When this is done, the diagonal will be an integer, and the width and height will be multiplied by however many `10`s were necessary.

```
+`(a|c|e|j)(\d)(\d*)(i*)((?:b|d|f|k).*h.*\2(i*))
$1$3$4$4$4$4$4$4$4$4$4$4$6$5

```

Convert all numbers to base 1, using the lookup-table I appended in the first step

```
g`(i+)
Q$1R$1

```

Prepare to square all of the numbers

```
+`Q(i+)Ri
$1Q$1R

```

Square each number

```
+`(j(i*).*e)i(.*f)
$1$3$2

```

Multiply the square of the diagonal by the square of the 300 we inserted in the first step

```
a(i*).*c(i*).*f\1\2.*
Trash!

```

If the width appended to the height fits in the product we just computed, the pixel density is too low, and it's Trash!

```
.*0
Retina!

```

Otherwise, it's Retina!

# Answer
> 9 votes
# JavaScript ES6, 49 bytes

```
(w,h,d)=>Math.hypot(w,h)/d>300?'Retina!':'Trash!'

```

I hate that JavaScript has such long math operators. But even if there was a `Math.pythagorean` this would be shorter.

# Answer
> 9 votes
# APL, ~~40~~ 36 bytes

Saved 4 bytes thanks to Dennis!

```
{(9E4×⍵*2)<+/⍺*2:'Retina!'⋄'Trash!'}

```

This creates an unnamed dyadic function that takes the first two arguments on the left and the third on the right. It checks whether the sum of the squares of the left values is greater than 300^2 times the square of the right one. Output is printed accordingly.

You can try it online!

# Answer
> 9 votes
# TI-BASIC, 43

Takes width and height through the homescreen as a two-element list, and diagonal through Input.

```
Input D
If 300D>√(sum(Ans²
Then
Disp "Retina!
Else
"Trash!

```

TI-BASIC's two-byte lowercase letters add 7 bytes (`i`, being the imaginary unit, is one byte) cause it to be quite uncompetitive. Thankfully, `!` is also one byte because it represents the factorial function.

# Answer
> 8 votes
## Excel, 44 bytes

Type your inputs in these cells.

* A1 = Width in pixels
* B1 = Height in pixels
* C1 = Diagonal in inches

And this formula gives your result:

```
=IF((300*C1)^2<A1^2+B1^2,"Retina!","Trash!")

```

# Answer
> 7 votes
# Prolog, 51 bytes

```
a(W,H,D,R):-9e4*D*D<W*W+H*H,R="Retina!";R="Trash!".

```

Running `a(8192,4320,100.0,R).` outputs: `R = "Trash!" .`

Edit: Thanks to @PaulButcher for correcting an edge case and golfing one byte.

# Answer
> 5 votes
# , ~~40~~ 37 bytes

```
jjjrmd\/'īu>{"Retina!"p}{"Trash!"p}?

```

A lot of bytes for the input formatting :\

Try it online

# Answer
> 5 votes
## JavaScript (ES6), 45 bytes

```
f=(w,h,d)=>w*w+h*h>d*d*9e4?'Retina!':'Trash!'

```

## CoffeeScript, 47 bytes

No ternary operator, but there is exponentiation (which doesn't help in the latest attempt).

```
f=(w,h,d)->w*w+h*h>d*d*9e4&&'Retina!'||'Trash!'

# Previous attempt
f=(w,h,d)->(w*w+h*h)**.5/d>300&&'Retina!'||'Trash!'

```

# Answer
> 5 votes
# Pure Bash (no bc/other external commands), ~~138~~ ~~136~~ ~~135~~ ~~82~~ 83 bytes

```
a=${3#*.}
d=${a//?/0}
r=(Trash Retina)
echo ${r[$1$d**2+$2$d**2>90000*${3/./}**2]}!

```

I decided to try doing it in pure bash. I've probably made a few obvious inefficiencies as this is my first time code golfing, but I am VERY familiar with bash and have had fun in the past trying to write things that don't use any external commands (ie pure bash).

~~The printf statement is the most annoying. Anyone got any better ideas for padding numbers with zeroes?~~

EDIT: Saved two bytes, turns out printf will take an empty argument for zero. Saved another byte, turns out I'd previously miscounted and just assigning the output of printf to a variable is smaller than using -v.

EDIT2: Thanks to Digital Trauma in the comments, this is now down much more significantly. Tricks: using bash's regex support to replace the string of digits with zeroes instead of counting it then printing that number of zeroes (seems obvious when I put it like that...), storing the strings in a bash array to save an echo, and taking into account a slight change in rules that means you can end all input numbers in .0.

EDIT3: Added a byte to fix bug introduced by Digital Trauma's suggested modification.

# Answer
> 4 votes
# dc, 41 bytes

```
[[Retina!]pq]sr?d*rd*+vr/300<r[Trash!]p

```

Requires args to be input in `d, w, h` order - I hope this is OK.

### Test output:

```
$ for t in \
> "4.95 1920 1080" \
> "5.96 2560 1440" \
> "10.5 1920 1080" \
> "0.04 10 10" \
> "19 4096 2160" \
> "100.00 8192 4320" \
> "11.18 3000 1500" ; do \
> echo $t | dc -e'9k[[Retina!]pq]sr?d*rd*+vr/300<r[Trash!]p'
> done
Retina!
Retina!
Trash!
Retina!
Trash!
Trash!
Retina!
$

```

# Answer
> 3 votes
# Julia, ~~46~~ ~~45~~ 42 bytes

```
f(w,h,d)=w^2+h^2>9e4d^2?"Retina!":"Trash!"

```

This creates a function that accepts three numeric values and returns a string.

It's a direct implementation of the formula, just rearranged a bit. Both sides of the inequality were multiplied by `d` then squared.

# Answer
> 3 votes
# R, ~~59~~ 55 Bytes

As an unnamed function now

```
function(h,w,d)if(h^2+w^2>9e4*d^2)'Retina!'else'Trash!'

```

Very simple implementation, that eliminates the need for the index references.

**Previous**

```
cat(if((n=scan()^2)[1]+n[2]>9e4*n[3])'Retina!'else'Trash!')

```

Fairly simple, get the input from scan into a vector (single line, space separated or multi-line). Square the vector. Do the calculation and cat the result.

# Answer
> 3 votes
# MATLAB - ~~49~~ 45 bytes

```
c={'Trash!','Retina!'};c{(w*w+h*h>9e4*d*d)+1}

```

I first had to declare a cell array which contains `Trash!` and `Retina!` which are stored in locations 1 and 2 in the cell array. Next, I use the observation observed by many to rearrange the equation so that you are checking for the condition only using integer arithmetic. I represented 90000 as `9e4` to save some bytes. If this condition is true, we output a 1, else we output a 0. I use this output to index directly into the cell array. Because MATLAB starts indexing at 1, I also had to add 1 to complete the indexing. What's nice is that adding `true` with 1 gives 2, while adding `false` with 1 gives 1. This will output either `Trash!` or `Retina!` in the MATLAB command prompt.

# Example

```
>> w=1920;h=1080;d=4.95;
>> c={'Trash!','Retina!'};c{(w*w+h*h>9e4*d*d)+1}

ans =

Retina!

```

# Answer
> 3 votes
# XSLT, 400 bytes

This is the debut of a never-before seen language on PPCG, and I hope to use it more in the future as I get to know it more.

## Code:

```
<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="input"><xsl:variable name="n" select="for $i in tokenize(.,'[^\d\.]+')return number($i)" /><xsl:choose><xsl:when test="$n[1]*$n[1]+$n[2]*$n[2]>90000*$n[3]*$n[3]">Retina!</xsl:when><xsl:otherwise>Trash!</xsl:otherwise></xsl:choose></xsl:template></xsl:stylesheet>

```

### Pretty Printed

```
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="input">
        <xsl:variable name="n" select="for $i in tokenize(.,'[^\d\.]+')return number($i)" />
        <xsl:choose>
            <xsl:when test="$n[1]*$n[1]+$n[2]*$n[2]>90000*$n[3]*$n[3]">
                Retina!
            </xsl:when>
            <xsl:otherwise>
                Trash!
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

```

## Notes:

As XSLT has no way of taking input via STDIN, we have to use an XML file, with the input between two `<input>` tags. Of course, this method has its limitations but it will work perfectly well for most challenges.

## Example I/O

### Input file:

```
<?xml version="1.0" encoding="ISO-8859-1"?>
<input>3000 1500 11.18</input>

```

### Output file:

```
<?xml version="1.0" encoding="UTF-8"?>Retina!

```

---

### Input file:

```
<?xml version="1.0" encoding="ISO-8859-1"?>
<input>1920 1080 10.5</input>

```

### Output file:

```
<?xml version="1.0" encoding="UTF-8"?>Trash!

```

# Answer
> 2 votes
# Bash, 85 bytes

```
if [ $(echo "sqrt($1^2+$2^2)/$3"|bc) -gt 300 ];then
echo Retina!
else
echo Trash!
fi

```

# Answer
> 2 votes
## C# (81)

```
string D(int w,int h,double d){return Math.Sqrt(w*w+h*h)/d>300?"Retina":"Trash";}

```

Ungolfed:

```
string Density(int width, int height, double diagonal)
{
    return Math.Sqrt(width * width + height * height) / diagonal > 300 ? "Retina" : "Trash";
}

```

# Answer
> 2 votes
## Swift, 77 bytes

Function parameter declerations mean this takes up way more characters than it should:

`func r(w:Float,h:Float,d:Float){print((w*w+h*h)>9e4*d*d ?"Retina!":"Trash!")}`

# Answer
> 2 votes
**C++ 72 70 Byte**

```
void F(int w,int h,float d){cout<<w*w+h*h>9e4*d*d?"Retina!":"Trash!";}

```

Similiar to other solutions, figured out myself to warm up with code golf.

# Answer
> 2 votes
# PHP, 47,43,40 38 bytes

```
<?=sqrt($w*$w+$h*$h)/$d>300?'Retina':'Trash'?>!
<?=sqrt($w*$w+$h*$h)/$d>300?Retina:Trash?>!
<?=$w*$w+$h*$h>9e4*$d*$d?Retina:Trash?>!

```

```
<?=hypot($w,$h)/$d>300?Retina:Trash?>!

```

Requires `register_globals==true` (which it should never be!), with GET values w,h,d
\- Saved 4 bytes by removing quotes around string. Bad coding, but it works.
\- Moved `d` and square root to the other side of the equation, saving the `sqrt()` function
\- Saved 2 bytes by switching to `hypot()` (thank you Lucas Costa)

# Answer
> 2 votes
# Swift, 56 bytes

```
let r={print($0*$0+$1*$1>9e4*$2*$2 ?"Retina!":"Trash!")}

```

Basically the same as GoatInTheMachine's but with implicit closure parameters

When Code Golfing with Swift, always declare methods like this, it's much shorter

# Answer
> 2 votes
## Haskell, 46

```
f w h d|w^2+h^2>d^2*9e4="Retina!"|0<1="Trash!"

```

# Answer
> 2 votes
Here is my contribution for this problem

## Ruby, 67 bytes reading from stdin

```
w,h,d=ARGV.map{|v|Float(v)}
puts w*w+h*h>d*d*9e4?"Retina!":"Trash!"

```

## Ruby, 56 bytes in a function

A bit shorter

```
def r(w,h,d)
puts w*w+h*h>d*d*9e4?"Retina!":"Trash!"
end

```

Thanks to the previous contributors for the 9e4!

# Answer
> 2 votes
# C# 6, 67 Bytes

```
string D(int w,int h,double d)=>w*w+h*h>9e4*d*d?"Retina!":"Trash!";

```

This answer is based on Wolfsheads answer. I made it 8 bytes shorter using a new feature of C# 6.

# Answer
> 2 votes
# JavaScript (ES6) 58 54 43 Bytes

### 43 Bytes

Removed function assignment (as per PPCG rules) (-2), as well as remove square root and comparing to 900 (300^2) (-12)

```
(w,h,d)=>w*w+h*h/d*d>300?"Retina!":"Trash!"

```

### 54 Bytes

Got rid of unnessesary parentheses (-4 bytes)

```
a=(w,h,d)=>Math.sqrt(w*w+h*h)/d>300?"Retina!":"Trash!"

```

### 58 Bytes

```
a=(w,h,d)=>Math.sqrt((w*w)+(h*h))/d>300?"Retina!":"Trash!"

```

Explanation here:

```
a =                           // The function is a
 (w,h,d) =>                   // Accepts the three arguments
   Math.sqrt((w*w)+(h*h))/d   // Calculate pixel density
   > 300                      // Above the threshold
   ? "Retina!"                // If so, return "Retina!"
   : "Trash!"                 // Otherwise return "Trash!"

```

This uses ternary operators to test the density and kills a couple of bytes by using arrow functions

# Answer
> 1 votes
## **Pyth, ~~34 32~~ 31 bytes**

My first attempt at golfing with Pyth, comments/criticisms are welcome!

```
?<.)Jrz7c.aJ300"Retina!""Trash!

```

Explaination:

```
     rz7                            Split the input on spaces and eval
    J                               Store the result list in J
  .)                                Take the last element from the list
         .aJ                        Find the vector length of the remaining elements
        c   300                     Divide this by 300
?<             "Retina!""Trash!     Ternary comparison and output

```

*Edit: replaced slice with pop to save 2 bytes*

*Edit 2: inline assignment to save 1 byte - thanks to isaacg*

# Answer
> 1 votes
# Java, ~~82~~ 74 bytes

```
String g(int w,int h,double d){return 9e4*d*d>w*w+h*h?"Trash!":"Retina!";}

```

Call it with `g(width,height,diagonal)`

# Answer
> 1 votes
# Javascript, ~~87~~ 69 bytes

OK, I'm rather late to the party and this isn't a great score, but:

```
function r(w,h,d){return Math.sqrt(w*w+h*h)/d>300?"Retina!":"Trash!"}

```

which translates to this in readable code:

```
function r(w, h, d) {
    return (Math.sqrt(w * w + h * h) / d) > 300     // if term > 300
        ? "Retina!"    // return "Retina!"
        : "Trash"!"    // otherwise return "Trash!"
}

```

# Answer
> 1 votes
# Clojure, 58 bytes

```
#(if(>(+(* %1%1)(* %2%2))(* %3%3 90000))"Retina!""Trash!")

```

Used @Kroltan's fancy math to shorten this. Uses implicit arguments passed in the order of (w, h, d).

First Clojure golf...I was surprised how much whitespace I am allowed to leave out

# Answer
> 1 votes
# C#, 74 bytes

```
string D(int w,int h,double d){return w*w+h*h>9e4*d*d?"Retina!":"Trash!";}

```

Based on the answer by Abbas, but without the need for the square root or the additional space :-).

Also the original version returned "Retina" and "Trash" without the exclamation marks...

I had to post as a new answer due to lack of reputation :-(

# Answer
> 1 votes
## **Groovy, 49 bytes**

My first attempt at golfing whatsoever, hello everyone!

```
def f(w,h,d){h*h*+w*w>9e4*d*d?'Retina!':'Trash!'}

```

# Answer
> 0 votes
# C macro, 73 (56) bytes

73 including "#include"s, 56 excluding them. They are technically unnecessary for the code to compile and run under GCC. I'm going to assume here that macro parameters count as function parameters, and that the result after executing the substituted code counts as its return value.

```
#include<math.h>
#define r(w,h,d) (hypot(w,h)/(d)>300?"Retina!":"Trash!")

```

If you make the assumption that this only takes literals, function return values or single variables as parameters (rather than any expressions), and is inserted in a position where it will be either assigned directly to a variable or inserted directly into an argument list, you can drop 4 bytes by removing the enclosing parentheses and those around "d".

Similarly, if it needs to be used as a statement which prints the result instead of substituting it, just add 4 bytes by sticking "puts" before the opening parenthesis before `hypot`. (And 18 for `#include<stdio.h>` \+ newline)

## (Lazily-written) test case:

```
#include <stdio.h>
/* ..golfed code goes here.. */
main() {
    puts(r(1920,1080,4.95));
    puts(r(2560,1440,5.96));
    puts(r(1920,1080,10.5));
    puts(r(10,10,0.04));
    puts(r(4096,2160,19));
    puts(r(8192,4320,100.00));
    puts(r(3000,1500,11.18));
    puts(r(180,240,1));
}

```

# Answer
> 0 votes
## Matlab, 60 bytes

Using an anonymous function:

```
f=@(w,h,d)char('retina!'+(hypot(w,h)<=300*d)*('epPm]#b'-99))

```

Examples:

```
>> f=@(w,h,d)char('retina!'+(hypot(w,h)<=300*d)*('epPm]#b'-99))
f =
    @(w,h,d)char('retina!'+(hypot(w,h)<=300*d)*('epPm]#b'-99))

>> f(1920,1080,4.95)
ans =
retina!

>> f(1920,1080,10.5)
ans =
trash!

```

# Answer
> 0 votes
# Powershell, 69

Using the same approach as many others here..

```
function d($w,$h,$d){@('Trash!','Retina!')[$w*$w+$h*$h-gt9e4*$d*$d]}

```

# Answer
> 0 votes
# Perl, 43 bytes

```
print<>**2+<>**2><>**2*9E4?Retina:Trash,v33

```

Expects width, height and diagonal on STDIN, one per line.

---
Tags: code-golf
---


title: MIRROR | ЯOЯЯIM

text:
# Question
Title: MIRROR | ЯOЯЯIM
## Challenge

Given the equation of a line and the coordinates of the vertices of a shape, output the coordinates of the shape when reflected across the given line.

## Further Information

The line's equation will be given with a `y` and an `x` separated by an equals sign (there may not always be a `y` and an `x`). Some examples:

```
y=x
y=5.0
y=2.4x
x=6.6
y=2.0x+5.0
x=2.0y

```

The equation will always be supplied as a string.

The line will *always* be linear.

The equation will only contain `+`s or `-`s and any multiplication will be before an `x` or a `y`. The `*` is not used however, and the number will be placed directly before the variable.

A `0.0` is never used in the equation because there is no need for it to be shown.

The coordinates will be an array of length `n>2` of arrays of length `2`. Outputted coordinated must also be in a similar array.

No numbers supplied will be greater than `(2^32)-1` or less than `-((2^32)-1)`. All supplied numbers will be floats, and the output is expected to be the same.

The program may either be a full program or a function (a function may be easier for passing the coordinates).

## Example

```
Input: y=5.0 [(0.0,0.0),(0.0,4.0),(5.0,0.0),(5.0,4.0)]
Output: [(0.0,10.0),(0.0,6.0),(5.0,10.0),(5.0,6.0)]

Input: x=3.5y [(1.14,2.04),(4.16,5.86),(6.02,0.86),(4.2,2.44)]
Output: [(2.05,-1.13),(6.63,-2.78),(5.57,2.45),(4.86,0.15)]

```

## Winning

The shortest program in bytes wins.

# Answer
# მƧƎ ɈqiɿɔƧɒvɒႱ, ~~54~~ ~~47~~ ~~88~~ ~~65~~ ~~60~~ 67 bytes

<sub>**JavaScript ES6**</sub>

I've updated to the new question specifications.

```
(a,b)=>b.map(l=>([y,x]=l,l[g=a[0]>'x']+=l[g]-eval(a.slice(2))*2,l))

```

I've defined variables x and y to their corrosponding value so we can eval the expression to get the value. Using `[x,y]=l`, we can easilt set x to `l[0]` and y to `l[1]`

```
(a,b)=>b.map(l=>([x,y]=l,l[a[0]<'y'|0]+=eval(a.slice(2)),l))

```

Broken up:

```
(a,b)=>  // Function with args: a and b
  b.map(l=> . Loops through b
    (
      l[ // Gets x or y depending on condition
         a[0]<'y'|0 // x returns 0, y returns 1
      ]
      += // plus...
      eval( // evaluate the following expression
        a.slice(2).replace( // Replace the input expression
          /x|y/g, // Match 'x' and 'y'
          l=>
             `*l[${l<'y'|0}]`) // Multiple previous value by corresponding value
        )
    ,l)) // Returns new coordinates

```

---

The old version which didn't expect variables on the right-hand side, **(47 bytes)**
```
(a,b)=>b.map(l=>(l[a[0]<'y'|0]+=+a.slice(2),l))

```

Running it (second example):

```
[[2.05, -1.13], [6.63, -2.78], [5.57, 2.45], [4.86, 0.15]]

```
> 6 votes

---
Tags: code-golf
---


title: Marching Squares Lookup

text:
# Question
Title: Marching Squares Lookup
Marching Squares is an algorithm from computer graphics, which is used to recover 2D isocontours from a grid of samples (see also, its big brother Marching Cubes for 3D settings). The idea is to process each cell of the grid independently, and determine the contours passing through that cell based on the values at its corners.

The first step in this process is to determine which edges are connected by contours, based on whether the corners are above or below the value of the contour. For simplicity, we'll only consider contours along the value `0`, such that we're interested in whether the corners are positive or negative. There are `2<sup>4</sup> = 16` cases to distinguish:

Image Source: Wikipedia

The identification of white and black doesn't really matter here, but for definiteness say that white is positive and black is negative. We will ignore cases where one of the corners is exactly `0`.

The saddle points (cases 5 and 10) provide a little extra difficulty: it's not clear which diagonals should be used by only looking at the corners. This can be resolved by finding the average of the four corners (i.e. an approximation of the centre value), and choosing the diagonals such that the contours separate the centre from the corners with the opposite sign. If the average is exactly `0`, either case can be chosen.

Normally, these 16 cases are simply stored in a lookup table. This is great for efficiency, but of course, we'd prefer the code to be *short* around here. So your task is to perform this lookup step and print an ASCII representation of the case in as little code as possible.

## The Challenge

You're given the values of the four corners (non-zero integers) in a fixed order of your choice. You should then generate the correct layout of the contours, correctly resolving the saddle point cases.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Input may be taken in any convenient string or list format.

The 16 cases will be represented in ASCII art using one of the following 5x5 blocks:

```
o---o  o---o  o---o
|   |  |   |  | | |
|   |  |---|  | | |
|   |  |   |  | | |
o---o  o---o  o---o

o---o  o---o  o---o  o---o
|/  |  |  \|  |   |  |   |
|   |  |   |  |   |  |   |
|   |  |   |  |\  |  |  /|
o---o  o---o  o---o  o---o

o---o  o---o
|/  |  |  \|
|   |  |   |
|  /|  |\  |
o---o  o---o

```

You must not print any leading or trailing whitespace, but you may print a single optional newline.

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

## Test Cases

The test cases assume that input is given in order *top-left*, *top-right*, *bottom-left*, *bottom-right*. Test cases are presented in 9 groups, one corresponding to each of the 9 representations given above (in the same order, starting from the empty cell, ending with the two saddle points).

```
[1, 2, 1, 3]
[-9, -2, -2, -7]

[4, 5, -1, -2]
[-1, -2, 3, 4]

[7, -7, 7, -7]
[-5, 5, -5, 5]

[1, -6, -4, -1]
[-2, 3, 3, 4]

[-1, 6, -4, -1]
[2, -3, 3, 4]

[-1, -6, 4, -1]
[2, 3, -3, 4]

[-1, -6, -4, 1]
[2, 3, 3, -4]

[3, -8, -9, 2]
[-3, 8, 9, -2]

[8, -3, -2, 9]
[-8, 3, 2, -9]

```

Additionally, the following test cases may return either of the saddle points (your choice):

```
[1, -4, -2, 5]
[-1, 4, 2, -5]

```

# Answer
> 5 votes
# Ruby, ~~201 180~~ 176

This is an anonymous lambda function, to be called in the way shown in the ungolfed example.

This contains no variable `s`. In the ungolfed version a complex expression is assigned to `s` for clarity, before it is used. 4 bytes are saved in the golfed version by putting it inline. The only other difference between the versions is the whitespace and comments.

If it is acceptable to return the output as an array of five strings of five characters, instead of printing to stdout, one more byte can be saved.

```
->a{p=t=0
4.times{|i|t+=a[i]*=a[3];p+=a[i]>>9&1<<i}
q=p==6&&t>0?19:'@AC@P*10'[p].ord
puts c='o---o',(0..2).map{|i|b=p*i==3?'|---|':'|   |';b[q%4]='|/|\|/'[q%4+(i&2)];q/=4;b},c}

```

I'm happy with the parsing of the array, but I think there may be shorter ways to form the output.

All four elements of the input array are multiplied by the last element. This guarantees that the last element is positive, and reduces the number of cases from 16 down to 8. The elements are rightshifted 9 places, so that all positive numbers become 0 and all negative numbers become -1 (at least in the range of input given in the test cases.) They are then ANDed by `1<<array index` to give a 3-bit binary number indicating the pattern (actually 4-bit, but as the last element is always positive, the 4th bit is always zero.)

This number from 0..7 is then fed to a (sigh) lookup table to determine which characters of each row are non-whitespace. It is at this stage that the two different displays for the saddle case are handled, with an alternative to the number in the lookup table being used if the total is positive (the question says to consider the "average", but as we are only interested in the sign, it doesn't matter if we consider the total instead.)

The way the display of output works is hopefully clear from the comments in the code.

**ungolfed in test program**

```
f=->a{p=t=0
  4.times{|i|                      #for each number in the input
    t+=a[i]*=a[3];                   #multiply each number by a[3]; totalize the sum in t
    p+=a[i]>>9&1<<i                  #shift right to find if negative; AND with 1<<i to build index number for pattern
  }                                #q is a 3-digit base 4 number indicating which character of each line is non-whitespace (if any).
  q=p==6&&t>0?19:'@AC@P*10'[p].ord #It's encoded in the magic string, except for the case of saddles with a positive total, which is encoded by the number 19.
  s=(0..2).map{|i|                 #build an array of 3 strings, indexes 0..2
    b=p*i==3?'|---|':'|   |';        #IF p is 3 and we are on row 1, the string is |---| for the horizontal line case. ELSE it is |   |.
    b[q%4]='|/|\|/'[q%4+(i&2)];      #The numbers in q indicate which character is to be modified. The characters in the string indicate the character to replace with.
    q/=4;                            #If q%4=0, the initial | is replaced by | (no change.) i&2 shifts the string index appropriately for the last row.
    b                                #divide q by 4, and terminate the loop with the expression b so that this is the object loaded into array s.
  }
puts c='o---o',s,c}                #print the array s, capped with "o---o" above and below.

[[1, 2, 1, 3],
[-9, -2, -2, -7],

[4, 5, -1, -2],
[-1, -2, 3, 4],

[7, -7, 7, -7],
[-5, 5, -5, 5],

[1, -6, -4, -1],
[-2, 3, 3, 4],

[-1, 6, -4, -1],
[2, -3, 3, 4],

[-1, -6, 4, -1],
[2, 3, -3, 4],

[-1, -6, -4, 1],
[2, 3, 3, -4],

[3, -8, -9, 2],
[-3, 8, 9, -2],

[8, -3, -2, 9],
[-8, 3, 2, -9],

[1, -4, -2, 5],
[-1, 4, 2, -5]].each{|k|f.call(k)}

```

---
Tags: code-golf, ascii-art
---