title: Divide into 2 isosceles triangles

text:
# Question
Title: Divide into 2 isosceles triangles
Given the measures of two of the interior angles of a triangle (`x` and `y`; the other angle can be easily calculated with `180 - x - y`), draw a line segment that cuts this triangle into two isosceles triangles. You need to output the angle measures of both of your triangles.

However, because the base angles are the same, you only need to output the list `[apex angle, base angle]` of the divided triangles for both of the isosceles triangles. You can output the divided triangles in any order.

## An example

```
Say your input is 100, 60.

Let's take a look at the complete triangle first. The triangle looks approximately like this.

   100

60            20

Now we try to divide one of the angles such that two divided triangles are both isosceles triangles.

       100

(40,20)           20

Now our bottom triangle is an isosceles triangle, since both of the base angles
of the bottom triangle are 20. The angle measures of the bottom triangle
looks approximately like this.

       140
20             20

Now, is the top triangle an isosceles triangle?

    100
          40
40

It is an isosceles triangle, because two of the angle measures are 40.

Therefore, for [100, 60], you need to output [[100, 40], [140, 20]].

```

## Example cases

```
[20, 40] -> [[140, 20], [100, 40]]
[45, 45] -> [[90, 45], [90, 45]]
[36, 72] -> [[108, 36], [36, 72]]
[108, 36] -> [[108, 36], [36, 72]]
[44, 132] -> [[92, 44], [4, 88]]

```

## Specifications

* You can always assume that the triangle is dividable into two isosceles triangles.
* You can output one of the many solutions of the cases; for example, you can also output `[20, 40] -> [[100, 40], [20, 80]]` for the first test case.

# Answer
> 3 votes
# 05AB1E, ~~39~~ 38 bytes

```
OƵΔαª©90KD®Qiʒ45‹®y23S*åà*}ßx‚}ε90α·y‚

```

Input as a pair of integers; output as a pair of pairs of integers.

Try it online or verify all test cases.

**Explanation:**

```
O                 # Take the sum of the (implicit) input-pair of angles
 ƵΔα              # Get the absolute difference with (compressed) 180
    ª             # Append that third angle to the (implicit) input-pair
     ©            # Store it in variable `®` (without popping)
90K               # Remove 90 from the triplet of angles
   D              # Duplicate it
®Qi               # If it's still equal to `®` (thus none were 90):
   ʒ              #  Filter the triplet by:
    45‹           #   Check that the angle is smaller than 45
               *  #   AND
        y2 S*     #   Check if the angle multiplied by 2
          3S* à   #   or multiplied by 3
       ®     å    #   is in the triplet of angles `®`
   }ß             #  After the filter: pop and push the minimum of the remaining angles
     x            #  Double it (without popping)
      ‚           #  Pair the non-doubled and doubled values together
  }ε              # After the if statement: map the angles in the pair to:
    90α           #  Get the absolute difference with 90
       ·          #  Double it
        y‚        #  And pair it with the non-mapped angle
                  # (after which the resulting pair of pairs is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `ƵΔ` is `180`.

# Answer
> 3 votes
# Python 3.8 (pre-release), ~~123~~ 129 bytes

```
g=lambda*p:[[180-2*x,x]for x in p]
f=lambda a,b:((c:=180-a-b)==90or c>45>2in{a/b,b/a})*g(a,b)or(c/3in{a,b})*g(c/3,c/3*2)or f(b,c)

```

Try it online!

A function that takes in 2 angles, and returns the 2 isosceles triangles. If the given triangle cannot be divided, the function loops forever.

# Answer
> 2 votes
# APL (Dyalog Unicode), 47 bytes

```
(⊢,⍨¨2×90-⊢)∘{90∊⍵:⍵~90⋄1 2×⌊/⍵∩∊⍵÷⊂2 3},,180-+

```

Try it online!

A tacit function that takes two angles as left and right arguments.

Uses the information found by Neil, modified to take care of xnor's test case:

> A triangle can be divided into 2 isosceles triangles either if **one of the angles** is \< 45° and is exactly one half or one third of one of the other angles, or if one of the angles is 90°.

Now, the base angles of the result can be found as follows:

* If one of the angles is 90°, the bases are the other two angles.
* Otherwise, `one of the angles is < 45° and is exactly one half or one third of one of the other angles` should hold, because the input is guaranteed to have a solution. In this case, the angle satisfying the condition becomes the base for one triangle, and the other triangle's base angle is twice the angle.

### How it works: the code

```
(⊢,⍨¨2×90-⊢)∘{90∊⍵:⍵~90⋄1 2×⌊/⍵∩∊⍵÷⊂2 3},,180-+  ⍝ Left, Right: two angles
                                        ,,180-+  ⍝ Length-3 vector of three angles
             {                         }  ⍝ Find two base angles:
              90∊⍵:⍵~90⋄                  ⍝ If an angle is 90, the bases are the other two
                              ⍵∩∊⍵÷⊂2 3   ⍝ Otherwise, find the angles that are 1÷2 or 1÷3 of another
                        1 2×⌊/            ⍝ Take the minimum angle of that and attach its double
(          )∘  ⍝ Attach apex angles to two base angles
     2×90-⊢    ⍝ apex=180-2×base
 ⊢,⍨¨          ⍝ Attach each apex to the left of the base

```

# Answer
> 1 votes
# Charcoal, 66 bytes

```
Ｆ²⊞υＮ⊞υ⁻¹⁸⁰Συ≔Φυ∧‹ι⁴⁵∨№υ⊗ι№υ×³ιθ¿θ≔⟦⌊θ⊗⌊θ⟧θＦ№υ⁹⁰≔Φυ⁻⁹⁰κθＩＥθ⟦⊗⁻⁹⁰ιι

```

Try it online! Link is to verbose version of code. Explanation:

```
Ｆ²⊞υＮ

```

Input the two provided angles.

```
⊞υ⁻¹⁸⁰Συ

```

Calculate the third angle.

```
≔Φυ∧‹ι⁴⁵∨№υ⊗ι№υ×³ιθ

```

See if any angle under 45° appears doubled or tripled.

```
¿θ≔⟦⌊θ⊗⌊θ⟧θ

```

If so then the base angles of the result are that angle and the doubled angle.

```
Ｆ№υ⁹⁰

```

Otherwise if this is a right-angled triangle, ...

```
≔Φυ⁻⁹⁰κθ

```

... then the base angles of the result are the other two angles.

```
ＩＥθ⟦⊗⁻⁹⁰ιι

```

If we got any base angles then compute the apex angles and output all of the angles.

# Answer
> 1 votes
# , ~~146~~ ~~132~~ 128 bytes

or **~~158~~ ~~150~~ 146 bytes** to output the 4 angles as 2 lists of 2 angles each.

```
function(i,j,t=c(i,j,180-i-j),s=min(t))`if`((45-s/4)%in%t,c(45-s/4,90+s/2,s,90-s/2),c(s,180-2*s,2*s,`if`(90%in%t,90-s,180-4*s)))

```

Try it online!

An approach that does not use the 'one-half or one-third' trick:

Consider initial triangle with angles a,b,s, where *s is the smallest angle* (so s is never divided). a will be the angle that gets divided.

**case 1:** right-angle triangle (uses both bases of smaller triangles as sides) =\> divide right angle

**case 2:** starting triangle uses base and base+wall of smaller triangles as sides

=\> t1=b,b,d (where d is formed from divided angle: d=a-s)

=\> t2=s,s,180-b

=\> so (from t2) we get b=2\*s and *we can specify both t1 and t2 from s*

**case 3:** starting triangle uses only 1 base as side (other is created internally)

=\> t1=b,b,180-d (where d is formed from divided angle: d=a-b)

=\> t2=s,d,d

=\> so (from t2): d=90-s/2, and *we can specify both t1 and t2 from s*

and (from t1): b=45-s/4 to check when this case is satisfied (but we won't bother to do this...)

**Readable code:**

```
cuttri=function(i,j,t=c(i,j,180-i-j)){      # we don't know which angle is a or b
    s=min(t)                                # but we know s is the smallest
    if(90 %in% t){                          # case 1: right-angle triangle
     list(c(90-s,2*s),c(s,180-2*s))}
    else if((2*s) %in% t){                  # case 2:
     list(c(2*s,180-4*s),c(s,180-2*s))}
    else if((45-s/4) %in% t){               # case 3 (but we don't actually need to check if
     list(c(45-s/4,90+s/2),c(s,90-s/2))}    # we're assured that triangle can be divided)
}

```

Note that because the golfed code skips the final check for case 3, the output will be incorrect if it is 'fed' non-valid angles corresponding to a triangle that can't be divided into two isosceles triangles.

---
Tags: code-golf, integer, geometry
---


title: Orientation Oriented Programming

text:
# Question
Title: Orientation Oriented Programming
Write a program for a specific language that in different orientations performs different tasks.

Your code should have at least two non-empty lines and at least two non-empty columns and should complete at least one challenge from each category of challenges below when oriented in different ways.

## Orientations

Your code can be arranged eight different ways, original and three ninety degree rotations and each reversed, eg:

```
$_=     $@$      /$     =.
@F.     /F_     .F@     _F/
$/       .=     =_$     $@$

=_$      .=     $/      $@$
.F@     /F_     @F.     _F/
 /$     $@$     $_=     =.

```

Here's a generator (thanks to @fireflame241!)

## Tasks

###

###

###

###

###

## Scoring

Your score will be the number of different tasks solved by your code (higher is better) with code length as a tie-breaker (lower is better).

## Rules

* All programs must be in the same language
* The rules for each task are as specified in the linked questions.
* Multiple tasks can be completed in the same orientation to help maximise score. For example, if s challenge has no expectation to handle the empty input, you could instead perform another task that takes no input.
* Your code must perform tasks when oriented in at least three unique rotations.
* You can assume that spaces will be automatically added when rotating your code, however if your code does necessitate space padding on the end of lines of each rotation, these should be included.

# Answer
# 05AB1E, ~~5~~ ~~14~~ ~~15~~ 18 rotations (~~5~~ ~~6~~ ~~7~~ 8 unique, ~~61~~ ~~213~~ ~~1488~~ 4367 bytes)

```
.ï i…( )7ÝJ»•αγʒδÓ₂©8¥ŽQxΣxêÿ•sÅвJIvN”</[(0._-=:"ÆŸ,*”0¶:º•DùÙÂ+;Èγтáì³ÓW©ÎÂ_`ƒ≠îj*ΓçÊ~ÞÒ¸β¦oåb/õ47/vÎΓ”›≠øØZµλÝº•20вè¶¡Nè4äyè.;ëĀiηû»ëтÝ3Å€"Fizz"}5Å€á”ÒÖ”J}¦»]q]À=F₂Aë}š.?ćvD¡SaA„iĀë∍sna„>+?Å8IàQô2$4Žнв₄iï.
ï                                                                                …
i                                                                                _
Å                                                                                |
f                                                                                _
ë                                                                                Ć
∞                                                                                Ƶ
€                                                                                м
,                                                                                ×
]                                                                                T
q                                                                                ä
]                                                                                »
.                                                                                q
                                                                                ”
.                                                                                !
…                                                                                ï
ë                                                                                ‚
p                                                                                ,
i                                                                                ™
ï                                                                                Ÿ
.ïi_i“Ûà€‰€ž€¢‡Í! :D“ćuìëdiU„ $„ |}…-~-`)X·>δ∍»}ëĀi1ú.γžOså}R`¦??н©?н®ì.•gÍĆdQ¸G•Â‡D?,ë“«Î‡Ä¦í¥Â“#€¦`«'kì)™•1¢₂P•3вè4ô»]q]»ì” ©¢ØŽ”)s”E1BA50 Ž¬”Ð”î€ot”ëFëgiÊ¹Š'iĀëå4B23iï.                                 \””

```

Try it online (integer input): Do you want to code a snowman?
Try it online (string input): It took me a lot of time to make this, pls like. (YouTube Comments #1)
Try it online (no input): 1, 2, Fizz, 4, Buzz

Try it online with all rows reversed (integer input): It's my Birthday :D
Try it online with all rows reversed (string input): Covefify a string
Try it online with all rows reversed (no input): Hare Krishna Hare Krishna Krishna Krishna Hare Hare

Try it online with each row reversed (integer input): You're on a 8 day streak!
Try it online with each row reversed (string input): No A, just CAPS LOCK
Try it online with each row reversed (no input): Print a Tabula Recta!

Try it online with both the rows and each row itself reversed (integer input): Am I a Rude Number?
Try it online with both the rows and each row itself reversed (string input): Don't google "google"
Try it online with both the rows and each row itself reversed (no input): Sing Happy Birthday to your favourite programming language

Try it online rotated 90 degrees clockwise (integer input): Fibonacci function or sequence
Try it online rotated 90 degrees clockwise (no input): Count up forever

Try it online rotated 90 degrees clockwise and then each row reversed (integer input): Is this number a prime?
Try it online rotated 90 degrees clockwise and then each row reversed (no input): Print the last, middle and first character of your code

Try it online rotated 90 degrees counterclockwise (no input): Build me a brick wall!

Try it online rotated 90 degrees counterclockwise and then each row reversed (no input): "Hello, World!"

## Explanation:

In general, I mostly rely on the builtin `q`. This will stop the program, making everything after it no-ops.

In addition, for the four main rotations, I split them up into integer/string/no input with:

```
.ïi         # If the (implicit) input is an integer:
            #  Do something with the integer-input
ëĀi         # Else-if the (implicit) input-string is NOT empty:
            # (using the Python-truthify builtin `Ā`)
            #  Do something else with the string-input
ë           # Else (there is no input):
            #  Do something else without input

```

For the two clockwise rotations it's similar, but only with integer or no input (since there aren't any other challenges available with input from the list in the challenge).
And for the two counterclockwise rotations it's just a kolmogorov-complexity output without input.

Some things I had to fix for the rotations include:

* Adding an additional space between the  and `i` at the start of the first line, and a space on each subsequent line. Without this space, the middle character for subprogram of the *Print the last, middle and first character of your code* challenge would have a newline character as the center, which isn't possible without screwing up the layout. With that added space, the middle character in that rotation also becomes a space (the first and last characters are both `.`).
* Adding `\”` at the end of the final line. This is to close this string and discard it for the programs with all rows and each row itself reversed, which will now contain a leading `””\` followed by a bunch of no-op spaces.
* For most rotations I reuse the `.` for the  (is\_integer check), but for one rotation it's `.…` instead. `.` opens up 2-byte builtins, but since `.…` doesn't exist, the `.` is a no-op instead in this case.

**As for an explanation of each individual program:**

*Do you want to code a snowman?*: `…( )7ÝJ»•αγʒδÓ₂©8¥ŽQxΣxêÿ•sÅвJIvN”</[(0._-=:"ÆŸ,*”0¶:º•DùÙÂ+;Èγтáì³ÓW©ÎÂ_`ƒ≠îj*ΓçÊ~ÞÒ¸β¦oåb/õ47/vÎΓ”›≠øØZµλÝº•20вè¶¡Nè4äyè.;`
See this answer of mine, except that the actual newline is replaced with a `0`, which we replace to a newline after creating the string with `0¶:`.

*It took me a lot of time to make this, pls like. (YouTube Comments #1)*: `ηû»`
See the second program in this answer of mine (provided by *@Grimmy*).

*1, 2, Fizz, 4, Buzz*: `тÝ3Å€"Fizz"}5Å€á”ÒÖ”J}¦»`
See this answer of *@Grimmy*.

*It's my Birthday :D*: `_i“Ûà€‰€ž€¢‡Í! :D“ćuìëdiU„ $„ |}…-~-`)X·>δ∍»}`
See this answer of *@Grimmy*, with additional trailing `}` to close the if-statement.

*Covefify a string*: `1ú.γžOså}R`¦??н©?н®ì.•gÍĆdQ¸G•Â‡D?,`
See this answer of *@Grimmy*.

*Hare Krishna Hare Krishna Krishna Krishna Hare Hare*: `“«Î‡Ä¦í¥Â“#€¦`«'kì)™•1¢₂P•3вè4ô»`
See this comment of mine on the answer of *@Emigna*.

```
“«Î‡Ä¦í¥Â“  # Push dictionary string "drama share irish dna"
 #          # Split it on spaces: ["drama","share","irish","dna"]
  €¦        # Remove the first character of each word:
            #  ["rama","hare","rish","na"]
    `       # Push them separated to the stack
     «      # Merge the last two together: "rishna"
      'kì  '# Prepend a "k": "krishna"
         )  # And wrap everything on the stack into a list again:
            #  ["rama","hare","krishna"]
          ™ # Titlecase each: ["Rama","Hare","Krishna"]
•1¢₂P•      # Push compressed integer 27073120
 3в         # Convert it to base-3 as list: [1,2,1,2,2,2,1,1,1,0,1,0,0,0,1,1]
   è        # Index each integer into the list of words
    4ô      # Split the list of words into parts of size 4
      »     # Join each inner list by spaces, and then each string by newlines
            # (after which the result is output implicitly as result)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?*, *How to compress large integers?*, and *How to compress integer lists?*) to understand why `“«Î‡Ä¦í¥Â“` is `"drama share irish dna"`; `•1¢₂P•` is `27073120`; and `•1¢₂P•3в` is `[1,2,1,2,2,2,1,1,1,0,1,0,0,0,1,1]`.

*You're on a 8 day streak!*: `₄внŽ4$2ôQàI8Å?+>„ans∍`
See this answer of mine.

*No A, just CAPS LOCK*: `„AaS¡Dvć?.š`
See this this answer of *@Emigna*, although without `õ?` and with  instead of `š`, since his answer is built in the legacy version of 05AB1E instead of the new one.

*Print a Tabula Recta!*: `A₂F=À`
See this answer of *@Adnan*, although with `₂F` instead of `Dv`, since I personally prefer to keep my programs as straight-forward as possible despite codegolfing (where  is the builtin for `26`, and `F` loops that many times).

*Am I a Rude Number?*: `32B4å`
See this answer of mine.

*Don't google "google"*: `'Š¹ÊigëF`
Although there is this pretty old answer of *@Adnan* which worked on one of the earliest versions of 05AB1E when he posted it back in 2016, it doesn't even work anymore in the latest legacy version on TIO from around mid-2017, let alone in the latest 05AB1E version. So instead I now use this (which is also 2 bytes shorter anyway):

```
'Š¹        '# Push the dictionary string "google"
   Êi       # If the (implicit) input-string is NOT equal to "google":
     g      #  Pop and push the length of the (implicit) input-string
            #  (which will be output implicitly as result)
    ë       # Else:
     F      #  Start a loop using the (implicit) input-string,
            #  which will result in an error if it isn't an integer

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `'Š¹` is `"google"`.

*Sing Happy Birthday to your favourite programming language*: `”to€î”Ð”¬Ž 05AB1E”s)”ŽØ¢© ”ì»`
See this 05AB1E answer of *@Grimmy*.

*Fibonacci function or sequence*: `Åf`

```
Åf          # Given the (implicit) input-integer `n`, get the n'th Fibonacci number
            # (after which it is output implicitly as result)

```

*Count up forever*: `∞€,`
See this answer of *@Sagittarius*.

*Is this number a prime?*: `p`

```
p           # Given the (implicit) input-integer, check if it's a prime number
            # (1 if truthy; 0 if falsey)
            # (after which it is output implicitly as result)

```

*Print the last, middle and first character of your code*: `.…. .`
As I already mentioned earlier, I added an additional no-op space to the program so the middle character in this orientation would be a space character, instead of a newline character. The first and last characters are `.`, so we'll have the following sub-program:

```
.           # No-op, since `.…` isn't an available 2-byte builtin
 …. .       # Push 3-char string ". ."
     q      # Stop the program, making everything after that no-ops
            # (after which the result is output implicitly)

```

*Build me a brick wall!:* `.…_|_ĆƵм×Tä»`
See this answer of *@Adnan*, although golfed by 2 bytes by replacing `"_|__"` with `…_|_Ć` (push 3-char string `"_|_"`; and then enclose, appending its own first character) and `175` with `Ƶм` (compressed integer).

*"Hello, World!"*: `”Ÿ™,‚ï!”`
See this answer of *@Adnan*, except with trailing  to close the string.

The `]` you see before the `q` in each program is to close all open if-else statements and loops before doing this `q`.

I'm unable to fit anything more in it from the list in the challenge description. The ones left are three (/) that require you to output something without input (which I have already used in all eight rotations) and four -related challenges, which are just impossible with this kind of layout in 05AB1E.
If there would have been more challenges taking integer/string inputs, those could have been added as well.
> 34 votes

# Answer
# perl -M5.010 -Mbigint, 8 orientations, 8 18 tasks, 1644 2840 bytes

```
####################################################iA;"/sv)=-=f{.{ei#
if(eof()){say+("11 *25 *\n7 4*10 *5 *10 4*" .##cAc##f.e[^ag.(-po$./lf#
"\n5 4*12 7*12 4*\n3 6*12 7*12 6*\n2 9*9 9*".##'+b##(.x^(yk$$$orp*^s(#
"9 9*\n 47*\n49*\n49*\n49*\n 47*\n  5*7 21*".##@wM##eYi$$$k3x_d =).ee#
"7 5*\n4 4*7 3*4 5*4 3*7 4*\n7 **7 *6 3*6 *".##@@E##o;tvc1g)[>#2$.+{o#
"7 **\n")=~s/(\d+)(\D)/$2 x$1/gre}else{chomp(##4`c##f/}]*.px1=%._(?$f#
$_=<>);if(/\D/){/^google/&¨$_=length}else##":B##(.$"$(b ]00.>?(_(#
{$_=sprintf"00%b",$_;$_=/00100(.{5})*$/?1:0}}##VQl##){_;v(s2,;#$1{?=)#
say;#[447}E<vFX**gd's<kN6iiX#gS0qnsHgj'M%um$###>fr##)2=$*(z)$son;s{<)#
=pod#+RvC!y-9UwQ7ImGlBV03'UoBoqY:#OR`6z&C_;0###$I7##{6<v({t}xa+-$as>{#
[$1=~y,a-zA-Z,A-Za-z,r]ige}};say;#zG}B2|M}TI###X^4##$}>=$sde[yQ2nya;{#
"ur new baby! :D"}}else{s[a([^aA]*)a?] ##l"}###/)u##_(;"cpvl0$s;=$ycs#
$/,grep$_,@x}else{$_="Congratulations on yo".##"(O##=?$[)lfs]x9s$1$ha#
' $'x$_,' |'x$_,'-'x$x,'~'x$x,'-'x$x);$_=join##ZSo##j{v$)ize+[Ja_}&oy#
;if(/^-?\d+$/){if($_){$x=1+2*($_<0?1:$_);@x=(##)<V##os=v$ts{$0Jy;)}m+#
if(eof()){$_="Hello, World!"}else{$_=<>;chomp##WJ+##iaa]c/}@x]^!$()p+#
###############################################JvE##nye"*/-x[}@!p?(;$#
###############F+g@,ZHTSgmA|[\N"0`EV(>QJ'=b(9]+FJY##"$i;(,>=1#>$&!?i_#
###########.###lq{$LWnQj&g|l27@'o}Tr@VFDBI`K#np#7g##"&oi$b{(]6>p&)!f;#
#9Tj=~7D#Sxy{##.YTb}.:7dj+t|4-8Fo\GZJ?E=L7CWYq-RVu##,}ufvp$0){/}=/)(r#
#7$_j;&Q,A$b###<M+agLQ5{_6z^mL6V:VVo;Azb`4<5tAUx9###A)y()c2,wwd}$x//e#
#L[vlh(sa#ya(##hOy>[A&.[usZ_Xzkgn^{qdp|2B{T-g5&$u+##.(;#/g}1h;0#n};\d#
#,zQS#wBpraB.##(Qrc\!&X(_i[Cd1o:vuq76kWY/g0v>xso8|##.?$/)d|)id'[%e/Do#
#{x]V;Gzdos."##eXBcnsw2l?ImMzjJ;0NO045|JIrUh\sT@wh##Z!ca{t|;lCxd$l^/}#
###LuyK/nf;)k##G{3|#3B)J\n"rG__@*w0,6h6m6\MLggprbN##,)=[#f$@eiU\_s()}#
#";M!aBwa x3r##Oj@;),oZ-Yh6gBXx*B-Aq|!Xg;vx!@O7V^_###/###.2x#####e####
#t"]#sLTrr$xa##p79<GL"e"STDrRWLVRHuQY`_zmq;wDu`3cD####################
#ru}~;b'Ggy)h#########################################################
#io#=rgr,/a/S###rof zzuBzziF:zzuB:zziF:_$?3%_$?5%_$?51%_$yas{))(foe(fi
#BYyr!vay_s$ ###Xat(\'7O(>#;a:na?/$*)...(]81[1^|8^/~=><yas}tixe;001..1
#  a!l+7m$;.y###iv&.:!Pd.MSjhr6,|E+>cjA(%?NuLB"}ss#8H?<Otd~Bw0zy>#dop=
#yosrrm#m/")b###$#;yas}")".]]7[c$[)"   ","___",'" "'," : "(."( n\".]]5
#pt;ae{;oy!6a##[c$[)"$,"\\","$,">"(.")".]]6[c$[)"   ","< >","[ ]"," :"
#p yePVaMbkxB##."$(."(".]]4[c$[)"$,"/","$,"<"(./$.]]5[c$[)"$,"$,"/","$
#ayaD!~m,ar""##(.")".]]3[c$[)"-","O","o","."(.]]1[c$[)"$,"_",".",","(.
#Has!u#dyBao(##]]2[c$[)"-","O","o","."(."(".]]4[c$[)"$,"$,"\\","$(./$.
#"d;oodnd/ho(##]]0[c$[)")_*_(","\\_/ ",".....","_===_"(."$./$.]]0[c$[)
#=hytYoadsSd=##"___ ","_  ","___ ",""(."$=_$;g/./~=><}1-_${pam=c@{esle
#_"a!!pra~  x##}5=x _$;g//$..|..^/s;2=x _$;/$.)81x"|___"(=_${))(foe(fi
#$.sss=GD=""$#########################################################

```

Before explaining how it works, let me tell how I created the monster above. I started off with 8 programs, each doing 1 to 3 tasks. Which task they do depends on the input (all input is read as a single line from `STDIN`) they get: void, an integer, or a string. 8 programs handle void input, 6 handle integer input, and 4 handle string input. If there would be more tasks which take integer and/or string input, we could have handled 24 inputs.

Now, we take the 8 programs, and combine them in the following way:

```
###################PP=PP#
PROGRAM 1 TOP    ##RRpRR#
PROGRAM 1 BOTTOM ##OOoOO#
=pod             ##GGdGG#
PROGRAM 2 BOTTOM ##RR RR#
PROGRAM 2 TOP    ##AA AA#
###################MM MM#
#     #           #     #
# M M #           #44 33#
# O O #           #     #
# T T #           #TB BT#
#PT TP#           #OO OO#
#OO OO#           #PT TP#
#TB BT#           # T T #
#     #           # O O #
#77 88#           # M M #
#     #           #     #
#MM MM###################
#AA AA##    POT 6 MARGORP
#RR RR## MOTTOB 6 MARGORP
#GGdGG##             dop=
#OOoOO## MOTTOB 5 MARGORP
#RRpRR##    POT 5 MARGORP
#PP=PP###################

```

Any 'gaps' (whether from short lines, or how the programs are laid out) are filled with random characters, protected by comment characters. Any lines starting with `=pod` prevent Perl to see the rest of the program; this way we get to have two programs per rotation; flipping the program in the x-axis exposes the other program.

A few things need to be taken care off: programs should finish with semi-colon or a right-paren which closes a block. That way, the final statement is finished, and only then, Perl will recognized the `=pod` as the start of a `POD` section. Second, if we have a construct of the form `s[pattern][replacement]`, with a newline between the `s[pattern]` and `[replacement]`, we must add a space after `s[pattern]`. Otherwise, we may end up with `s[pattern]#`, and that `#` Perl will not see as a comment, but as a delimiter for the replacement part. With a space before the `#`, Perl will treat it as a comment.

Up to the tasks!

## No rotations, no mirroring

```
if(eof()){say+("11 *25 *\n7 4*10 *5 *10 4*" .
"\n5 4*12 7*12 4*\n3 6*12 7*12 6*\n2 9*9 9*".
"9 9*\n 47*\n49*\n49*\n49*\n 47*\n  5*7 21*".
"7 5*\n4 4*7 3*4 5*4 3*7 4*\n7 **7 *6 3*6 *".
"7 **\n")=~s/(\d+)(\D)/$2 x$1/gre}else{chomp(
$_=<>);if(/\D/){/^google/&¨$_=length}else
{$_=sprintf"00%b",$_;$_=/00100(.{5})*$/?1:0}}
say;

```

### No input

Without input, this does the "In Honor of Adam West" task. We're using a simple encoded string, where repeated characters are encoded as `NNc`, which means `NN` times the character `c`. The string is decoded and printed.

Try it online!

### Integer input (non negative)

Now we determine whether the given number is a Rude Number. We take the number, get the binary representation, prepend `00`, and look whether the result contains `00100` followed by `N`s `0`s and `1`s, where `N` is a multiple of 5.

Try it online!

### String input

For other inputs, if the input equals `google`, we die. Otherwise, we print the length of the input.

Try it online!

## No rotation, mirrored.

If we mirror the program, we effectively end up with:

```
if(eof()){$_="Hello, World!"}else{$_=<>;chomp
;if(/^-?\d+$/){if($_){$x=1+2*($_<0?1:$_);@x=(
' $'x$_,' |'x$_,'-'x$x,'~'x$x,'-'x$x);$_=join
$/,grep$_,@x}else{$_="Congratulations on yo".
"ur new baby! :D"}}else{s[a([^aA]*)a?] #
[$1=~y,a-zA-Z,A-Za-z,r]ige}};say;

```

### No input.

The program prints out `Hello, World!`. Nothing creative going on here.

Try it online!

### Integer input

We do the "It's my Birthday :D" task. If the input equals `0`, we print out `Congratulations on your new baby! :D`. For the input (`N`) is positive, we start printing out `N` candles, then a cake of width `2 * N - 1`. If the input is negative, we print a candleless cake, with width `3`. All pretty straightforward.

Try it online!

### String input

Now we do the "No A. just CAPS LOCK". We repeatedly find strings which are delimited by `a` (either case), with no `a` in between (with some trickery to make it work for the end of the string as well. We throw away the bounding `a`s, and flip the case of the string between the `a`s.

Try it online!

## Rotating 90° counter clockwise, no mirroring

We then end up with effectively:

```
if(eof()){{say++$_;redo}}
else{$_=<>;chomp;if(/\D/)
{/^.+?(?{say$&})(?!)/;/^(
..*).(?{say$1})(?!)/x}else
{$p=$_>1;$n=$_;$p&&=$n%$_
for 2..$n-2;say!!$p}}

```

### No input

With no input, we enter an infinite loop, where we increment `$_` and print the result.

Try it online!

### Integer input (non-negative)

We will now determine whether the given number is a prime number. We do this by checking whether non of the integers between (but not including) `1` and the input number evenly divides the input number. We then print the result (`1` if it's a prime, an empty line if it's not).

Try it online!

### String input

Now we do the YouTube Comments #1 task. We do this by finding all sub strings of the given string, which are anchored at the beginning. This is done by use a regexp (`/^.*?/`), printing the match (`/(?{say $&})/`) and then failing the match (`/(?!)/` (it can never happen that the current position isn't followed by an empty string)). This cause Perl to backtrack and try the next match. The quantifier modifier `?` makes Perl try the shortest strings first. This takes care of the first half (including the full line). For the second half, we use `/^(..*)./`, which does almost the same thing, except it only matches sub strings which are followed by at least one other character (so, it skips the full string), and it tries it in "longest first" order.

Try it online!

## Rotating 90° counter clockwise, mirrored

Then we effectively get:

```
if(eof()){$_=join"",A..Z,
A..Y;/.{26}(?{say$&})(?!)/
;exit}$_=<>;$v=aeiouy;$c=
"[^$v]";$v="[$v]";if(
/^($c*$v*($c))$c*($v)/){
say$1.((({split//,bpcgdtf.
vgkkgpbsztdvfzs}->{$2}||$2
).$3)x 2)}else{@x=(0,1);@x
=($x[1],$x[0]+$x[1])while
--$_>=0;say$x[0]}

```

### No input

This prints out the "Tabula Recta". It does so by creating a string consisting of all the letters `A` to `Z`, followed by the letters `A` to `Y` (so, 51 letters in total). We then find all sub strings of length 26 and print them, using the same trick as above.

Try it online!

### Integer input (non negative)

In this case, we calculate the `N`th Fibonacci number, where `N` is the input. We do this by keeping track of two numbers, initialized to `(0, 1)`, and `N` times replacing `(n, m)` by `(m, n + m)`.

Try it online!

### String input

Now we "Covfefify a string". We start of by grabbing the parts of the string we need (`/^($c*$v*($c))$c*($v)/`, where `$c` and `$v` are character classes matching consonants and vowels). We find the replacement consonant by doing a lookup (`{split//,bpcgdtfvgkkgpbsztdvfzs}->{$2}||$2` -- the string is split into a list of characters, the surrounding `{}` turns the list into a hash ref; the `->{$2}` indexes the second captures; if there is no match, the `||$2` makes it return the second capture -- this takes care of consonants which are replaced by themselves). Then it's a matter of constructing the final string.

Try it online!

## Rotate the program, no mirroring

We effectively end up with:

```
if(eof()){$_=("___|"x18).$/;$_ x=2;s/^..|..$//g;$_ x=5}
else{@c=map{$_-1}<>=~/./g;$_=$".(""," ___","  _"," ___"
)[$c[0]].$/.$".("_===_","....."," /_\\","(_*_)")[$c[0]]
.$/.($","\\",$",$")[$c[4]]."(".(".","o","O","-")[$c[2]]
.(",",".","_",$")[$c[1]].(".","o","O","-")[$c[3]].")".(
$","/",$",$")[$c[5]].$/.("<",$","/",$")[$c[4]]."(".($".
": ","] [","> <","   ")[$c[6]].")".(">",$","\\",$")[$c[
5]]."\n (".(" : ",'" "',"___","   ")[$c[7]].")"}say;

```

### No input

We now "Build me a brick wall!". We start off by concatenating the string `___|` 18 times by it self, adding a newline, then doubling the line. We remove the first two characters, and the last two characters before the final newline. We then print the result 5 times.

Try it online!

### Other input

It's time to build a snowman. We split the input on characters (which is assumed to be a string consisting of `1`s, `2`s, `3`s, and `4`s). It's then just a matter of combining the pieces of the snowman by getting the right parts from a series of lists.

Try it online!

## Rotated 180°, mirrored.

Effectively, we have:

```
if(eof()){say$_%15?$_%5?$_%3?$_:Fizz:Buzz:FizzBuzz for
1..100;exit}say<>=~/^8|^1[18](...)*$/?an:a;

```

### No input

Without input, the program does the FizzBuzz challenge. Nothing special going here, we loop numbers from 1 to 100, if 15 divides it evently, "FizzBuzz" is printed; if 5 divides it evently, "Buzz" is printed; if 3 divides it evenly, "Fizz" is printed, else, the number itself is printed.

Try it online!

### Other input (assumed to be a non-negative integer)

This does the "You're on a 8 day streak!" task. If the input starts with `8`, or starts with either `18` or `11` followed by `3 k` digits for some `k >= 0`, we print "an", else we print "a".

Try it online!

## Rotated 270° counter clockwise, no mirroring.

We end up with:

```
$_="Happy Birt"
."hday to You";
say;say;say
s!to!Dear!r=~
s!You!Perl!r;say;

```

This does only one thing, sing "Happy Birthday". The string "Happy Birthday to You" is created, and printed twice. Then it's printed with "to" replaced by "Dear", and "You" by "Perl". Then the original string is printed once again.

Try it online!

## Rotated 270° counter clockwise, mirrored.

Effectively, we end up with:

```
$x=(("Baby Shark".(
" doo"x6).$/)x3).Baby.
" Shark!";say$x;say$x
=~s/Baby/$_/gr for
Daddy,Mommy,Grandpa,
Grandma;

```

This sings Baby Shark. It creates the string "Baby Shark doo doo doo doo\n", repeated thrice, followed by "Baby Shark!". This is printed, then it's printed another four times with Baby replaced by "Daddy", "Mommy", "Grandpa", and "Grandma" repectively.

Try it online!
> 14 votes

# Answer
# Befunge-93, 4 orientations, 4 tasks, 1205 bytes

## In Honor of Adam West

```
>52*"       **       *      ***      *       **       "v  v.:>1
v"    ****       ***    *****    ***       ****    "*52<  <1+^
>52*"  *****       *********************       *****  "v
v" *********************************************** "*52<
>52*"*************************************************"v
v"*************************************************"*52<
>52*"*************************************************"v
v" *********************************************** "*52<
>52*"  *********         *********         *********  "v
v"   ******            *******            ******   "*52<
>52*"     ****            *******            ****     "v
v"       ****          *     *          ****       "*52<
>52*"           *                         *           "v
                            >        ^v         **25"A"<
                            v-1,\_@#:<<
                            >        ^v       *2"s"<
>52*"EEEEE      DDDD     CCCC       BBBB      AAA "v
v"A   A     B   B     C         D   D     E    "*52<
>52*" EEEE     D   D         C      BBBB     AAAAA"v
v"A   A     B   B     C         D   D     E    "*52< <,,,,,,,,,,,,,,@
>52*"EEEEE      DDDD     CCCC       BBBB     A   A"v v"Hello, World!"*25

```

Try it online!

Nothing special here. We push the 650 characters which needs to be printed on the stack, then use a loop to print 650 characters.

## 5 Favorite Letters

Mirroring the original program vertically gives us:

```
>52*"EEEEE      DDDD     CCCC       BBBB     A   A"v v"Hello, World!"*25
v"A   A     B   B     C         D   D     E    "*52< <,,,,,,,,,,,,,,@
>52*" EEEE     D   D         C      BBBB     AAAAA"v
v"A   A     B   B     C         D   D     E    "*52<
>52*"EEEEE      DDDD     CCCC       BBBB      AAA "v
                            >        ^v       *2"s"<
                            v-1,\_@#:<<
                            >        ^v         **25"A"<
>52*"           *                         *           "v
v"       ****          *     *          ****       "*52<
>52*"     ****            *******            ****     "v
v"   ******            *******            ******   "*52<
>52*"  *********         *********         *********  "v
v" *********************************************** "*52<
>52*"*************************************************"v
v"*************************************************"*52<
>52*"*************************************************"v
v" *********************************************** "*52<
>52*"  *****       *********************       *****  "v
v"    ****       ***    *****    ***       ****    "*52<  <1+^
>52*"       **       *      ***      *       **       "v  v.:>1

```

Try it online!

As above; it pushes the 230 characters to be printed on the stack, and then uses a loop to print 230 characters. It will reuse part of the loop from the solution above.

## Count up forever

Mirroring the original program horizontally give us:

```
         1>:.v  v"       **       *      ***      *       **       "*25>
          ^+1<  <25*"    ****       ***    *****    ***       ****    "v
                v"  *****       *********************       *****  "*25>
                <25*" *********************************************** "v
                v"*************************************************"*25>
                <25*"*************************************************"v
                v"*************************************************"*25>
                <25*" *********************************************** "v
                v"  *********         *********         *********  "*25>
                <25*"   ******            *******            ******   "v
                v"     ****            *******            ****     "*25>
                <25*"       ****          *     *          ****       "v
                v"           *                         *           "*25>
                <"A"52**         v^        >
                                 <<:#@_\,1-v
                    <"s"2*       v^        >
                    v" AAA      BBBB       CCCC     DDDD      EEEEE"*25>
                    <25*"    E     D   D         C     B   B     A   A"v
                    v"AAAAA     BBBB      C         D   D     EEEE "*25>
   @,,,,,,,,,,,,,,< <25*"    E     D   D         C     B   B     A   A"v
52*"!dlroW ,olleH"v v"A   A     BBBB       CCCC     DDDD      EEEEE"*25>

```

Try it online!

Uses a tiny loop. In the loop it duplicates the top of the stack, prints it, then adds 1 to the top of the stack. Rinse and repeat. `1` is pushed on the stack before entering the loop.

## Hello, World

Rotating the original program by 180° gives the following program:

```
52*"!dlroW ,olleH"v v"A   A     BBBB       CCCC     DDDD      EEEEE"*25>
   @,,,,,,,,,,,,,,< <25*"    E     D   D         C     B   B     A   A"v
                    v"AAAAA     BBBB      C         D   D     EEEE "*25>
                    <25*"    E     D   D         C     B   B     A   A"v
                    v" AAA      BBBB       CCCC     DDDD      EEEEE"*25>
                    <"s"2*       v^        >
                                 <<:#@_\,1-v
                <"A"52**         v^        >
                v"           *                         *           "*25>
                <25*"       ****          *     *          ****       "v
                v"     ****            *******            ****     "*25>
                <25*"   ******            *******            ******   "v
                v"  *********         *********         *********  "*25>
                <25*" *********************************************** "v
                v"*************************************************"*25>
                <25*"*************************************************"v
                v"*************************************************"*25>
                <25*" *********************************************** "v
                v"  *****       *********************       *****  "*25>
          ^+1<  <25*"    ****       ***    *****    ***       ****    "v
         1>:.v  v"       **       *      ***      *       **       "*25>

```

Try it online!

This will push the necessary characters on the stack, and then prints those characters (no loop).
> 4 votes

# Answer
# Bash, 4 orientations, 4 tasks, 1794 bytes

We are (ab)using the fact that (ba)sh is a true interpreter: it reads a line of code, and execute it. This means, once it has encountered an `exit`, it will never see the rest of the program, and won't complain it cannot parse it.

## 5 Favorite Letters

```
echo " AAA      BBBB       CCCC     DDDD      EEEEE";#   eedw
echo "A   A     B   B     C         D   D     E    ";#   xcoh
echo "AAAAA     BBBB      C         D   D     EEEE ";#   ih i
echo "A   A     B   B     C         D   D     E    ";#   toxl
echo "A   A     BBBB       CCCC     DDDD      EEEEE";#     =e
exit                                                ;#    $$
                                                          x([
                                                          ;(
                                                          dx1
                                                          o+
                                                          n1]
                                                          e)
                                                           )
###                                                      ;;;;
;;;                                                      ####
"
c" #;                                                    tixe
\! #;"       **       *      ***      *       **       " ohce
,d #;"    ****       ***    *****    ***       ****    " ohce
ol #;"  *****       *********************       *****  " ohce
lr #;" *********************************************** " ohce
lo #;"*************************************************" ohce
eW #;"*************************************************" ohce
H  #;"*************************************************" ohce
"" #;" *********************************************** " ohce
   #;"  *********         *********         *********  " ohce
oot#;"   ******            *******            ******   " ohce
hhi#;"     ****            *******            ****     " ohce
ccx#;"       ****          *     *          ****       " ohce
eee#;"           *                         *           " ohce

```

Try it online!

## Count up forever

Rotating this by 90° counter clock wise, we end up with

```
while [ 1 ]  ;# eeeeeeeeeeeeee
do x=$((x+1));# xccccccccccccc
echo $x;done ;# ihhhhhhhhhhhhh
exit         ;# tooooooooooooo

                 """""""""""""
                     ***
######              *****
;;;;;;             *******
"""""              ********
E   E             *********
E E E             **********
E E E             **********
E E E            ** *********
EEEEE            *  *********
                    ******  *
                    ******  *
                    *****    *
                    *****
                    *****
 DDD               ******
D   D             *******
D   D            ********
D   D             *******
DDDDD              ******
                   ******
                   *******
                   **********
                  **********
                 ***********
C   C            ***********
C   C            ***********
C   C             **********
C   C              **********
 CCC               *******
                   ******
                   ******
                  *******
                 ********
                  *******
 B B               ******
B B B               *****
B B B               *****
B B B               *****    *
BBBBB               ******  *
                    ******  *
                 *  *********
                 ** *********
                  **********
                  **********
 AAAA             *********
A A                ********
A A                *******
A A                 *****
 AAAA                ***
"""""            """""""""""""
                ;;;;;;;;;;;;;;
ooooot          ##############
hhhhhi       #;           tixe
cccccx       #; "!dlroW " ohce
eeeeee       #;"c\,olleH" ohce

```

Try it online!

## In Honor of Adam West

Rotating this once again by 90° counter clockwise, and we get:

```
echo "           *                         *           ";#eee
echo "       ****          *     *          ****       ";#xcc
echo "     ****            *******            ****     ";#ihh
echo "   ******            *******            ******   ";#too
echo "  *********         *********         *********  ";#
echo " *********************************************** ";# ""
echo "*************************************************";#  H
echo "*************************************************";# We
echo "*************************************************";# ol
echo " *********************************************** ";# rl
echo "  *****       *********************       *****  ";# lo
echo "    ****       ***    *****    ***       ****    ";# d,
echo "       **       *      ***      *       **       ";# !\
exit                                                    ;# "c
                                                            "
####                                                      ;;;
;;;;                                                      ###
 )
 )e
]1n
 +o
1xd
 (;
[(x
 $$    #;                                                tixe
e=     #;"EEEEE      DDDD     CCCC       BBBB     A   A" ohce
lxot   #;"    E     D   D         C     B   B     A   A" ohce
i hi   #;" EEEE     D   D         C      BBBB     AAAAA" ohce
hocx   #;"    E     D   D         C     B   B     A   A" ohce
wdee   #;"EEEEE      DDDD     CCCC       BBBB      AAA " ohce

```

Try it online!

## Hello, World!

A final rotation of 90° counter clockwise, and we get:

```
echo "Hello,\c";#       eeeeee
echo " World!" ;#       xccccc
exit           ;#       ihhhhh
##############          tooooo
;;;;;;;;;;;;;;
"""""""""""""            """""
      ***                AAAA
     *****                 A A
    *******                A A
   ********                A A
   *********             AAAA
  **********
  **********
 ********* **
 *********  *
 *  ******
 *  ******               BBBBB
*    *****               B B B
     *****               B B B
     *****               B B B
     ******               B B
     *******
     ********
     *******
     ******
     ******
    *******               CCC
 **********              C   C
  **********             C   C
  ***********            C   C
  ***********            C   C
  ***********
  **********
 **********
    *******
     ******
     ******              DDDDD
     *******             D   D
     ********            D   D
     *******             D   D
     ******               DDD
     *****
     *****
*    *****
 *  ******
 *  ******
 *********  *            EEEEE
 ********* **            E E E
  **********             E E E
  **********             E E E
   *********             E   E
   ********              """""
    *******             ;;;;;;
     *****              ######
      ***
"""""""""""""

ooooooooooooot #;         tixe
hhhhhhhhhhhhhi #; enod;x$ ohce
cccccccccccccx #;))1+x(($=x od
eeeeeeeeeeeeee #;  ] 1 [ elihw

```

Try it online!

On TIO, this will actually print `Hello,\c`, followed by  `World!` on a newline. Whether `\c` is supported is implementation defined according to POSIX.1, and so is the alternative, the `-n` option. The intention is to surpres the newline `echo` by default emits. (And on my system, the builtin `echo` omits a newline when encountering `\c`, but doesn't recognize `-n` -- and the standalone utility does both). YMMV.
> 3 votes

---
Tags: code-challenge, source-layout, multiple-holes
---


# Question
Title: Identify the smallest possible tile in the matrix
## Challenge

Given a matrix of digits (0-9), find the smallest (in terms of area) rectangular matrix of digits where one or more copies of itself, possibly rotated, can tile the original matrix. Reflection is not allowed (think of a collection of tiles on a wall or floor).

Input can be taken in any reasonable ways to represent a matrix of integers or characters. Output format should be consistent with the input, but output in any orientation (out of four possible rotations) is allowed.

If there are multiple possible tiles of same area, you may output one or all of them. It is guaranteed to be solvable for any possible input, since the entire input matrix is always an option if no smaller tiles can cover it.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
Input:
0 1 2 3 4
5 6 7 8 9
0 1 2 3 4
5 6 7 8 9
0 1 2 3 4
5 6 7 8 9
Output:
0 1 2 3 4
5 6 7 8 9
------------------
Input:
1 1 1
1 1 1
1 1 1
Output:
1
------------------
Input:
1 2 3
4 5 6
7 8 9
Output:
1 2 3
4 5 6
7 8 9
------------------
Input:
1 2 3 4 1
4 5 6 5 2
6 5 4 6 3
3 2 1 3 6
1 2 3 2 5
4 5 6 1 4
Output:
1 2 3
4 5 6
------------------
Input:
0 0 0 0
0 1 0 1
0 0 0 0
0 0 0 0
1 0 1 0
0 0 0 0
Valid Output 1:
0 0 0 0 1 0
Valid Output 2:
0 1 0
0 0 0
Invalid Output (because it is an L-shape, not a rectangular matrix):
0 1 0 0 0
0
------------------
Input: (a hard case, suggested by Arnauld)
1 2 1 2 1 1
1 1 2 1 2 2
2 1 1 2 1 2
1 2 2 1 2 1
2 1 2 1 2 2
Output:
1 2

```

# Answer
> 5 votes
# JavaScript (ES6),  ~~354 352 345~~  342 bytes

I/O: matrix of integers.

This is quite long but pretty fast -- at least with those test cases.

```
m=>m[b=P='map']((r,h)=>r[P]((_,w)=>(M=m.slice(~h)[P](r=>r.slice(~w)),a=~w*~h,g=(x,y,F)=>a>b|q.some((r,Y)=>r.some((v,X)=>~v?v^m[Y][X]:![x=X,y=Y]))?0:1/y?[...P+0][P](z=>(F=k=>!M[P]((r,Y)=>r[P]((v,X)=>k^1?q[y-Y][x-X]=v|k:(z|=~(q[y-X]||0)[x-Y],T[X]=T[X]||[])[Y]=v),T=[]))(1)&T.reverse(M=T)|z||g(F())|F(-1)):(o=M,b=a))(q=m[P](r=>r[P](_=>-1)))))&&o

```

Try it online!

### How?

Whatever the tiling is, it is guaranteed that each corner of the matrix is also a corner of the tile that we're looking for. The two outer `map()` loops extract each possible tile \\$M\\$ from the bottom-right side of the input matrix \\$m\\$ and compute its area \\$a\\$.

```
m.map((r, h) =>           // for each row r[] at position h in m[]:
  r.map((_, w) =>         //   for each value at position w in r[]:
    (                     //
      M =                 //     build M[]:
        m.slice(~h)       //       keep the last h + 1 rows of m[]
        .map(r =>         //       for each of them:
          r.slice(~w)     //         keep the last w + 1 columns
        ),                //
      a = ~w * ~h,        //     area = (w + 1) * (h + 1)
      ...                 //     attempt to do a tiling with M
    )                     //
  )                       //   end of map()
)                         // end of map()

```

We build a matrix \\$q\\$ with the same dimensions as \\$m\\$, initially filled with \\$-1\\$.

```
q = m.map(r => r.map(_ => -1))

```

At each iteration of the recursive function \\$g\\$, we look for the position \\$(x,y)\\$ of the last cell in \\$q\\$ still set to \\$-1\\$, going from left to right and from top to bottom.

By definition, this cell has either a cell already set or a border on its right, and ditto below it. So it must be the bottom-right corner of a new tile, such as the cell marked with an 'x' below:

Simultaneously, we test whether there's a cell in \\$q\\$ whose value is not \\$-1\\$ and is different from the value in \\$m\\$ at the same position. If such a tile is found, we abort the recursion.

```
q.some((r, Y) =>          // for each row r[] at position Y in q[]:
  r.some((v, X) =>        //   for each value v at position X in r[]:
    ~v ?                  //     if v is not equal to -1:
      v ^ m[Y][X]         //       abort if v is not equal to M[Y][X]
    :                     //     else:
      ![x = X, y = Y]     //       set (x, y) = (X, Y)
  )                       //   end of some()
)                         // end of some()

```

If all cells of \\$q\\$ are matching the cells of \\$m\\$ and the area of \\$M\\$ is less than (or equal to) the best area found so far, we update the output \\$o\\$ to \\$M\\$.

Otherwise, we invoke the following code 4 times:

```
F(1) & T.reverse(M = T) | z || g(F()) | F(-1)

```

The behavior of the helper function \\$F\\$ depends on the parameter \\$k\\$:

* If \\$k=1\\$, it computes the transpose \\$T\\$ of \\$M\\$ and checks whether all cells in \\$q\\$ between \\$(x-w,y-h)\\$ and \\$(x,y)\\$ are set to \\$-1\\$. The result of this test is saved in \\$z\\$.
* If \\$k\\$ is undefined, it copies the content of \\$M\\$ to \\$q\\$ at \\$(x-w,y-h)\\$.
* If \\$k=-1\\$, it cancels the previous operation by restoring all updated values to \\$-1\\$.

It is defined as follows:

```
F = k =>                  // k = parameter
  !M.map((r, Y) =>        // for each row r[] at position Y in M[]:
    r.map((v, X) =>       //   for each value v at position X in r[]:
      k ^ 1 ?             //     if k is not equal to 1:
        q[y - Y][x - X] = //       set q[y - Y][x - X]
          v | k           //       to v if k is undefined, or -1 if k = -1
      :                   //     else:
        ( z |=            //       update z:
            ~( q[y - X]   //         read q at (x - Y, y - X)
              || 0        //
            )[x - Y],     //         set z if it's not equal to -1
          T[X] =          //       compute T by writing v at the
            T[X] || []    //       relevant position
        )[Y] = v          //
    ),                    //   end of inner map()
    T = []                //   initialize T to an empty array
  )                       // end of outer map()

```

Therefore, the code block mentioned above can be interpreted as follows:

```
F(1)                      // compute the transpose T[] of M[] and test whether
&                         // M[] can be copied at (x-w, y-h) in q[]
T.reverse(M = T)          // reverse T[] and assign it to M[], which means
|                         // that M[] has been rotated 90° counterclockwise
z ||                      // if z = 0:
  g(F()) |                //   copy M[] to q[] and do a recursive call
  F(-1)                   //   restore q[] to its previous state

```

# Answer
> 4 votes
# , 195 bytes

A bit long, but blazing fast! There should be some micro-optimizations still left, but I believe there could be an overall better strategy, maybe one without boxes.

```
((]>@{.@\:[:>./@(*i.@#)[:(#*0*/@,@:=])&>]([:(~.@#~0,@:=(_&e.&,+0+/@,@:>])"2)[:,/|:@|.^:(<4)@[(-~%2*/@,@:>[+&*-~)/@,:"2/(|.~*{.@#&(,/)(#:i.)@$)"2@])&.>^:(<_)<@,:@[)[:(/:*/@:$&>)[:,/<@|:\@|:\)&.:>:

```

Try it online!

### How it works

```
&.:>:

```

Add 1 to the matrix, so we can use 0 as a special value.

```
[:,/<@|:\@|:\

```

Get all possible tiles that contain the upper left digit.

```
[:(/:*/@:$&>)

```

Sort them according to their dimension.

```
](…)&.>^:(<_)<@,:@[

```

Use the initial matrix as seed, and execute – with the possible tiles on the left side – until the result does not change, while storing the results:

```
(|.~*{.@#&(,/)(#:i.)@$)"2@]

```

Shift the matrices so the first non-zero digit is in the upper left.

```
|:@|.^:(<4)@[

```

On the left side, rotate all the tiles.

```
(-~%2*/@,@:>[+&*-~)/@,:"2/

```

For each tile and each matrix, pad the tile and matrix to the same size (`/@,:"2`). The final result will be the subtraction, but we'll do some checks here by setting faulty results to infinity. With this we later don't have to keep track which tile produced which result. We add the signum of the tile and the matrix, then everything should be 1 (or 0, if the rotated tile stuck out and we added some 0 with padding. But it these cases, as every tile is \>0, we'll have some negative numbers there.) We divide the subtraction by this check and it's either the original number or infinity.

```
(_&e.&,+0+/@,@:>])"2

```

We check if there is infinity in a matrix or a value below 0.

```
[:(~.@#~0,@:=(…)

```

And filter these out. The `~.` is not necessary, but it reduces duplicates and speeds things quite a lot in the `1 1 1,1 1 1,1 1 1` cases.

```
[:(#*0*/@,@:=])&>

```

After the function's result does not change anymore, we have a matrix where each column represents a tile, and each row contains the possible placements for N tiles. We're interested in placements that result in a matrix filled with 0, so we check for them. We now have something like

```
0 0 0 0 0 0 0 0 0  0 tiles
0 0 0 0 0 0 0 0 1  1 tiles (the right-most tile is the whole matrix)
0 0 1 0 0 0 1 0 0  2 tiles

```

---

```
[:>./@(*i.@#)

```

We multiple each row with its index and reduce them, so we get for example `0 0 2 0 0 0 2 0 1`.

```
 >@{.@\:

```

Using this as an index we sort the tiles, take the first one, unpack it and with the decrement we have the final tile.

# Answer
> 2 votes
# APL (Dyalog Unicode), ~~189~~ 173 bytes

```
{{A[⍵]⍴⍨⊃⌽⍵}{{⊃⍵[⊃⍋⍴¨⍵]},↑⍵[⍸(~0∊∊)¨⍵]}{⊃((×/⍵)÷⍨⍴,A){⍺≤1:⊂¨↓⍵⋄R←⍵∇⍨⍺-1⋄,{0<≢R:⍵[⍸{((⊢≡∪)⊃,/⍵)∧((1≡⊃∘⍴∘∪)¨↓{A[⍵]}¨⍵)}¨⍵]⋄⍬}R∘.(,∘⊂)↓⍵}⊃⍪/{(,⍳1-⍵-⍴A)∘.+,¯1+⍳⍵}¨⍵(⌽⍵)}¨,⍳⍴A←⍵}

```

Try it online!

Slow when there are few distinct values in the grid (can't eliminate possibilities quickly).

Enumerates all possible rectangles (not many), then tries adding one at a time, checking for overlap and equal elements.

**Explanation**

```
⍳⍴A←⍵    ⍝ Set A to be the given matrix, and generate all dimensions of smaller rectangles
¨,       ⍝ For each smaller dimension (e.g. 5 4):
¨⍵(⌽⍵)     ⍝ Apply the following for both the dimension and its transpose:
  {(,⍳1-⍵-⍴A)∘.+,¯1+⍳⍵}  ⍝ Get all possible vectors of the indices of each cell in each possible translated submatrix

  ((×/⍵)÷⍨⍴,A)     ⍝ The number of these matrices needed to get the right area to tile the grid
  {⍺≤1:...∇⍺-1⋄⍬}  ⍝ Repeat that many times, starting with ⍬ (empty vector):
    R←⍵∇⍨⍺-1       ⍝ Take R to be the result of the previous step
    R∘.(,∘⊂)↓⍵}⊃⍪/ ⍝ Add to R all possible existing submatrix sequences
    ⍵[⍸...]        ⍝ Filter for those that:
     ((⊢≡∪)⊃,/⍵)   ⍝ Have no overlapping tiles and
     ((1≡⊃∘⍴∘∪)¨↓{A[⍵]}¨⍵)  ⍝ Consist of the same sequence of entries
  {⊃⍵[⊃⍋⍴¨⍵]}  ⍝ Get the first possibility, sorted by area
{A[⍵]⍴⍨⊃⌽⍵}  ⍝ Get the corresponding elements from the original matrix, and correct the shape

```

---
Tags: code-golf, matrix, tiling
---


title: Make a 3var interpreter!

text:
# Question
Title: Make a 3var interpreter!
3var is a variant of deadfish which uses three variables called A, B and R. A and B are accumulators, while R is used as a result variable.

In this challenge, you need to make an interpreter for a stripped-down version of this language.

### Required Commands:

```
i   Increments A
d   Decrements A
s   Squares A
p   Prints A
P   Prints the ASCII character of A
>   Sets A to R
a   Increments B
k   Decrements B
m   Squares B
o   Prints B
O   Prints the ASCII character of B
<   Sets B to R
+   Adds A and B, stores in R
-   Subtracts B from A, stores in R
*   Multiplies A and B, stores in R
/   Divides A by B, stores in R
w   Prints R
@   Resets A to 0
#   Resets B to 0
e   Resets R to 0

```

Everything else (including whitespaces) is ignored.

### Clarifications

* `o` and `p` should output without anything after it.
* Division is integer division.
* Numbers above 255 and numbers below 0 are supported.
* 'w' should output a space or a newline after R
* Division by 0 halts without errors. (No output to STDERR)
* A, B and R are initially 0

### Rules

* This is so the shortest answer wins.
* In the event of a tie, the oldest answer wins.
* The file will be provided through command line arguments or STDIN.
* Any language is allowed.
* Eval is allowed.

### Test Cases

`Hello world!` (taken from Esolangs)

```
iisssaa/>e
maa->e#
aamam->e#
dddddddddddddddddddddddddPiiiiiiiiiiiiiiiiiiiiiiiii
iiiiPiiiiiiiPPiiiP
@#e
iis
aamaaaa
*>P
@#e
iisssaa/>e
maa->e#
aamam->e#
iiiiiiiiiiiiiiiiiiiiiiP
ddddddddP
iiiP
ddddddP
ddddddddP
@#e
iiss
aa*>
iP

```

Outputs `20spooky22me`:

```
iipois+iis<-<aaaO<OkOOkkkkOP@#iippisa+<m+>PaO

```

Outputs `9P-1420 100 3Q-1 162 0`:

```
iiispsdPkokmo/w<+w#aaaommO-w@ii*wew

```

## Leaderboards

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

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

```
# Language Name, N bytes

```

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

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

```

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

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

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

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

```

```
var QUESTION_ID=63008,OVERRIDE_USER=45220;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# 05AB1E, ~~104~~ ~~103~~ 102 bytes

```
0©U0Vv“ìÉP@p>akmO#o<+-*/ew“ykDdi…><nS'Xì'U«"Xç?0UX?®U"4ä«Dε„XU„YV‡}«"+-*÷"S„XYì0ª„©\«„®,ª«sè.Vy'/Q®+iq

```

Try it online or verify all test cases.

**Explanation:**

```
0©U0V          # Set variables `X` (A), `Y` (B) and `®` (R) to 0
               # (they are 1, 2, and -1 respectively by default)
v              # Loop over each character `y` of the (implicit) input-string:
 “ìÉP@p>akmO#o<+-*/ew“
               #  Push dictionary string "idsP@p>akmO#o<+-*/ew"
  yk           #  Get the index of `y` in this string
    D          #  Duplicate it
 di            #  If the index is not -1 (thus it's a valid character):
   …><n        #   Push string "><n"
    S          #   Convert it to a list of characters: [">","<","n"]
     'Xì      '#   Prepend an "X" in front of each item: ["X>","X<","Xn"]
        'U«   '#   Append an "U" after each item: ["X>U","X<U","XnU"]
   "Xç?0UX?®U" #   Push string "Xç?0UX?®U"
    4ä         #   Try to split it into 4 equal-sized parts: ["Xç?","0U","X?","®U"]
   «           #   Merge these two lists together:
               #    ["X>U","X<U","XnU","Xç?","0U","X?","®U"]
    D          #   Duplicate the list
     ε       } #   Map over each inner string:
      „XU„YV‡  #    And transliterate all "X" to "Y" and all "U" to "V"
   «           #   Merge the lists together:
               #    ["X>U","X<U","XnU","Xç?","0U","X?","®U",
               #     "Y>V","Y<V","YnV","Yç?","0V","Y?","®V"]
   "+-*÷"      #   Push string "+-*÷"
    S          #   Convert it to a list of characters: ["+","-","*","÷"]
     „XYì      #   Prepend "XY" in front of each item: ["XY+","XY-","XY*","XY÷"]
   0ª          #   Append a 0: ["XY+","XY-","XY*","XY÷",0]
     „©\«      #   Append "®\" after each item:
               #    ["XY+©\","XY-©\","XY*©\","XY÷©\","0©\"]
   „®,ª        #   Append string "®," to this list:
               #    ["XY+©\","XY-©\","XY*©\","XY÷©\","XY0©\","®,"]
   «           #   Merge the two lists together:
               #    ["X>U","X<U","XnU","Xç?","0U","X?","®U",
               #     "Y>V","Y<V","YnV","Yç?","0V","Y?","®V",
               #     "XY+©\","XY-©\","XY*©\","XY÷©\","XY0©\","®,"]
    s          #   Swap to get the duplicated index
     è         #   Use it to index into this list of strings
      .V       #   And evaluate/execute it as 05AB1E code
   y'/Q       '#   Check if the current character equals "/"
       ®+      #   Add the value of `®` to it
         i     #   If this is now 1:
               #   (thus the current character is "/" and the value of `®` is 0):
          q    #    Stop the program

```

Here an overview of all characters translated to 05AB1E code:

```
i   X>U        # Push `X`; increase it by 1; pop and store it as new `X`
d   X<U        # Push `X`; decrease it by 1; pop and store it as new `X`
s   XnU        # Push `X`; square it; pop and store it as new `X`
P   Xç?        # Push `X`; convert it to a character; pop and print it (without newline)
@   0U         # Push 0; pop and store 0 as new `X`
p   X?         # Push `X`; pop and print it (without newline)
>   ®U         # Push `®`; pop and store `®` as new `X`
a   Y>V        # Push `Y`; increase it by 1; pop and store it as new `Y`
k   Y<V        # Push `Y`; decrease it by 1; pop and store it as new `Y`
m   YnV        # Push `Y`; square it; pop and store it as new `Y`
O   Yç?        # Push `Y`; convert it to a character; pop and print it (without newline)
#   0V         # Push 0; pop and store 0 as new `Y`
o   Y?         # Push `Y`; pop and print it (without newline)
<   ®V         # Push `®`; pop and store `®` as new `Y`
+   XY+©\      # Push `X` and `Y`; add them together; store it in `®` (without popping);
               # and discard it from the stack
-   XY-©\      # Push `X` and `Y`; subtract them from one another; store it in `®`
               # (without popping); and discard it from the stack
*   XY*©\      # Push `X` and `Y`; multiply them together; store it in `®` (without
               # popping); and discard it from the stack
/   XY÷©\      # Push `X` and `Y`; integer-divide them from one another; store it in `®`
               # (without popping); and discard it from the stack
e   0©\        # Push 0; store 0 in `®` (without popping); and discard it from the stack
w   ®,         # Push `®`; pop and print it with trailing newline

```

See this 05AB1E tip (section *How to use the dictionary?*) to understand why `“ìÉP@p>akmO#o<+-*/ew“` is `"idsP@p>akmO#o<+-*/ew"`.
> 1 votes

# Answer
# JavaScript (ES7) 208 ~~213 223 237 241 311~~

**Edit3** Copying each other, I and Dendrobium are collapsing together.

**Edit2** Using EcmaScript 7 to save just 2 bytes, joined together handling of A and B

**Edit** Following the changes of the rules.

~~Note, I added the `r` command that is not required in the question, just to run the **old** example *Hello world*~~

```
V=p=>(o='',[for(c of'@#e'+p)eval('++x,--x,x*=x,x=R,x=0,o+=x,o+=String.fromCharCode(x),R=A+B,R=A-B,R=A*B,R=A/B|0,R=0,o+=R+` `'.replace(/x/g,(k='ids>@pP+-*/ewakm<#oO'.indexOf(c))<13?'A':'B').split`,`[k%13])],o)

// More readable
U=p=>(
  o='',
  [for(c of'@#e'+p)
   eval(
   '++x,--x,x*=x,x=R,x=0,o+=x,o+=String.fromCharCode(x),R=A+B,R=A-B,R=A*B,R=A/B|0,R=0,o+=R+` `'
   .replace(/x/g,(k='ids>@pP+-*/ewakm<#oO'.indexOf(c))<13?'A':'B')
   .split`,`[k%13])]
  ,o
)

// ES6, no array comprehension, 2 bytes more
W=p=>
  [...'@#e'+p].map(c=>
    eval(
    '++x,--x,x*=x,x=R,x=0,o+=x,o+=String.fromCharCode(x),R=A+B,R=A-B,R=A*B,R=A/B|0,R=0,o+=R+` `'
    .replace(/x/g,(k='ids>@pP+-*/ewakm<#oO'.indexOf(c))<13?'A':'B')
    .split`,`[k%13]),
    o=''
  )&&o

// Test
function test()
{
  OUT.innerHTML = V(I.value)
}

test()
```

```
textarea { width: 75%; height: 8em }
```

```
Test program <button onclick="test()">Run</button><br><textarea id=I>
iisssaa/>e
maa->e#
aamam->e#
dddddddddddddddddddddddddPiiiiiiiiiiiiiiiiiiiiiiiii
iiiiPiiiiiiiPPiiiP
@#e
iis
aamaaaa
*>P
@#e
iisssaa/>e
maa->e#
aamam->e#
iiiiiiiiiiiiiiiiiiiiiiP
ddddddddP
iiiP
ddddddP
ddddddddP
@#e
iiss
aa*>
iP
</textarea><br>Output<pre id=OUT></pre>
```
> 10 votes

# Answer
# GNU Sed (with eval option to evaluate `dc` expression), 254

Deadfish maps fairly nicely to a subset of `dc`. So we use sed to do that mapping:

```
s/^/@#e/
s/\+/AB+r/g
s/-/AB-r/g
s/\*/AB*r/g
s|/|AB/r|g
s/a/B1+b/g
s/i/A1+a/g
s/d/A1-a/g
s/s/Ad*a/g
s/p/An/g
s/P/AP/g
s/>/Ra/g
s/k/B1-b/g
s/m/Bd*b/g
s/o/Bn/g
s/O/BP/g
s/</Rb/g
s/w/Rn/g
s/@/0a/g
s/#/0b/g
s/e/0r/g
s/[ABR]/l&/g
s/[abr]/s\u&/g
s/.*/dc -e'&'/e

```

Try it online!
> 9 votes

# Answer
# Javascript ~~ES6~~ ES7, ~~217~~ ~~215~~ ~~213~~ 208 bytes

```
f=s=>(O='',[for(c of'@#e'+s)eval('v=0,++v,--v,v*=v,O+=v,O+=String.fromCharCode(v),v=R,R=0,R=A+B,R=A-B,R=A*B,R=A/B|0,O+=R+" "'.replace(/v/g,'AB'[(x='@idspP>e+-*/w#akmoO<'.indexOf(c))/13|0]).split`,`[x%13])],O)

```

Ungolfed

```
f=s=>(
    O='',                                                                   // initialize output to empty string
    [for(c of'@#e'+s)eval(                                                  // initialize A, B, and R, loop over all chars in input, eval returned function string
        'v=0,++v,--v,v*=v,O+=v,O+=String.fromCharCode(v),v=R,R=0,R=A+B,R=A-B,R=A*B,R=A/B|0,O+=R+" "' // operation list
            .replace(/v/g,'AB'[(x='@idspP>e+-*/w#akmoO<'.indexOf(c))/13|0]) // replace all instances of v with either A or B
            .split`,`[x%13])],                                              // split ops list, select corresponding function string
    O)                                                                      // return output string

```
> 8 votes

# Answer
# CJam, 112

```
q{"+-*/dspP>@ikmoO<#awe"_@#\4<"X2 U|{TU :V;}P?"S/f*'T"( _*T cT;V;0)"2/f+":T;"f+_'Tf/'Uf*+"VS 0:V; "S/++=~}%Pa/0=

```

Try it online

**Explanation:**

The program builds an array of pieces of code to be executed, and executes the corresponding piece for each character. Dealing with the division by zero is more difficult, because CJam doesn't yet have a "break" operator. Instead, the program pushes π as a marker (since no floating point number can appear otherwise), and at the end it keeps only the output before the first π.
Also, the program uses variables T, U and V instead of A, B and R, because they are preinitialized with 0 in CJam.

```
q            read the input
{…}%         transform each character
  "…"        push a string with all the 3var commands, in a convenient order
  _@         duplicate the string and bring the current character to the top
  #          find the index of the character in the string (or -1 if not found)
  \          swap with the other string copy
  4<         keep only the first 4 characters ("+-*/")
  "…"        push a string that will be used for implementing those operators
  S/         split by space into ["X2" "U|{TU" ":V;}P?"]
  f*         join with each of '+', '-', '*', '/' -> 4 strings
  'T         push the 'T' character
  "…"        push a string with implementations of commands involving A
  2/         split into pieces of length 2
  f+         prepend 'T' to each piece
  ":T;"f+    append ":T;"to each piece
  _          duplicate the array (containing full A-command implementations)
  'Tf/       split each piece by the 'T' character
  'Uf*       join each split piece using the 'U' character
              practically replacing 'T' with 'U'
              to obtain B-command implementations
  +          concatenate the 2 arrays
  "…"        push a string containing implementations for "w" and "e",
              separated by space; the string also ends with a space
  S/         split by space, obtaining the implementations for "w" and "e"
              and an empty string, for handling unrecognized characters
  ++         concatenate with the A and B command and +-*/ implementations
  =          get the corresponding string implementing the current command
              if the character was not found, -1 will get the empty string (no-op)
  ~          execute it
Pa/          split the array of results by the π separator
0=           get the first piece (before the first π, if any)

```

The actual command implementations (constructed by the program):

```
+: X2+U|{TU+:V;}P?    if (1+2)|U != 0, set V=T+U, else push π
-: X2-U|{TU-:V;}P?    if (1-2)|U != 0, set V=T-U, else push π
*: X2*U|{TU*:V;}P?    if (1*2)|U != 0, set V=T*U, else push π
/: X2/U|{TU/:V;}P?    if (1/2)|U != 0, set V=T/U, else push π
d: T( :T;             set T=T-1
s: T_*:T;             set T=T*T
p: TT :T;             push T and set T=T (no-op)
P: TcT:T;             push T converted to character and set T=T (no-op)
>: T;V:T;             push and pop T (no-op) and set T=V
@: T;0:T;             push and pop T (no-op) and set T=0
i: T):T;              set T=T+1
k: U( :U;             set U=U-1
m: U_*:U;             set U=U*U
o: UU :U;             push U and set U=U (no-op)
O: UcU:U;             push U converted to character and set U=U (no-op)
<: U;V:U;             push and pop U (no-op) and set U=V
#: U;0:U;             push and pop U (no-op) and set U=0
a: U):U;              set U=U+1
w: VS                 push V and a space
e: 0:V;               set V=0
(default): (empty)    no-op

```
> 8 votes

# Answer
# APL, 191

```
{0::→⋄A B R←0⋄{⍵∊G←'aikdms<>':⍎'AB'[1+2|G⍳⍵],'+-*∘'[M],'←','112R'[M←⌈2÷⍨G⍳⍵]⋄⍵∊G←'PpOo':⍞←⎕UCS⍣(2|G⍳⍵)⊢A B[⌈2÷⍨G⍳⍵]⋄⍵∊G←'+-*/':R∘←⌊A(⍎'+-×÷'[G⍳⍵])B⋄⍵∊G←'@#e':⍎'ABR'[G⍳⍵],'∘←0'⋄⍵='w':⍞←R}¨⍵}

```

This is a function that takes the program as an argument, e.g:

```
      ∆3var←{0::→⋄A B R←0⋄{⍵∊G←'aikdms<>':⍎'AB'[1+2|G⍳⍵],'+-*∘'[M],'←','112R'[M←⌈2÷⍨G⍳⍵]⋄⍵∊G←'PpOo':⍞←⎕UCS⍣(2|G⍳⍵)⊢A B[⌈2÷⍨G⍳⍵]⋄⍵∊G←'+-*/':R∘←⌊A(⍎'+-×÷'[G⍳⍵])B⋄⍵∊G←'@#e':⍎'ABR'[G⍳⍵],'∘←0'⋄⍵='w':⍞←R}¨⍵}
      ∆3var 'iipois+iis<-<aaaO<OkOOkkkkOP@#iippisa+<m+>PaO'
20spooky22me

```

It can be used as an anonymous function, I just gave it a name for clarity.

Explanation:

* `0::→`: if an error occurs (say, division by zero), halt without printing the error message
* `A B R←0`: initialize variables
* `{`...`}¨⍵`: for each command:

+ `⍵∊G←'aikdms<>'`: If the command is one of the type *var ← fn(var, x)*, find the proper *fn* and *x*, substitute them in and then evaluate it:
        - : evaluate
        - `'AB'[1+2|G⍳⍵`: `A` if the position of  in `'aikdms<>'` is even, `B` otherwise.
        - `'+-*∘'[M]`: add, subtract, power, or nothing, depending on `M` (defined later)
        - `'←'`: assign
        - `'112R'[M←⌈2÷⍨G⍳⍵]`: `1` (for adding and subtracting), `2` (for power), and `R` (for nothing, i.e. it just sets the variable to `R`), depending on `M`, which is whether the command belongs to the first, second, third or fourth pair.
    + `⍵∊G←'PpOo'`: output:
        - `⍞←`: output
        - `⎕UCS⍣(2|G⍳⍵)`: ASCII (well, Unicode) or number depending on whether the command was on an odd or even position in `PpOo`,
        - `⊢A B[⌈2÷⍨G⍳⍵]`: `A` or `B`, depending on whether the command was in the first or second half.
    + `⍵∊G←'+-*/`: math:
        - `R∘←⌊A(⍎'+-×÷'[G⍳⍵])B`: set `R` to the result of applying the given operator to `A` and `B`.
    + `⍵∊G←'@#e':` reset:

    - : evaluate
        - `'ABR'[G⍳⍵]`: select the right variable
        - `'∘←0`': set to zero
    + `⍵='w':⍞←R`: if the command is `w`, output `R`.
> 6 votes

# Answer
# VBA, ~~484, 453~~ 380 Bytes

To long to win but A super Simple way of doings things, Nothing Fancy just good old `Select Case`

~~Adding in Integer Division and Div 0 Error Handling Ate a lot of Bytes~~
Removed Error Handling as it seems the normal error handling results in the same functionality. Fixed Int Division to work as expected. Was also shorter.

```
Function Y(x)
For Z=1 To Len(x)
w=Mid(x,Z,1)
Select Case w
Case"i":A=A+1
Case"d":A=A-1
Case"s":A=A^2
Case"p":Y=Y &A
Case"P":Y=Y &Chr(A)
Case">":A=R
Case"a":B=B+1
Case"k":B=B-1
Case"m":B=B^2
Case"o":Y=Y &B
Case"O":Y=Y &Chr(B)
Case"<":B=R
Case"+":R=A+B
Case"-":R=A-B
Case"*":R=A*B
Case"/":R=A\B
Case"w":Y=Y &R &vbCrLf
Case"@":A=0
Case"#":B=0
Case"e":R=0
End Select
Next
End Function

```

> Thanks to Henrik Ilgen for saving ~~31~~ 104 bytes
> 4 votes

# Answer
# C, 253 241 bytes

```
#define _ c--?c--?c--
k="id@s>ak#m<e+-*/wpoPO",*p;main(c,a,b,r){for(a=b=r=0;~c;c=getchar())c=strchr(k,c),c&&(c-=k,p=&a+c/5,*p=_?_?_?_?_?printf(c?c<3?"%d":"%c":"%d ",c?c%2?a:b:r):a/(b?b:exit()):a*b:a-b:a+b:0:r:b*b:0:b-1:b+1:r:a*a:0:a-1:a+1);}

```

This code uses the string `id@s>ak#m<e+-*/wpoPO` as a table of commands. The string is arranged according to the destination of the calculated expression. It just so happens that there are 5 commands that update each of the variables:

* `id@s>` \- update `a`
* `ak#m<` \- update `b`
* `e+-*/` \- update `r`
* `wpoPO` \- update... the memory location after `a`, `b` and `r`. I hope it's not too important :)

So after locating the input character in the string of commands, its index is repeatedly decreased, and depending on when it reaches 0, an expression is chosen.

If it doesn't reach 0 after 15 subtractions, it's a `printf` with some properly chosen arguments.

Also, when dividing, it avoids division by 0 by calling `exit()`.

This code should be compiled without optimizations, because it assumes that `a`, `b` and `r` are located at adjacent addresses on stack (not in CPU registers).

Also, it should be compiled in 32-bit mode, because it converts pointers to integers and vice-versa.
> 4 votes

# Answer
# PHP, 310 bytes

First time in my life using ~~`eval`~~:

```
for($A=$B=$R=0;$c=$argv[1][$i++];)eval([i=>'++$A',d=>'--$A',s=>'$A*=$A',p=>'echo$A',P=>'echo chr($A)','>'=>'$A=$R',a=>'++$B',k=>'--$B',m=>'$B*=$B',o=>'echo$B',O=>'echo chr($B)','<'=>'$B=$R','+'=>'$R=$A+$B','-'=>'$R=$A-$B','*'=>'$R=$A*$B','/'=>'$R=$A/$B',w=>'echo$R','@'=>'$A=0','#'=>'$B=0',e=>'$R=0'][$c].';');

```

Takes the first command line input:

```
php 3var.php "iipois+iis<-<aaaO<OkOOkkkkOP@#iippisa+<m+>PaO"

```

---

Output from the examples:

> Hello world!
> 20spooky22me
> 3 votes

# Answer
# C, 357

Macros FTW!

<sub>(Who am I kidding - c will never win this one)</sub>

```
#define X(p,e) case p:e;break;
#define Y(p,a,b,c,d,e,f) X(a,p++)X(b,p--)X(c,p*=p)X(d,printf("%d",p))X(e,printf("%c",p%256))X(f,p=R)
A,B,R;main(int C,char**V){for(;*V[1];)switch(*V[1]++){Y(A,'i','d','s','p','P','>')Y(B,'a','k','m','o','O','<')X('+',R=A+B)X('-',R=A-B)X('*',R=A*B)X('/',R=A/(B?B:exit(0),1))X('w',printf("%d",R))X('@',A=0)X('#',B=0)X('e',R=0)}}

```
> 3 votes

# Answer
# JavaScript (ES6), 293 262 bytes

```
f=x=>(o="",a=b=r=0,p=String.fromCharCode,[...x].map(c=>{if(eval(`m={i_a++,d_a--,s_a*=a,p_o+=a,P_o+=p(a),">"_a=r,a_b++,k_b--,m_b*=b,o_o+=b,O_o+=p(b),"<"_b=r,"+"_r=a+b,"-"_r=a-b,"*"_r=a*b,"/"_r=a/b|0,w_o+=r,"@"_a=0,"#"_b=0,e_r=0}[c]`.replace(/_/g,":_=>")))m()}),o)

```

## Usage

```
f(`iisssaa/>e
maa->e#
aamam->e#
dddddddddddddddddddddddddPiiiiiiiiiiiiiiiiiiiiiiiii
iiiiPiiiiiiiPPiiiP
@#e
iis
aamaaaa
*>P
@#e
iisssaa/>e
maa->e#
aamam->e#
iiiiiiiiiiiiiiiiiiiiiiP
ddddddddP
iiiP
ddddddP
ddddddddP
@#e
iiss
aa*>
iP`)

=> "Hello world!"

```

## Explanation

There are a few details of the language that I'm unsure about (integer sizes, handling unrecognised characters, etc) but this solution seems to work sufficiently and ignores whitespace characters like the new-lines in the test case.

```
f=x=>(
  o="",                           // o = output string
  a=b=r=0,
  p=String.fromCharCode,
  [...x].map(c=>{                 // iterate through each character
    if(                           // if used for NOP characters (whitespace)

      // Functions:
      eval(`m={
        i_a++,
        d_a--,
        s_a*=a,
        p_o+=a,
        P_o+=p(a),
        ">"_a=r,
        a_b++,
        k_b--,
        m_b*=b,
        o_o+=b,
        O_o+=p(b),
        "<"_b=r,
        "+"_r=a+b,
        "-"_r=a-b,
        "*"_r=a*b,
        "/"_r=a/b|0,
        w_o+=r,
        "@"_a=0,
        "#"_b=0,
        e_r=0
      }[c]`.replace(/_/g,":_=>")) // dynamically add common characters

    )m()                          // execute the function
  }),
  o                               // return the output string
)

```
> 2 votes

# Answer
# Simplex v.0.8, 211 bytes

<sup><sup>(UTF-8 encoded.)</sup></sup>

```
h@u]u2ƒ§I]ƒ§M]ƒ§^O]ƒ§o]ƒ§s]ƒ§@]ƒ§Ah]ƒ§Sh]ƒ§Mh]ƒ§Vh]ƒ§&oh]ƒðI]ƒðM]ƒð^O]ƒðo]ƒðs]ƒð@]ƒðAh]ƒðSh]ƒðMh]ƒðVh]ƒð&oh]ƒ§z]ƒðz]ƒuz@]{"idspP>akmoO<+-*/w@#e"RlyG^u·u†vøÏ}

```

## Explanation

Since this is *the longest* simplex program I have thus far written, I will generally explain how this works in bullet points.

* `h@u]` \- defines macro 0. This macro simply writes to the register and makes a lambda return nothing.
* `u2` \- goes to the above strip and sets the current byte to 2; this defines the arity of the lambdas to be defined.
* `ƒ` \- begin lambda expression; once completed by `]`, will push lambda function to the lambda stack. It acts by taking (arity) cells from the pointer into its local strip, and, after completion, will set its local strip to the taken cells, unless the current byte is unwritten. The pointer is not affected. Macro 0 allows for a function to return without modifying anything in the strip.
* `§` \- moves to the first written cell in the current strip i.e. `A`.
* `ð` \- moves to the last written cell in the current strip i.e. `B`.
* `{"idspP>akmoO<+-*/w@#e"RlyG^u·u†vøÏ}`
    + `{...Ï}` repeat until the input stack is empty
    + `"idspP>akmoO<+-*/w@#e"` \- the commands
    + `Rly` \- put the strip into a tuple
    + `G^u` \- the index of the input in the tuple
    + `·` \- load the current byte<sup>th</sup> into the lambda evaluator
    + `uRL` \- goes to the strip holding `A` and `B` (writes `A` and `B` if they don't exist)
    + \- executes lambda (this is the lambda evaluator)
    + \- resets below strip

*phew* I'm impressed. It's long for Simplex, but short for everything else. `;)`
> 2 votes

# Answer
## Minkolang 0.11, 222 bytes

I'm sure this can be golfed further, but it was fun. Also, first Minkolang interpreter of another language!

```
>I3&000V$Vod?.45*[di1q=5&]x00wx1i2+kw
idspP>akmoO<+-*/w@#e
vr1+r
vr1-r
vr2;r
v0c1$((dl%"0"+$rl:d)$Ok
v0cO
vrx0cr
v1g1+1G
v1g1-1G
v1g2;1G
v1c1$((dl%"0"+$rl:d)$Ok
v1cO
v1gxd1G
vx$d+
vx$d-
vx$d*
vx$dd?.:
vdN
vrx0r
v1gx01G
vx0

```

Try it here.

### Explanation

```
>I3&000                    Initializes A, B, and R if they don't already exist.
V$V                        An idiom that ensures no time-travel.
od?.                       Reads in a character and halts if input is empty.
45*[di1q=5&]               Looks through the second row for a matching character.
            x00w           Jumps back to beginning if no match.
                x1i2+kw    Jumps to corresponding line upon match.

```

The rest of the lines are pretty simple, perhaps with the exception of those with `1$((dl%"0"+$rl:d)$Ok`, which is an idiom that prints a number without a trailing space. (I haven't yet implemented the convert-this-number-to-a-string functionality, which will be `1Z`.) Oh, yes, they all have a `v` at the beginning, which takes it back to the beginning.
> 2 votes

# Answer
# GNU Sed (with eval option to evaluate dc expression), 289

Inspired by Digital Trauma who sadly failed to realize, that a) illegal characters need to be ignored, b) dc needs the entire converted program in one argument and c) division by 0 must terminate the program without error.

If all these rules wouldn't apply, my solution would only be 235 bytes long ;)

```
H
$!d
x
s/^/@#e/
s:[^-a><de/+i*k@w#opsmOP]::g
s:[e@#]:0&:g
s:[-*+/pPid]:Q&:g
s:[-kaoO*+/]:H&:g
s:[><w]:Z&:g
s:[diak]:1&:g
s:s:Q2^>:g
s:m:H2^<:g
s:[-+*/]:&e:g
s:[ia]:+&:g
s:[dk]:-&:g
y:Oop:Pnn:
s:w:n32P:g
s:[id>@]:sq:g
s:e:sz:g
s:[#<ka]:sh:g
s:[QHZ]:l\l&:g
s:/:d0=t/:g
s/.*/dc -e'[q]st&'/e

```
> 2 votes

# Answer
# AWK, ~~311~~ 309

```
func p(z,f,x){if(c~z)printf"%"f,x}BEGIN{FS=z}{for(i=0;++i<=NF;){c=$i;A=c~/i/?A+1:c~/d/?A-1:c~/s/?A*A:c~/@/?0:c~/>/?R:A;p("p","d",A);p("P","c",A);B=c~/a/?B+1:c~/k/?B-1:c~/m/?B*B:c~/#/?0:c~/</?R:B;p("o","d",B);p("O","c",B);R=c~/+/?A+B:c~/-/?A-B:c~/*/?A*B:c~/e/?0:R;if(c~"/")if(B)R=A/B;else exit;p("w","d ",R)}}

```

TIL parenthesis were not needed around printf. 2 bytes saved!

### Ungolfed version for easier reading:

```
func p(z,f,x) {
    if(c~z) printf "%"f,x
}

BEGIN {
    FS=z
}

{
    for(i=0;++i<=NF;){
        c=$i;
        A=c~/i/?A+1:c~/d/?A-1:c~/s/?A*A:c~/@/?0:c~/>/?R:A;
        p("p","d",A);
        p("P","c",A);
        B=c~/a/?B+1:c~/k/?B-1:c~/m/?B*B:c~/#/?0:c~/</?R:B;
        p("o","d",B);
        p("O","c",B);
        R=c~/+/?A+B:c~/-/?A-B:c~/*/?A*B:c~/e/?0:R;
        if(c~"/")if(B)R=A/B;else exit;
        p("w","d ",R)
    }
}

```
> 2 votes

# Answer
# Python 2, 272

```
import sys;a,b,r=0,0,0;exec';'.join(filter(None,map(dict(x.split(':')for x in"a:b+=1|@:a=0|#:b=0|/:r=a/b|d:a-=1|PXchr(a)|i:a+=1|-:r=a-b|k:b-=1|*:r=a*b|m:b*=b|oXb|pXa|s:a*=a|OXchr(b)|wXr|+:r=a+b|e:r=0|<:b=r|>:a=r".replace('X',':print ').split('|')).get,sys.stdin.read())))

```
> 1 votes

# Answer
# Ruby, 199 bytes

```
a=b=r=0
$<.read.chars{|c|eval %w{a+=1
a-=1
a*=a
$><<a
$><<a.chr
a=r
b+=1
b-=1
b*=b
$><<b
$><<b.chr
b=r
r=a+b
r=a-b
r=a*b
b==0&&exit||r=a/b
puts\ r
a=0
b=0
r=0
p}["idspP>akmoO<+-*/w@#e".index(c)||-1]}

```

5 bytes can be saved by removing `.read` from the second line if you can tolerate a warning being printed to stderr on newer version of Ruby.
> 1 votes

# Answer
# Python, 244

```
import sys;P=sys.stdout.write;A=B=R=0;exec';'.join(filter(None,map(dict(zip('idspP>akmoO<+-*/w@#e','A+=1 A-=1 A**=2 P(`A`) P(chr(A)) A=R B+=1 B-=1 B**=2 P(`B`) P(chr(B)) B=R R=A+B R=A-B R=A*B R=A/B print(R) A=0 B=0 R=0'.split())).get,input())))

```

Bit late but I wanted to have a go.
> 1 votes

# Answer
# Prolog, 759 bytes

Not the shortest program, but at least it's structured and readable.

```
q(A,B,R,i,X,B,R):-X is A+1.
q(A,B,R,d,X,B,R):-X is A-1.
q(A,B,R,s,X,B,R):-X is A*A.
q(_,B,R,>,R,B,R).
q(A,B,R,a,A,X,R):-X is B+1.
q(A,B,R,k,A,X,R):-X is B-1.
q(A,B,R,m,A,X,R):-X is B*B.
q(A,_,R,<,A,R,R).
q(A,B,_,+,A,B,X):-X is A+B.
q(A,B,_,-,A,B,X):-X is A-B.
q(A,B,_,*,A,B,X):-X is A*B.
q(_,0,_,/,_,_,_):-!,1=2.
q(A,B,_,/,A,B,X):-B>0,X is A/B.
q(_,B,R,@,0,B,R).
q(A,_,R,#,A,0,R).
q(A,B,_,e,A,B,0).
q(A,B,R,p,A,B,R):-write(A).
q(A,B,R,'P',A,B,R):-A>0,format('~c',A).
q(A,B,R,'P',A,B,R):-write(A).
q(A,B,R,o,A,B,R):-write(B).
q(A,B,R,'O',A,B,R):-format('~c',B).
q(A,B,R,'O',A,B,R):-write(B).
q(A,B,R,w,A,B,R):-write(R),nl.
q(A,B,R,_,A,B,R).
f([],_,_,_).
f([H|T],A,B,R):-q(A,B,R,H,X,Y,Z),f(T,X,Y,Z),!.
p(X):-atom_chars(X,Y),f(Y,0,0,0).

```

**Example input**

```
p('iipois+iis<-<aaaO<OkOOkkkkOP@#iippisa+<m+>PaO').

```

Try it out online here
> 1 votes

# Answer
# Perl 5 `-Minteger -n0`, 274 bytes

```
s//;/g;s/e/R=0/g;s/\+/R=A+B/g;s/-/R=A-B/g;s/\*/R=A*B/g;s/i/A++/g;s/d/A--/g;s/s/A*=A/g;s/p/printA|0/g;s/P/print chrA/g;s/>/A=R/g;s/a/B++/g;s/k/B--/g;s/m/B*=B/g;s/o/printB|0/g;s/O/print chrB/g;s/</B=R/g;s,/,B||exit;R=A/B,g;s/w/sayR|0/g;s/\@/A=0/g;s/#/B=0/g;s/[ARB]/\$$&/g;eval

```

Try it online!
> 1 votes

---
Tags: code-golf, interpreter
---