title: A Change in Perspective

text:
# Question
Title: A Change in Perspective
In this challenge you will write a piece of text which when viewed from two different angles will create two different programs.

Your string as viewed from above must take a string containing only characters ASCII 10, 32 - 126 and output it as viewed from above. Additionally your program when viewed from the left must take a string containing only characters ASCII 10, 32 - 126 and output it as viewed from the left.

A string **viewed from above** will be the first non-space character in every column of the string, or a space if no such character exists, in the order of the columns.

Here is a Haskell program that implements this:

```
stitchZip (' ' : b) (c : d) = c : stitchZip b d
stitchZip (a : b) (c : d)   = a : stitchZip b d
stitchZip [] x = x
stitchZip x [] = x

main = getContents >>= (putStr . foldr1 stitchZip . lines)

```

Try it online!

A string **viewed from the left** will be the first non-space character in every row of the string, or a space if no such character exists, in the *reverse* order of the rows. We reverse the order of the rows since our left hand would be towards the bottom of the string.

Here is a Haskell program that implements this:

```
stitch ' ' y = y
stitch x y = x

main = getContents >>= (putStr . reverse . map (foldl stitch ' ') . lines)

```

Try it online!

Your program may use characters outside of that ASCII range, but for layout purposes all characters (other than newlines) are considered to have a width of 1. As a side effect of how the views work, your programs cannot have newlines in them (although your string almost certainly will).

## Scoring

Your score will be the number of non-space characters in your submission plus the number of space characters that appear in the two programs.

For example if your program were:

```
sc  e ex mp e
g
        a
   r

d
           l
  o

```

you would score **16** since there are **14** non whitespace characters in the submission, and each program (`score example` and `old rags`) has **1** space.

Your goal is to have as low a score as possible.

# Answer
# Jelly, score 9 + 0 = 9

```
 Z
       ⁶
      €
     ɗ
    o
   Ḣ
  ḟ
 Ṛ
Ỵ

```

From the top:

```
ỴZḟḢoɗ€⁶

```

**Try it online!** (or see it self-operate)

From the side:

```
ỴṚḟḢoɗ€⁶Z

```

**Try it online!** (or see it self-operate)

### How?

```
Ỵ Z|Ṛ ḟḢoɗ€⁶ [Z]  - Link list of characters:
Ỵ                 - split at newline characters
  Z               - | top: transpose to get columns
    Ṛ             - | side: reverse the lines
           ⁶      - set the right argument to a literal space character
          €       - for each (x = column (top) OR line (side)):
         ɗ        -   last three links as a dyad - i.e. f(x, space)
      ḟ           -     filter discard (spaces from x)
       Ḣ          -     pop & yield the head (first remaining character or 0 if none left)
        o         -     logical OR (with space character) (replace a 0 with a space)
                  - | top: no code remaining
              Z   - | side: transpose (at this point a no-op since we have a flat list)

```
> 6 votes

# Answer
# Pyth, 15 score

```
           z
        .T.
        ;
       d
       +
      !
     \
    D
   <
  h
 m
s
_

```

The two programs are:

```
smh<D\!d.T.z

```

Try it online!

```
_smh<D\!+d;.z

```

Try it online!

I attempted to make the code as similar as possible between the two programs, hence a few inefficiencies in each. Both programs filter out unwanted spaces by sorting the rows/columns by if the character is less than a `!`. Since the sorts are stable this preserves the rest of the line. The rest of the programs are fairly straightforward.

The main save that I think could be made for this approach would be to make the code that converts from empty lines to a space more similar. I haven't found a way to do that that isn't wastefully long.
> 4 votes

# Answer
# Wolfram Language (Mathematica), score 31 + 2 = 33

```
                        &
                       )
                    #
                  @
                 /
                ]
               &
              2
             #
            >
           -
          "

        "
       .
      /
     #
    [
   d
  l
 o
F
                   (
@
e
s
r
e
v
e
R

```

From the top:

```
Fold[#/." "->#2&]/@(#)&

```

Try it online!

From the side:

```
Reverse@(Fold[#/." "->#2&]/@#)&

```

Try it online!

Takes a matrix of characters as input. If the rows are not guaranteed to have equal length, add another \\$18+2\times2=22\\$ by replacing `#` with `(PadRight@#/. 0->" ")`.

If input must be a list of strings, add \\$11\\$ by replacing `#` with `Characters@#`

If input must be a single string, add \\$29\\$ instead by replacing `#` with `Characters[#~StringSplit~"\n"]`

In these cases, if lines are not guaranteed to have equal length, add an additional \\$15\\$ instead of 22 by replacing `Characters` with `Characters@StringPadRight`.
> 4 votes

# Answer
# Charcoal, score ~~22~~ 18

```
              κ→
              Ｐ
             !
            Ｋ
           Ｋ
          ‹
         ¿
        ι
       Ｆ
       ←
  «Ｊ⁰¬¹
 Ｓ
Ｗ

```

Note: This is designed for a pleasant input format i.e. at least one character on each line, then a completely empty line to terminate the input. Replace  with  and  with  for a JSON-like input format which allows for empty lines. Additionally, the variable width characters that Charcoal uses (even in a fixed width font, sigh...) mean that the columns don't quite line up nicely. Check the output of the sample link for the expected result.

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

```
ＷＳ«

```

Repeatedly read the input.

```
Ｊ⁰¬¹

```

Start at the top left of the canvas each time.

```
Ｆι

```

Loop through the characters on each line.

```
¿‹ＫＫ!κ→

```

Output the current character unless it would overwrite something already there in which case simply move right.

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

```
ＷＳ«

```

Repeatedly read the input.

Move left for each character, thus reversing the output.

```
Ｆι

```

Loop through the characters on each line.

```
¿‹ＫＫ!Ｐκ

```

Output the current character without moving the cursor unless it would overwrite something already there.
> 3 votes

# Answer
# 05AB1E (legacy), score: 10 (10 non-space bytes \+ 0)

```
  ø
         q
        н
       «
      ð
     Û
    ð
   ε
  R
 B
.

```

Outputs as a list of characters.

Top view: `.BøεðÛð«нq`
Try it online.

Side view: `.BRεðÛð«нqø`
Try it online.

EDIT: I now notice it's very similar to the Jelly answer, although I've came up with this independent.. Great minds think alike I guess.

**Explanation:**

Uses the legacy version of 05AB1E because the zip/transpose builtin `ø` works on a list of strings (whereas the new version only works on 2D lists).

```
.B           # Split the (implicit) input-string by newlines,
             # and at the same time append spaces to make all lines of equal length
  ø          # Top view: Zip/transpose the lines; swapping rows/columns
  R          # Side view: Reverse the list of lines
   ε         # Map each string to:
    ðÛ       #  Remove all leading spaces
      ð«     #  Append a space
        н    #  Only leave the first character
         q   #  And exit the program (although it still finishes the map first)
             #  Top view: nothing more
          ø  #  Side view: no-op since we've already stopped the program with `q`
             # (after the map, the resulting character-list is output implicitly)

```
> 1 votes

# Answer
# APL (Dyalog Unicode), score 11 + 2 = 13

```
         1⍉
        ⍤
       )
      '

    '
   ∘
  ~
 ⊃
(
⌽

```

Top view:

```
(⊃~∘' ')⍤1⍉

```

Left view:

```
⌽(⊃~∘' ')⍤1

```

Try it online!

### How they work

```
[⌽] (⊃~∘' ')⍤1 [⍉]
                ⍉   Top view only: Transpose the given char matrix
    (      )⍤1      On each row:
     ⊃~∘' '         Remove all spaces and take the first char
 ⌽                  Left view only: Reverse the string

```

The lack of one-byte shortcut for a space adds 3 to the score; otherwise it'd be a tie with 05AB1E.
> 1 votes

# Answer
# Python 3, 98 + 9 + 5 = 112

```

                                                                                )).strip()
                                                                                ]
                                                                                -
                                                                                :
                                                                                :
                                                        [
                                                                                )
                                                                                '
                                                                                n
                                                                                \
                                                                                '
                                                                                (
                                                                                t
                                                                                i
                                                                                l
                                                                                p
                                                                                s
                                                                               .
                                                                              s

                                                 n zip(* i+' '*len(s)for i in
                                                i

                                              i

                                            r
                                           o
                                          f
                                         '

                                       '
                                      r
                                     o
                                    ]
                                   1
                                  :
                                 [
                                )
                               (
                              p
                             i
                            r
                           t
                          s
                         .
                       i))
                      (
                   j(j
                  :
                 n
                i
               o
              j
             .
            '
           '
          =
         j
        ,
       s

     a
    d
   b
  m
 a
l

```

Top view:

```
lambda s,j=''.join:j(j(i).strip()[:1]or' 'for i in zip(*[i+' '*len(s)for i in s.split('\n')])).strip()

```

Left view:

```
lambda s,j=''.join:j(i.strip()[:1]or' 'for i in s.split('\n')[::-1])

```

Try it online!
> 1 votes

---
Tags: string, code-challenge, source-layout
---


title: Shorthand Combined Functions

text:
# Question
Title: Shorthand Combined Functions
I was doing some investigation into trig functions using compound angles recently, and noticed that the results are really long and tedious to write: $$ \cos(A+B) = \cos A \cos B - \sin A \sin B \\ \cos(A-B) = \cos A \cos B + \sin A \sin B \\ \sin(A+B) = \sin A \cos B + \sin B \cos A \\ \sin(A-B) = \sin A \cos B - \sin B \cos A \\ $$ $$ \tan(A+B) = \frac{\tan A + \tan B}{1 - \tan A \tan B} $$ $$ \tan(A-B) = \frac{\tan A - \tan B}{1 + \tan A \tan B} $$

Realising this, I devised a shorter, golfier way, of writing such expressions:

```
<direction><operator>[functions](variables)

```

Where `direction` is either `«` or `»` and `operator` is in the string `+-*/`

---

Also, when there is more variables than functions, the variables are, in a sense, left shifted through the functions, with unused variables simply being concatenated to the expression:

```
»-[f,g](x,y,z)

```

Turns into:

$$ f(x)g(y)z - f(y)g(z)x - f(z)g(x)y $$

*Note that the variables `x`, `y` and `z` are left shifting through the functions*

---

Note that when there is only one function given, it is applied as if the expression was an algebraic expansion. For example:

```
«+[cos](a,b)

```

Turns into

$$ cos(a) + cos(b) $$

---

For an expression like `«+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to every variable, as if the expression was being algebraically expanded:

```
f(foo)f(bar)f(baz)
g(foo)g(bar)g(baz)
h(foo)h(bar)h(baz)

```

These expressions are then concatenated with the provided operator (when the operator is `*`, the expressions are simply concatenated without any symbols):

```
f(foo)f(bar)f(baz) + g(foo)g(bar)g(baz) + h(foo)h(bar)h(baz)

```

---

For an expression like `»+[f, g, h](foo, bar, baz)`, each function in the function list (`f, g, h`) is applied to the variables in sequence, as if the variables were "shifting" through the functions:

```
f(foo)g(bar)h(baz)
f(bar)g(baz)h(foo)
f(baz)g(foo)h(bar)

```

These expressions are once again concatenated using the above method:

```
f(foo)g(bar)h(baz) + f(bar)g(baz)h(foo) + f(baz)g(foo)h(bar)

```

## Some Clarifications

When the direction is `»` and there are more variables than functions , the following method is applied:

```
FOR j = 0 TO length of functions
 FOR i = 0 TO length of variables
  IF i >= length of functions - 1 THEN
   Result += variables[i]
  ELSE
   Result += Functions[i] + "(" + variables[i] + ")"
 NEXT i
 Left shift variables
 Result += operator
NEXT j

```

Given the expression `»-[f,g](x,y,z)`, this would turn into:

```
f(x)g(y)z - f(y)g(z)x - f(z)g(x)y

```

Empty function lists should return an empty expression, as should empty variable lists.

When there are more functions than variables and the direction is `»`, simply ignore the functions in the functions list whose index is greater than the length of the variables list. For example, given `»+[f,g,h](x,y)`:

```
f(x)g(y) + f(y)g(x)

```

## The Challenge

Given a shorthanded string as described above, output the expanded expression

## Test Cases

```
Input -> Output
«+[cos,sin](a,b) -> cos(a)cos(b) + sin(a)sin(b)
»+[cos,sin](a,b) -> cos(a)sin(b) + cos(b)sin(a)
«[f](x,y,z,n) -> f(x)f(y)f(z)f(n)
«+[f](x,y,z,n) -> f(x) + f(y) + f(z) + f(n)
«+[f,g]() ->
»*[f,g]() ->
»-[f,g](a,b) -> f(a)g(b) - f(b)g(a)
»[g,f](a,b) -> g(a)f(b)g(b)f(a)
«+[tan](a,b) -> tan(a) + tan(b)
»+[](a,b) ->
»-[f,g](x,y,z) -> f(x)g(y)z - f(y)g(z)x - f(z)g(x)y
«/[f,g](x,y,z) -> f(x)f(y)f(z) / g(x)g(y)g(z)
«[]() ->
»[]() ->
»+[x,y](foo,bar,baz) -> x(foo)y(bar)baz + x(bar)y(baz)foo + x(baz)y(foo)bar
»+[f,g](x) -> f(x) + g(x)
«+[f,g](x) -> f(x) + g(x)
»+[f,g,h](x,y) -> f(x)g(y) + f(y)g(x)

```

Let it be known that:

* The direction will *always* be given
* The operator is *optional*
* The `[]` denoting the functions will always be present, but will not always contain functions
* The `()` denoting the variables will always be present, but will not always contain variables
* Functions can be outputted in any order just as long as the expressions are in order (`cosAsinB - sinAsinB` can be written as `sinBcosA - sinBsinA` but not as `sinAsinB - cosAsinB`)
* Variable names can be of any length
* The `«` and `»` can be taken as `<` and `>` if wanted (`«` and `»` are preferred however)

Therefore, if no functions/variables are present, then an empty output is required. Whitespacing within the answer doesn't matter (i.e. newlines/extra spaces don't invalidate outputs).

Input can also be taken as:

```
[direction, operator, [functions], [variables]]

```

In which case, `direction` will be a string, `operator` will be either an empty string or an operator, `functions` will be a (sometimes empty) list of strings, as will variables.

## Score

This is code golf, so fewest bytes wins. Standard loopholes are forbidden.

## 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=194719;
var OVERRIDE_USER=8478;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&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(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.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(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```

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

```
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <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><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><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```

# Answer
> 2 votes
# 05AB1E, 63 bytes

```
UÇ`θiVεY€…(ÿ)«}ëDg©DIgα+>∍Œ®ùεζεðK'(ýyðå≠i')«]Dg≠iJ}¸˜Xý³gIg*Ā×

```

Four loose inputs in the order `operator, direction, [variables], [functions]`.

Try it online or verify all test cases.

**Explanation:**

```
U                   # Pop and store the 1st (implicit) input `operator` in variable `X`
Ç                   # Convert the 2nd (implicit) input `direction` to a list of codepoint
 `                  # Push this codepoint to the stack
  θ                 # Only leave its last digit
   i                # If this digit is 1 (so the direction is "«"):
    V               #  Pop and store the 3rd (implicit) input `variables` in variable `Y`
    ε       }       #  Map over the 4th (implicit) input `functions`:
     Y              #   Push the `variable`-list from variable `Y`
      €…(ÿ)         #   Surround each variable with parenthesis
           «        #   And append it to the current `function` we're mapping
   ë                # Else (so the direction is "»" instead):
    D               #  Duplicate the 3rd (implicit) input `variables`
     g              #  Pop and push the length to get the amount of `variables`
      ©             #  Store it in variable `®` (without popping)
       D            #  Duplicate this length
        I           #  Push the fourth input `functions`
         g          #  Pop and take its length as well
          α         #  Take the absolute difference between the two amounts
           +        #  And add it to the duplicated amount of `variables`
            >       #  And increase it by 1
             ∍      #  Then extend the duplicated `variables` list to that length
    Œ               #  Get all sublists of this list
     ®ù             #  Only leave the sublists of a length equal to variable `®`
       ε            #  Map each remaining sublist to:
        ζ           #   Create pairs with the 4th (implicit) input `functions`,
                    #   with a default space as filler character if the lengths differ
         ε          #   Map each pair:
          ðK        #    Remove the spaces
          '(ý      '#    Join the pair with a ")" delimiter
          yðå≠i     #    If the current pair did NOT contain a space:
               ')« '#     Append a ")"
]                   # Close all open if-statements and maps
 D                  # Duplicate the resulting list
  g≠i }             # Pop and if its length is NOT 1:
     J              #  Join the inner-most list together to a string
       ¸            # Then wrap it into a list (in case it wasn't a list yet)
        ˜           # And deep flatten the list
         Xý         # Join it by the operator we stores in variable `X`
           ³g       # Get the length of the 3rd input-list `variables`
             Ig     # And the length of the 4th input-list `functions`
               *    # Multiply them with each other
                Ā   # Truthify it (0 remains 0; everything else becomes 1)
                 ×  # And repeat the string that many times
                    # (so it becomes an empty string if either list was empty,
                    #  or remains unchanged otherwise)
                    # (after which this is output implicitly as result)

```

# Answer
> 4 votes
# JavaScript (ES6),  ~~174~~  171 bytes

```
(d,o,f,v,g=(f,V=v)=>f?V.map(v=>f+`(${v})`):V)=>f+f&&v+v?(d<'»'?f[1]?f.map(f=>g(f).join``):g(f[0]):v.map((_,i)=>v.map((_,j)=>g(f[j],[v[i++%v.length]])).join``)).join(o):''

```

Try it online!

### Commented

```
( d,                              // d   = direction
  o,                              // o   = operator
  f,                              // f[] = list of functions
  v,                              // v[] = list of variables
  g = (f, V = v) =>               // g = helper function taking (f, V[])
    f ?                           //   if f is defined:
      V.map(v =>                  //     for each variable v in V[]:
        f + `(${v})`              //       return f, followed by '(v)'
      )                           //
    :                             //   else:
      V                           //     just return V[] as-is
) =>                              //
  f + f && v + v ?                // if both f[] and v[] are non-empty:
    ( d < '»' ?                   //   if the direction is '«':
        f[1] ?                    //     if there are at least 2 functions:
          f.map(f =>              //       for each function f_i in f[]:
            g(f).join``           //         return 'f_i(v_0)f_i(v_1)...'
          )                       //       end of map()
        :                         //     else:
          g(f[0])                 //       return [ 'f_0(v_0)', 'f_0(v_1)', ... ]
      :                           //   else (the direction is '»'):
        v.map((_, i) =>           //     for each variable at position i:
          v.map((_, j) =>         //       for each variable at position j:
            g(                    //         return [ 'f_j(v_k)' ]
              f[j],               //         where k = i mod v.length
              [v[i++ % v.length]] //         and increment i
            )                     //
          ).join``                //       end of inner map(); join the list
        )                         //     end of outer map()
    ).join(o)                     //   join the final list with the operator
  :                               // else:
    ''                            //   just return an empty string

```

# Answer
> 1 votes
# Python 2, ~~179~~ ~~190~~ 194 bytes

```
lambda d,o,F,V,S='%s(%s)':(o*(o>'*')).join([(''.join(S%(u,v)for v in V)for u in F if V),(''.join(map(lambda u,v:v and u and S%(u,v)or v or'',F,(V+V)[i:i+len(V)]))for i in range(len(V)))][d>'<'])

```

Try it online!

11 bytes lost to fixing a bug.

A function that takes a direction, an operator, a list of functions, and a list of variables. For direction, uses `<,>` instead of `«,»` because utf-x reasons. This assumes that if the direction is `>`, and there are more functions than variables, that we ignore the excess function(s); e.g., `>*[f,g,h],[c,d]) => f(c)g(d)*f(d)g(c)`

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 177 bytes

```
(d,o,f,v)=>string.Join(o=="*"?"":o,d<61?f.Select(l=>v.Aggregate("",(a,b)=>a+l+$"({b})")):v.Select((x,y)=>string.Concat(v.Select((i,o)=>o>=f.Count?i:f[(y+o)%f.Count]+$"({i})"))))

```

Try it online!

---
Tags: code-golf, math, parsing
---


# Question
Title: Calculate the internal angles of a regular polygon with N sides
This is a simple challenge: given `n` in any way practical (Function arg, stdin, file, constant in code) output the **internal angles** (NOT the sum of the internal angles, just one) of a regular polygon with `n` sides. The output can be in degrees, gradians or radians, and can be displayed in any way practical (Function return, stdout, stderr if you feel like it, file etc)

As usual, smallest byte count wins.

# Answer
# MathGolf, ~~6~~ ~~5~~ 4 bytes

```
⌡π*╠

```

-1 byte thanks to *@someone* nu outputting in gradians instead of degrees.
Another -1 byte by outputting in radians instead.

Try it online.

Outputs in radians by using the formula: \\$A(n) = \frac{(n−2)×\pi}{n}\\$.

**Explanation:**

```
⌡     # Decrease the (implicit) float input by 2
 π*   # Multiply it by PI
   ╠  # Then divide it by the (implicit) input (b/a builtin)
      # (after which the entire stack joined together is output implicitly as result)

```
> 6 votes

# Answer
# Perl 6, 8 bytes

```
π- τ/*

```

Try it online!

Output in radians. Simple function in WhateverCode notation which computes \\$π-τ/n\\$. \\$τ\\$ is the constant *tau* equaling \\$2π\\$.
> 14 votes

# Answer
# Python 3, 18 bytes

```
lambda s:180-360/s

```

An unnamed function which returns a floating point number of degrees. (For gradians swap `180` for `200` and `360` for `400`.)

**Try it online!**
> 8 votes

# Answer
# JavaScript, 12 bytes

```
n=>180-360/n

```

Try it Online!
> 7 votes

# Answer
# Shakespeare Programming Language, 242 226 203 bytes

Try it online!

(Whitespace added for readability only)

```
N.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]
Ajax:Listen tothy.
You is the quotient betweenthe product ofthe sum ofyou a big pig twice the square oftwice the sum ofa big big cat a cat you.
Open heart

```

Explanation: I use the formula ((n-2)200)/n. Input in STDIN. Much of this program is the number 200, which I represent as 2\*2\*2\*(1+2\*2\*2\*(2+1)). Saved 16 bytes by switching to gradians, since 180 is harder to represent than 200. Saved 23 bytes by instead representing 200 as 2\*(2\*(4+1))^2.
> 7 votes

# Answer
# 05AB1E, 6 bytes

```
ÍƵΔ*I/

```

Try it online or verify some more test cases (output in degrees).

**Explanation:**

Uses the formula \\$A(n) = \frac{(n-2)×X}{n}\\$ where \\$n\\$ is the amount of sides, and \\$A(n)\\$ is the interior angle of each corner, and \\$X\\$ is a variable depending on whether we want to output in degrees (\\$180\\$), radians (\\$\pi\\$), or gradians (\\$200\\$).

```
Í       # Decrease the (implicit) input by 2
 ƵΔ*    # Multiply it by the compressed integer 180 (degrees output)
 žq*    # Multiply it by the builtin PI (radians output)
 т·*    # Multiply it by 100 doubled to 200 (gradians output)
    I/  # Divide it by the input
        # (after which the result is output implicitly)

```

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

# Answer
# Japt, ~~8~~ 7 bytes

```
Í*-#´/U

```

Try it

```
Í*-#´/U     :Implicit input of integer U
Í           :Subtract from 2
 *          :Multiply by
  -#´       :-180
     /U     :Divided by U

```

Taking a page out of Kevin's book, see this Japt tip to find out why `#´ = 180`.
> 6 votes

# Answer
# WDC 65816 machine code, 20 bytes

Hexdump:

```
00000000: a2ff ffa9 6801 e838 e500 b0fa 8600 a9b5  ....h..8........
00000010: 00e5 0060

```

Assembly:

```
    ; do 360/n (using repeated subtraction... it'll go for at most 120 loops anyways, with sane inputs)
    LDX #$FFFF
    LDA.w #360
loop:
    INX
    SEC
    SBC $00
    BCS loop
; quotinent in X now. do 180-X
    STX $00
    LDA.w #181 ; carry is clear here, so compensate by incrementing accumulator
    SBC $00
    RTS

```

Input in $00, output in A. Overwrites $00 and X. 16-bit A/X/Y on entry (REP #$30).

Apparently I'm the only one using \\$ 180 - \frac{360}{n} \\$ instead of the more conventional formula. Note that this code rounds the division downwards, and thus rounds the result upwards.
> 6 votes

# Answer
# , ~~21~~ ~~20~~ 14 bytes

-7 thanks to Robin Ryder. Outputs in radians

```
pi-2*pi/scan()

```

Try it online!
> 6 votes

# Answer
# APL (Dyalog Unicode), 6 bytes

```
○1-2÷⊢

```

Try it online!

The result is in radians. It implements `pi * (1 - 2 / x)`. The big circle is the "pi times" function.
> 6 votes

# Answer
# Python 3, 20 bytes

```
lambda n:(n-2)*180/n

```

Try it online!
> 5 votes

# Answer
# C (gcc), 18 bytes

```
z(n){n=180-360/n;}

```

Try it online!

---

The above has accuracy issues on some inputs, below does not within the constraints of a float. The same could be said about slightly longer code which uses doubles... it's data types of ever increasing width all the way down.

# C (gcc), 30 bytes

```
float z(float n){n=180-360/n;}

```

Try it online!
> 5 votes

# Answer
# Wolfram Language (Mathematica), 9 bytes

```
Pi-2Pi/#&

```

Try it online!

Returns the angle, in radians.
> 5 votes

# Answer
# APL (Dyalog Unicode), ~~11~~ 9 bytes

```
180-360÷⊢

```

Try it online!

Train that returns the value of each angle in degrees. Shaved a couple bytes off by switching to a smaller formula.
> 4 votes

# Answer
# Excel, 11 bytes

```
=180-360/A1

```

Result in Degrees.

For Degrees (and Gradians), 3 bytes can be saved by simplifying `=(A1-2)*180/A1`.

The Radians version though remains the same length: `=(A1-2)*PI()/A1` vs `=PI()-2*PI()/A1`. Shortest Radians answer is 14 bytes: `=(1-2/A1)*PI()`
> 4 votes

# Answer
# Jelly, 6 bytes

```
_2÷×ØP

```

A monadic Link accepting an integer which outputs a float.

**Try it online!**

### How?

```
_2÷×ØP - Link: integer, sides
 2     - literal two
_      - (sides) subtract
  ÷    - divided by (sides)
    ØP - literal pi (well, a float representation of it)
   ×   - multiply

```
> 3 votes

# Answer
# Cubix, 31 bytes

```
U;o;O@...I2-'´*p,O;%u//'O;oS@!

```

Try it online!

Outputs degrees as a integer and a fraction (if needed). This was interesting to do as, there is no floats in Cubix. I hope the output format is OK for the challenge.

Wrapped onto a cube

```
      U ; o
      ; O @
      . . .
I 2 - ' ´ * p , O ; % u
/ / ' O ; o S @ ! . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

```

Watch It Run

* `I2-'´*` Get n input, take away 2, push 180 and multiply
* `p,O;` Bring initial input to the TOS, integer divide, output integer and pop
* `%u!` Do modulo, u-Turn to the right, test for 0
    + `@` if zero halt
* `So;O` push 32 (space) onto stack, output as char and pop. Output modulo result
* `'//` push / to stack and reflect around the cube. This will end up on the top face after jumping an output
* `o;U;O@` output the `/`, pop, u-Turn to the left, pop and output the input
> 3 votes

# Answer
# Retina 0.8.2, ~~44~~ ~~42~~ 39 bytes

crossed out 44 is still regular 44

```
.+
$*
^11
$' $&
\G1
180$*
(?=1+ (1+))\1

```

Try it online! Explanation:

```
.+
$*

```

Convert to unary.

```
^11
$' $&

```

Make a copy that is two less than the input.

```
\G1
180$*

```

Multiply that copy by 180.

```
(?=1+ (1+))\1

```

Divide by the original input and convert to decimal.

In Retina 1 you would obviously replace the `$*` with `*` and hence the `1` with `_` but you could then save a further 5 bytes by replacing the middle two stages with this stage:

```
^__
180*$' $&

```
> 2 votes

# Answer
# , 18 bytes

Hardly a new answer, but since I cannot comment I'll post it anyway. Output is in radians.

```
n=scan();pi-2*pi/n

```

Try it online!
> 2 votes

# Answer
# PHP (7.4), ~~21~~ 18 bytes

-3 bytes thanks to Jonathan Allan.

```
fn($n)=>180-360/$n

```

Try it online!
> 1 votes

# Answer
# Bash, 21 bytes

Same answer as everyone else, but in Bash :)

```
echo $[($1-2)*180/$1]

```

Try it online!
> 1 votes

# Answer
# , 9 bytes

```
%~180*-&2

```

Try it online!

or

# , 9 bytes

```
180-360%]

```

Try it online!

# K (oK), 8 bytes

```
180-360%

```

Try it online!
> 1 votes

# Answer
# , 8 bytes

```
%o.@*-&2

```

Try it online!

Implements `pi * (x - 2) / x`. Just like APL, J has the "Pi times" built-in `o.`.

### How it works

```
%o.@*-&2
     -&2  x - 2
%   *-&2  (1/x) * (x - 2)
 o.@      Pi times the above

```
> 1 votes

# Answer
# Forth (gforth), 25 bytes

```
: f 180e 360e s>f f/ f- ;

```

Try it online!

Output is in degrees

### Code Explanation

```
: f          \ start a new word definition
  180e       \ put 180 on the floating point stack
  360e       \ put 360 on the floating point stack
  s>f f/     \ move n to the floating point stack and divide 360 by n
  f-         \ subtract result from 180
;            \ end word definition

```
> 1 votes

# Answer
# Zsh, 17 bytes

```
<<<$[180-360./$1]

```

Try it online!

---

Pending consensus, the following may be a valid **15 byte** solution, or more likely a **17 byte** tie with `()` declaring it a function:

```
((180-360./$1))

```

Try it online!
> 1 votes

# Answer
# Runic Enchantments, 8 bytes

```
PPi2,,-@

```

Try it online!

Output is in radians.

### Explanation

```
P           Push Pi
 P          Push Pi
  i         Read input
   2        Push 2
    ,       Divide
     ,      Divide
      -     Subtract
       @    Output and terminate

```

Works out to `Pi-(Pi/(i/2))` which is equivalent to `Pi-(2Pi/i)` (`PP2*i,-@`, same length), I just liked the "push all the parts, then do all the math" arrangement ("it looked prettier").
> 1 votes

# Answer
# SimpleTemplate, 37 bytes

Just uses the simple formule `180-360/n` used on other answers.
Due to ... sub-optimal ... math support, the formule was adapted to `(-360/$n)+180` (it's almost the same, calculated in a different order).

```
{@set/A-360 argv}{@incby180A}{@echoA}

```

You can try it on: http://sandbox.onlinephpfunctions.com/code/00b314dee3c10139928928d124be9fc1c59ef4bf
On line 918, you can change between `golfed`, `ungolfed` and `fn`, to try the variants below.

**Ungolfed:**

```
{@set/ A -360 argv}
{@inc by 180 A}
{@echo A}

```

Yeah, there's not much to ungolf...

**Explanation:**

* `{@set/ A -360 argv}` \- Stores in `A` the result of `-360/argv`.
`argv` is a variable that holds all passed arguments (in a function or when running the code).
`A` is now an array with `argc` elements (`argc` holds the number of aguments passed).
* `{@inc by 180 A}` \- Increments all values of `A` by 180 (`A+180`, basically)
* `{@echo A}` \- Outputs the values of A, without delimiter.
One could use `{@return A}` if inside a function, to get an usable array.

**Function alternative:**

Converting to a function to get an usable array is easy:

```
{@fn N}
    {@set/ A -360 argv}
    {@inc by 180 A}
    {@return A}
{@/}

```

Creates a function `N` that takes multiple arguments and returns an array.

Just call it as `{@call N into <variable> <argument, arguments...>}`.

---

If you are curious, this code compiles to the following:

```
// {@set/A-360 argv}
$DATA['A'] = array_map(function($value)use(&$DATA){return (-360 / $value);}, $FN['array_flat']((isset($DATA['argv'])?$DATA['argv']:null)));

// {@incby180A}
$DATA['A'] = $FN['inc'](isset($DATA['A'])?$DATA['A']:0, 180);

// {@echoA}
echo implode('', $FN['array_flat']((isset($DATA['A'])?$DATA['A']:null)));

```
> 1 votes

---
Tags: code-golf
---


title: Write it into number theory style

text:
# Question
Title: Write it into number theory style
Write a mathematical statement, using the symbols:

* `There exists at least one non-negative integer` (written as `E`, existential quantifier)
* `All non-negative integers`(written as `A`, universal quantifier)
* `+` (addition)
* `*` (multiplication)
* `=` (equality)
* `>`, `<` (comparison operators)
* `&`(and), `|`(or), `!`(not)
* `(`, `)` (for grouping)
* variable names

which is equivalent to the statement

> There exists a rational number a, such that π + e * a is rational.

(of course, \\$\pi =3.1415...\\$ is the mathematical constant equal to the circumference divided by the diameter of a circle, and \\$e=2.7182...\\$ is Euler's number)

You must prove that your statement is indeed equivalent to the statement above.

Obviously, the “shortest” way to go about this is to prove the statement true or false, and then answer with a trivially true or false statement, as all true statements are equivalent to one another, as are all false statements.

However, the given statement’s truth value is an unsolved problem in mathematics: we don't even know if \\$\pi+e\\$ is irrational! Therefore, barring groundbreaking mathematical research, the challenge is to find a “simple” equivalent statement, prove its equivalence, and describe it as briefly as possible.

# Scoring

`E` `A` `+` `*` `=` `>` `<` `&` `|` and `!` each add 1 to the score. `(` and `)` don't add anything to the score. Each variable name adds 1 to the score.

E.g. `E x (A ba x+ba>x*(x+ba))` score 13 (`E` `x` `A` `ba` `x` `+` `ba` `>` `x` `*` `x` `+` `ba`)

Lowest score wins.

---

# Note:

Disclaimer: This note was not written by the OP.

* This is **not** a challenge. Answers are not required to contain code.
* This is similar to, but not, a challenge, as you need to write a statement and prove it being equivalent to another statement.
* You are allowed to submit a trivially-true (e.g., for all x, x = x `Ax x=x`) or a trivially-false statement (e.g., for all x, x \> x `Ax x>x`) if you can prove the statement above is true/false.
* You are allowed to use additional symbols (similar to lemma in proof-golf), but the score would be counted the same as you not using them.
For example, if you define `a => b` to mean `(!a) | b`, each time you use `=>` in your proof, your score increases by 2.
* Because constants are not listed in the allowed symbols, you must not use them.
For example: The statement `1 > 0` can be written as

```

Forall zero: ( zero + zero = zero ) =>
Forall one: ( Forall x: x * one = x ) =>
one > zero

```

at the score of 23. (remember that `=>` costs 2 per use).

# Hints

* To use natural constants, you may do `E0, 0+0=0 & E1, At 1*t=t &` (so you don't need `=>` which is more expansive); for numbers larger than 1, just add some 1's

# Answer
> 4 votes
# 270

```
E1                                                                              { Exist 1, defined when Any k introduced }
Ec1 Ec2 Ec3 Ec4 Ec5 Ak k*1=k & c3>1 & ( En0 An n<n0 |                           { for large enough n, |(c1-c4)e+c3(4-pi)/8+(c2-c5)|<1/k }
Ex Ep Ew Emult At (Eb ((b>1 & Eh b*h=t) &! Eh h*p=b)) |                         { x read in base-p, then each digit in base-w. t as a digit }
Ee1 Ee2 Ehigher Elower e2<p & lower<t & ((higher*p+e1)*p+e2)*t+lower=x &        { last digit e1, this digit e2 }
    { Can infer that e2=w+1 | e1<=e2 & u1<=u2 & i1<=i2 & s1<=s2 & t1<=t2, so some conditions omitted }
Ei1 Es1 Et1 Eu1 (((u1*w)+i1)*w+t1)*w+s1=e1 &                                    { (u,i,t,s) }
Ei2 Es2 Et2 Eu2 i2<w & s2<w & t2<w & (((u2*w)+i2)*w+t2)*w+s2=e2 &               { e2=1+w is initial state u=i=0, s=t=1 }
(e2=w+1 | e1=e2 | i2=i1+1+1 & s2=s1*(n+1) & t2=t1*n &                           { i=2n, s=(n+1)^n, mult=t=n^n, s/mult=e }
Eg1 Eg2 g1+1=(i2+i2)*(i2+i2) & g1*u1+mult=g1*u2+g2 & g2<g1) &                   { u/mult=sum[j=4,8,...,4n]1/(j*j-1)=(4-pi)/8. mult=g1*(u2-u1)+g2 }
(t>1 | i2=n+n & t2=mult & Ediff Ediff2                                          { check at an end t=1 }
c1*s2+c2*mult+c3*u2+diff=c4*s2+c5*mult+diff2 & k*(diff+diff2)<mult))            { |diff-diff2|<=diff+diff2<mult/k, so ...<1/k }

```

`a|b&c` is `a|(b&c)` since I think removing these parentheses makes it look better, anyway they're free.

Used JavaScript `"(expr)".replace(/\{.*?\}/g,'').match(/[a-z0-9]+|[^a-z0-9\s\(\)]/g)` to count tokens.

# Answer
> 29 votes
# 671

`E a (a+a>a*a & (E b (E c (E d (A e (A f (f<a | (E g (E h (E i ((A j ((!(j=(f+f+h)*(f+f+h)+h | j=(f+f+a+i)*(f+f+a+i)+i) | j+a<e & (E k ((A l (!(l>a & (E m k=l*m)) | (E m l=e*m))) & (E l (E m (m<k & g=(e*l+(j+a))*k+m)))))) & (A k (!(E l (l=(j+k)*(j+k)+k+a & l<e & (E m ((A n (!(n>a & (E o m=n*o)) | (E o n=e*o))) & (E n (E o (o<m & g=(e*n+l)*m+o))))))) | j<a+a & k=a | (E l (E m ((E n (n=(l+m)*(l+m)+m+a & n<e & (E o ((A p (!(p>a & (E q o=p*q)) | (E q p=e*q))) & (E p (E q (q<o & g=(e*p+n)*o+q))))))) & j=l+a+a & k=j*j*m))))))) & (E j (E k (E l ((E m (m=(k+l)*(k+l)+l & (E n (n=(f+m)*(f+m)+m+a & n<e & (E o ((A p (!(p>a & (E q o=p*q)) | (E q p=e*q))) & (E p (E q (q<o & j=(e*p+n)*o+q))))))))) & (A m (A n (A o (!(E p (p=(n+o)*(n+o)+o & (E q (q=(m+p)*(m+p)+p+a & q<e & (E r ((A s (!(s>a & (E t r=s*t)) | (E t s=e*t))) & (E s (E t (t<r & j=(e*s+q)*r+t))))))))) | m<a & n=a & o=f | (E p (E q (E r (!(E s (s=(q+r)*(q+r)+r & (E t (t=(p+s)*(p+s)+s+a & t<e & (E u ((A v (!(v>a & (E w u=v*w)) | (E w v=e*w))) & (E v (E w (w<u & j=(e*v+t)*u+w))))))))) | m=p+a & n=(f+a)*q & o=f*r)))))))) & (E m (m=b*(h*f)*l & (E n (n=b*(h*f+h)*l & (E o (o=c*(k*f)*i & (E p (p=c*(k*f+k)*i & (E q (q=d*i*l & (m+o<q & n+p>q | m
o+q | o<n+q & p>m+q))))))))))))))))))))))))))`

### How it works

First, multiply through by the purported common denominators of a and (π + e·a) to rewrite the condition as: there exist a, b, c ∈ ℕ (not all zero) with a·π + b·e = c or a·π − b·e = c or −a·π + b·e = c. Three cases are necessary to deal with sign issues.

Then we’ll need to rewrite this to talk about π and e via rational approximations: for all rational approximations π₀ \< π \< π₁ and e₀ \< e \< e₁, we have a·π₀ + b·e₀ \< c \< a·π₁ + b·e₁ or a·π₀ − b·e₁ \< c \< a·π₁ + b·e₀ or −a·π₁ + b·e₀ \< c \< −a·π₀ + b·e₁. (Note that we now get the “not all zero” condition for free.)

Now for the hard part. How do we get these rational approximations? We want to use formulas like

2/1 · 2/3 · 4/3 · 4/5 ⋯ (2·k)/(2·k + 1) \< π/2 \< 2/1 · 2/3 · 4/3 · 4/5 ⋯ (2·k)/(2·k + 1) · (2·k + 2)/(2·k + 1),

((k + 1)/k)k \< e \< ((k + 1)/k)k + 1,

but there’s no obvious way to write the iterative definitions of these products. So we build up a bit of machinery that I first described in this Quora post. Define:

divides(d, a) := ∃b, a = d·b,

powerOfPrime(a, p) := ∀b, ((b \> 1 and divides(b, a)) ⇒ divides(p, b)),

which is satisfied iff a = 1, or p = 1, or p is prime and a is a power of it. Then

isDigit(a, s, p) := a \< p and ∃b, (powerOfPrime(b, p) and ∃q r, (r \< b and s = (p·q + a)·b + r))

is satisfied iff a = 0, or a is a digit of the base-p number s. This lets us represent any finite set using the digits of some base-p number. Now we can translate iterative computations by writing, roughly, there exists a set of intermediate states such that the final state is in the set, and every state in the set is either the initial state or follows in one step from some other state in the set.

Details are in the code below.

### Generating code in Haskell

```
{-# LANGUAGE ImplicitParams, TypeFamilies, Rank2Types #-}

-- Define an embedded domain-specific language for propositions.
infixr 2 :|

infixr 3 :&

infix 4 :=

infix 4 :>

infix 4 :<

infixl 6 :+

infixl 7 :*

data Nat v
  = Var v
  | Nat v :+ Nat v
  | Nat v :* Nat v

instance Num (Nat v) where
  (+) = (:+)
  (*) = (:*)
  abs = id
  signum = error "signum Nat"
  fromInteger = error "fromInteger Nat"
  negate = error "negate Nat"

data Prop v
  = Ex (v -> Prop v)
  | Al (v -> Prop v)
  | Nat v := Nat v
  | Nat v :> Nat v
  | Nat v :< Nat v
  | Prop v :& Prop v
  | Prop v :| Prop v
  | Not (Prop v)

-- Display propositions in the given format.
allVars :: [String]
allVars = do
  s <- "" : allVars
  c <- ['a' .. 'z']
  pure (s ++ [c])

showNat :: Int -> Nat String -> ShowS
showNat _ (Var v) = showString v
showNat prec (a :+ b) =
  showParen (prec > 6) $ showNat 6 a . showString "+" . showNat 7 b
showNat prec (a :* b) =
  showParen (prec > 7) $ showNat 7 a . showString "*" . showNat 8 b

showProp :: Int -> Prop String -> [String] -> ShowS
showProp prec (Ex p) (v:free) =
  showParen (prec > 1) $ showString ("E " ++ v ++ " ") . showProp 4 (p v) free
showProp prec (Al p) (v:free) =
  showParen (prec > 1) $ showString ("A " ++ v ++ " ") . showProp 4 (p v) free
showProp prec (a := b) _ =
  showParen (prec > 4) $ showNat 5 a . showString "=" . showNat 5 b
showProp prec (a :> b) _ =
  showParen (prec > 4) $ showNat 5 a . showString ">" . showNat 5 b
showProp prec (a :< b) _ =
  showParen (prec > 4) $ showNat 5 a . showString "<" . showNat 5 b
showProp prec (p :& q) free =
  showParen (prec > 3) $
  showProp 4 p free . showString " & " . showProp 3 q free
showProp prec (p :| q) free =
  showParen (prec > 2) $
  showProp 3 p free . showString " | " . showProp 2 q free
showProp _ (Not p) free = showString "!" . showProp 9 p free

-- Compute the score.
scoreNat :: Nat v -> Int
scoreNat (Var _) = 1
scoreNat (a :+ b) = scoreNat a + 1 + scoreNat b
scoreNat (a :* b) = scoreNat a + 1 + scoreNat b

scoreProp :: Prop () -> Int
scoreProp (Ex p) = 2 + scoreProp (p ())
scoreProp (Al p) = 2 + scoreProp (p ())
scoreProp (p := q) = scoreNat p + 1 + scoreNat q
scoreProp (p :> q) = scoreNat p + 1 + scoreNat q
scoreProp (p :< q) = scoreNat p + 1 + scoreNat q
scoreProp (p :& q) = scoreProp p + 1 + scoreProp q
scoreProp (p :| q) = scoreProp p + 1 + scoreProp q
scoreProp (Not p) = 1 + scoreProp p

-- Convenience wrappers for n-ary exists and forall.
class OpenProp p where
  type OpenPropV p
  ex, al :: p -> Prop (OpenPropV p)

instance OpenProp (Prop v) where
  type OpenPropV (Prop v) = v
  ex = id
  al = id

instance (OpenProp p, a ~ Nat (OpenPropV p)) => OpenProp (a -> p) where
  type OpenPropV (a -> p) = OpenPropV p
  ex p = Ex (ex . p . Var)
  al p = Al (al . p . Var)

-- Utility for common subexpression elimination.
cse :: Int -> Nat v -> (Nat v -> Prop v) -> Prop v
cse uses x cont
  | (scoreNat x - 1) * (uses - 1) > 6 = ex (\x' -> x' := x :& cont x')
  | otherwise = cont x

-- p implies q.
infixl 1 ==>

p ==> q = Not p :| q

-- Define one as the unique n with n+n>n*n.
withOne ::
     ((?one :: Nat v) =>
        Prop v)
  -> Prop v
withOne p =
  ex
    (\one ->
       let ?one = one
       in one + one :> one * one :& p)

-- a is a multiple of d.
divides d a = ex (\b -> a := d * b)

-- a is a power of p (assuming p is prime).
powerOfPrime a p = al (\b -> b :> ?one :& divides b a ==> divides p b)

-- a is 0 or a digit of the base-p number s (assuming p is prime).
isDigit a s p =
  cse 2 a $ \a ->
    a :< p :&
    ex
      (\b -> powerOfPrime b p :& ex (\q r -> r :< b :& s := (p * q + a) * b + r))

-- An injection from ℕ² to ℕ, for representing tuples.
pair a b = (a + b) ^ 2 + b

-- πn₀/πd < π/4 < πn₁/πd, with both fractions approaching π/4 as k
-- increases:
-- πn₀ = 2²·4²·6²⋯(2·k)²·k
-- πn₁ = 2²·4²·6²⋯(2·k)²·(k + 1)
-- πd = 1²⋅3²·5²⋯(2·k + 1)²
πBound p k cont =
  ex
    (\s x πd ->
       al
         (\i ->
            (i := pair (k + k) x :| i := pair (k + k + ?one) πd ==>
             isDigit (i + ?one) s p) :&
            al
              (\a ->
                 isDigit (pair i a + ?one) s p ==>
                 ((i :< ?one + ?one :& a := ?one) :|
                  ex
                    (\i' a' ->
                       isDigit (pair i' a' + ?one) s p :&
                       i := i' + ?one + ?one :& a := i ^ 2 * a')))) :&
       let πn₀ = x * k
           πn₁ = πn₀ + x
       in cont πn₀ πn₁ πd)

-- en₀/ed < e < en₁/ed, with both fractions approaching e as k
-- increases:
-- en₀ = (k + 1)^k * k
-- en₁ = (k + 1)^(k + 1)
-- ed = k^(k + 1)
eBound p k cont =
  ex
    (\s x ed ->
       cse 3 (pair x ed) (\y -> isDigit (pair k y + ?one) s p) :&
       al
         (\i a b ->
            cse 3 (pair a b) (\y -> isDigit (pair i y + ?one) s p) ==>
            (i :< ?one :& a := ?one :& b := k) :|
            ex
              (\i' a' b' ->
                 cse 3 (pair a' b') (\y -> isDigit (pair i' y + ?one) s p) ==>
                 i := i' + ?one :& a := (k + ?one) * a' :& b := k * b')) :&
       let en₀ = x * k
           en₁ = en₀ + x
       in cont en₀ en₁ ed)

-- There exist a, b, c ∈ ℕ (not all zero) with a·π/4 + b·e = c or
-- a·π/4 = b·e + c or b·e = a·π/4 + c.
prop :: Prop v
prop =
  withOne $
  ex
    (\a b c ->
       al
         (\p k ->
            k :< ?one :|
            (πBound p k $ \πn₀ πn₁ πd ->
               eBound p k $ \en₀ en₁ ed ->
                 cse 3 (a * πn₀ * ed) $ \x₀ ->
                   cse 3 (a * πn₁ * ed) $ \x₁ ->
                     cse 3 (b * en₀ * πd) $ \y₀ ->
                       cse 3 (b * en₁ * πd) $ \y₁ ->
                         cse 6 (c * πd * ed) $ \z ->
                           (x₀ + y₀ :< z :& x₁ + y₁ :> z) :|
                           (x₀ :< y₁ + z :& x₁ :> y₀ + z) :|
                           (y₀ :< x₁ + z :& y₁ :> x₀ + z))))

main :: IO ()
main = do
  print (scoreProp prop)
  putStrLn (showProp 0 prop allVars "")

```

Try it online!

---
Tags: math, number-theory, atomic-code-golf
---


title: Ethan Finds the Maximum Element

text:
# Question
Title: Ethan Finds the Maximum Element
This is a problem that the Hacker Cup team made for the 2018 Facebook Hacker Cup, but we ended up not using it (though Ethan struggles through  variety of other challenges). Normally code size isn't a factor in the Hacker Cup, but we thought this would make for an interesting code golf challenge. We look forward to seeing how a different sort of competitive programmer tackles this problem!

---

Ethan has been given quite the challenging programming assignment in school: given a list of \\$N\ (1 \le N \le 50)\\$ distinct integers \\$A\_{1..N}\ (1 \le A\_i \le 100)\\$, he must find the largest one!

Ethan has implemented an algorithm to solve this problem, described by the following pseudocode:

1. Set \\$m\\$ to be equal to \\$A\_1\\$.
2. Iterate \\$i\\$ upwards from 2 to \\$N\\$ (inclusive), and for each \\$i\\$, if \\$A\_i \> A\_{i-1}\\$, set \\$m\\$ to be equal to \\$A\_i\\$.
3. Output \\$m\\$.

Sometimes this algorithm will output the correct maximum value, but other times it sadly won't.

As Ethan's teaching assistant, you have some say in what input data his solution will be evaluated on. The professor has given you a list of \\$N\\$ distinct integers \\$A\_{1..N}\\$ to work with, but you may shuffle them into any permutation you'd like before feeding them into Ethan's program. This is your opportunity to show some mercy!

For how many different permutations of \\$A\_{1..N}\\$ would Ethan's algorithm produce the correct output?

## Input Format:

Line 1: 1 integer, \\$N\\$
Line 2: \\$N\\$ space-separated integers, \\$A\_{1..N}\\$

## Output Format:

1 integer, the number of permutations of \\$A\\$ for which Ethan's algorithm would produce the correct output.

### Sample Input 1:

```
1
100

```

### Sample Output 1:

```
1

```

### Explanation:

Only one permutation of \\$\[100\]\\$ exists, and Ethan's program would correctly output 100 for it.

### Sample Input 2:

```
3
16 82 43

```

### Sample Output 2:

```
5

```

### Explanation:

Ethan's program would correctly output 82 for 5 of the 6 possible permutations of \\$\[16, 82, 43\]\\$. However, when \\$A = \[82, 16, 43\]\\$, it would incorrectly output 43 instead.

### Sample Input 3:

```
10
26 81 40 5 65 19 87 27 54 15

```

### Sample Output 3:

```
986410

```

## Rules

This is , so shortest answer (in bytes) wins!

# Answer
> 21 votes
# APL (Dyalog Unicode), ~~5~~ 3 bytes

```
⍳⊥×

```

Try it online!

Adám gave me an inspiration to golf this further.

### How it works

```
⍳⊥×  Monadic train. Input: n, the length of array A.
  ×  v: Signum, which always gives 1 because n ≥ 1
⍳    B: An array of 0..n-1
 ⊥   Scalar-expand v to get V, a length-n vector of ones,
       then mixed base conversion of V in base B

```

---

# APL (Dyalog Unicode), 5 bytes

```
⍳⊥⍴∘1

```

Try it online!

*Edited to remove modulo 107*

Uses HyperNeutrino's formula, but optimized through the use of  (mixed base conversion) directly. Uses `⎕IO←0`.

### How the code works

```
⍳⊥⍴∘1  Monadic train. Input: n, the length of array A.
  ⍴∘1  V: An array of 1's of length n
⍳      B: An array of 0..n-1
 ⊥     Mixed base conversion of V in base B

```

### How the  works

```
base:  0         1         2         .. n-3         n-2 n-1
digit: 1         1         1         .. 1           1   1
value: 1×..(n-1) 2×..(n-1) 3×..(n-1) .. (n-2)×(n-1) n-1 1
sum of all digit values is the answer.

```

# Answer
> 19 votes
# Jelly, 6 bytes

```
RU×\S:

```

Try it online!

Let's analyze under which scenarios this algorithm works.

If the maximum element is at the end of the list, this obviously works, since \\$A\_N\>A\_{N-1}\\$ and it is processed last. This gives \\$(N-1)!\\$ possibilities.

If the maximum element is at the second last position, then this obviously works, since \\$A\_N\A\_{N-2}\\$ and is processed last. This gives \\$(N-1)!\\$ possibilities. There is no overlap between this case and the above because the numbers are guaranteed unique.

If the maximum element is at the third last position, then it depends on the last two elements. If the last element is larger than the second last element, it is treated as the maximum, which fails. There are \\$(N-1)!\\$ cases, and we can match them by identical first \\$(N-3)\\$ elements with one case going \\$\cdots,max,A,B\\$ and the other going \\$\cdots,max,B,A\\$. Exactly one of these is valid and not the other, so there are \\$\frac{(N-1)!}{2}\\$ cases.

In general, if the maximum element has \\$k\\$ elements after it, then the rest of the list must be strictly descending. There is exactly one case for each set of last \\$k\\$ elements out of the \\$k!\\$ permutations.

Thus, the answer is \\$\frac{(N-1)!}{0!}+\frac{(N-1)!}{1!}+\cdots+\frac{(N-1)!}{(N-1)!}\\$. This is OEIS A000522.

This is equal to \\$\frac{\frac{N!}{0!}+\frac{N!}{1!}+\cdots+\frac{N!}{(N-1)!}}{N}\\$, which is \\$\frac{(N\times(N-1)\times(N-2)\times\cdots\times 1+N\times(N-1)\times(N-2)\times\cdots\times 2+\cdots+N}{N}\\$, which is the sum of the cumulative product of the list \\$\[N,N-1,\cdots,2,1\]\\$, divided by N.

```
RU×\S:
R       [1, 2, ..., N]
 U      reversed
   \    cumulative
  ×     product
    S   sum
     :  divided by (N)

```

Having MathJax is really nice :D

Note that the list literally does not matter. All we need to know is N.

# Answer
> 6 votes
# Retina, 44 bytes

```
K`;
"$+"+`(.*);(.*)
$.(_$1*);$.(_$1*$2*
.*;

```

Try it online! Explanation:

```
K`;

```

Replace `N` with a counter and output (these should be decimal 0, but the empty string works here).

```
"$+"+`

```

Repeat `N` times...

```
(.*);(.*)
$.(_$1*);$.(_$1*$2*

```

... multiply the output by the counter and increment both.

```
.*;

```

Delete the loop counter.

Previous 47 bytes including modulo 107:

```
K`;
"$+"{`(i*);(j*)
i$1;j$.1*$2
)`(\w{107})*

j

```

Try it online! Explanation:

```
K`;

```

Replace `N` with a counter and output (both initially 0).

```
"$+"{`
)`

```

Repeat `N` times...

```
(i*);(j*)
i$1;j$.1*$2

```

... multiply the output by the counter and increment both...

```
(\w{107})*

```

... and reduce modulo 107.

```
j

```

Convert the output to decimal.

# Answer
> 3 votes
# JavaScript (ES6),  ~~19~~  18 bytes

*A shorter version suggested by @Neil*
*Saved 1 byte thanks to @Jitse*

```
f=n=>n&&--n*f(n)+1

```

Try it online!

Implements the following formula from A000522:

$$\cases{a\_0=1\\ a\_{n}=n\cdot a\_{n-1} + 1,&n\>0}$$

Turned into:

$$\cases{a\_0=0\\ a\_{n}=(n-1)\cdot a\_{n-1} + 1,&n\>0}$$

---

# JavaScript (ES6), 35 bytes

This is a port of @HyperNeutrino's answer.

Takes only \\$n\\$ as input, as per this consensus.

```
n=>(g=n=>n&&(p*=n)+g(n-1))(n,p=1)/n

```

Try it online!

# Answer
> 3 votes
# 05AB1E, ~~8~~ ~~5~~ 4 bytes

-1 byte thanks to @KevinCruijssen

Implementation of @Neil's algorithm.

```
GNP>

```

Explanation:

```
G    for loop from 1 to input
 N   push current iteration
  P  multiply the stack; in the first iteration there's only 1 element (1)
   > increment

```

Try it online!

# Answer
> 1 votes
# APL (Dyalog Unicode), 12 bytes

```
×\∘⌽∘⍳∘≢+.÷≢

```

Try it online!

-4 bytes thanks to the change in specifications;

-3 bytes thanks to @Adám

Train that implements @HyperNeutrino's formula, so go upvote their answer.

# Answer
> 1 votes
# C (gcc), ~~69~~ ~~62~~ 60 bytes

Following the consensus in C;

Updated to the most golfed solution thanks to contributions from Arnauld and FryAmTheEggman.

mod 107 has been removed from the rules, I was being too tricky. Thanks for the edit Arnauld.

```
c,o,d,e;f(n){for(e=n;n--;c+=o)for(d=e,o=1;d>n;)o*=d--;c/=e;}

```

Try it online!

# Answer
> 1 votes
# Japt `-x`, 6 bytes

```
ÆÉ /Xl

```

Try it

# Answer
> 1 votes
# , 28 bytes

```
n=scan();sum(cumprod(n:1))/n

```

Try it online!

R port of @HyperNeutrino’s algorithm.

# Answer
> 1 votes
# Python 3, 28 bytes

```
f=lambda n:n and~-n*f(n-1)+1

```

Try it online!

Python port of Neil's algorithm.

# Answer
> 0 votes
# Ruby, 24 bytes

```
f=->n{n<1?1:f[n-=1]*n+1}

```

Try it online!

Using the formula from OEIS A000522

---
Tags: code-golf, permutations
---


title: Letters associated with prime numbers

text:
# Question
Title: Letters associated with prime numbers
If we assign each letter a respective integer, starting from 1, then a is 1, b is 2, c is 3, and so on. After z, the letters loop back around, but with a in front (aa, ab, ac). It then goes to ba, bb, bc... After this is completed, as you may have figured, another letter is added (aaa, aab, aac). "Prime letters" would be letters that are associated with a prime number. b would be the first prime letter, followed by c, e, g, et cetera.

# The Challenge

Given an input *n*, find the nth "prime letter."

**Examples**

Input:

```
1

```

Output:

```
b

```

Input:

```
4

```

Output:

```
g

```

Input:

```
123

```

Output:

```
za

```

# Scoring Criteria

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

# Answer
# Python 3,~~262~~ ~~236~~ ~~209~~ ~~196~~ ~~179~~ ~~114~~ ~~93~~ ~~92~~ 97 bytes

```
def f(n):
 m=k=1;s=''
 while n:m*=k*k;k+=1;n-=m%k
 while k:s=chr(~-k%26+97)+s;k=~-k//26
 return s

```

Try it online!

Fixed a bug mentioned by @benrg about getting a wrong output for the input 123.

Thanks to:
\- @AdmBorkBork for help me getting started and save a few bytes
\- @Sriotchilism O'Zaic for saving me 6 bytes
\- @mypetlion for saving me 65 bytes and bringing me under 150 bytes :)
\- @dingledooper for saving me 21 bytes and bringing me under 100 bytes :D
\- @Jitse for saving 1 byte

---

**98 bytes**

```
f=lambda n,i=1,p=1:n and-~f(n-p%i,i+1,p*i*i)
g=lambda n,s='':n and g(~-n//26,chr(~-n%26+97)+s)or s

```

Try it online!
> 8 votes

# Answer
# Jelly, 8 bytes

```
ÆNḃ26ịØa

```

A monadic Link which accepts a non-negative integer that yields a list of characters.

**Try it online!**

### How?

```
ÆNḃ26ịØa - Link: integer, n
ÆN       - nth prime
   26    - literal 26
  ḃ      - bijective base
      Øa - literal list of characters = ['a', 'b', ..., 'z']
     ị   - index into

```
> 4 votes

# Answer
# JavaScript (Node.js), 83 bytes

```
f=(n,k=0)=>n?f(n-(g=d=>~k%d--?g(d):!d)(++k),k):k<0?'':f(n,k/26-1)+Buffer([k%26+65])

```

Try it online!

### Commented

```
f = (                // f is a recursive function taking:
  n,                 //   n = input
  k = 0              //   k = counter
) =>                 //
  n ?                // if n is not equal to 0:
                     //   == 1st pass: find the requested prime ==
    f(               //   do a recursive call:
      n - (          //     pass the updated value of n
        g = d =>     //     g is a recursive function which takes d = k
                     //     and tests the primality of k + 1:
          ~k % d-- ? //       if d is not a divisor of (k + 1):
                     //       (decrement d afterwards)
            g(d)     //         do recursive calls until it is
          :          //       else:
            !d       //         return true if d = 0
      )(++k),        //     increment k and invoke g
                     //     so we decrement n if k is prime
      k              //     pass k
    )                //   end of recursive call
  :                  // else:
                     //   == 2nd pass: convert the prime to a string ==
    k < 0 ?          //   if k is negative:
      ''             //     return an empty string and stop
    :                //   else:
      f(             //     do a recursive call:
        n,           //       pass n (which is now 0)
        k / 26 - 1   //       pass k / 26 - 1
      ) +            //     end of recursive call
      Buffer([       //     append the letter corresponding to
        k % 26 + 65  //     k mod 26
      ])             //

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), 53 bytes

```
Flatten[Tuples[Alphabet[],#]&/@Range@4,1][[Prime@#]]&

```

Try it online!
> 4 votes

# Answer
# Ruby `-rprime`, ~~48~~ ~~47~~ ~~46~~ 43 bytes

-5 bytes from GB.

```
->n{(?A..?Z*n).take(Prime.take(n)[-1])[-1]}

```

Try it online!
> 3 votes

# Answer
# PHP, 69 bytes

```
for($n=1,$a=a;$argn||!print$a;$m||--$argn,$a++)for($m=$n++;$n%$m--;);

```

Try it online!
> 2 votes

# Answer
# Java (JDK), ~~170~~ ~~163~~ ~~158~~ ~~157~~ 155 bytes

```
String p(int n){int c=0,i,v=1;String s="";while(c<n){v++;for(i=2;i<=v;i++)if(v%i<1)break;if(i==v)c++;}while(v>0){s=(char)(~-v%26+97)+s;v=~-v/26;}return s;}

```

Try it online!

Thanks to @Delta for saving me 14 bytes in total
> 2 votes

# Answer
# 05AB1E, 18 bytes

```
<Ø[₂‰˜0KZ27‹#}<Asè

```

Isn't there a convenient builtin to do this shorter?.. I have the feeling I should be able to use one of the base-conversion builtins here, but it isn't really working out.. Can without a doubt be golfed substantially, though..

Try it online or verify some more test cases.

**Explanation:**

```
<              # Decrease the (implicit) input-integer by 1 to make it 0-based
 Ø             # Get the 0-based n'th prime
  [            # Start an infinite loop:
   ₂‰          #  Take the divmod 26
     ˜         #  Flatten the resulting list
      0K       #  And remove any 0s
        Z      #  Get the maximum of the list (without popping)
         27‹   #  If it's smaller than 27:
            #  #   Stop the infinite loop
  }<           # After the loop: decrease all values by 1 to make it 0-based
    A          # Push the lowercase alphabet
     sè        # And index the list of integers into it
               # (after which the resulting character-list is output implicitly as result)

```
> 1 votes

# Answer
# Java, 169 Bytes

isProbablePrime is only valid for 32 bit integers, but it is correct for every 32 bit integer, so this is a valid solution.

```
(int n)->{int x=-1;for(int i=0;i<n;){x++;if(BigInteger.valueOf(x).isProbablePrime(15))i++;}String r="";while(x>0){x--;int m=x%26;r=(char)(m+97)+r;x=(x-m)/26;}return r;};

```
> 1 votes

# Answer
# Icon, 135 bytes

```
procedure f(n)
k:=seq()&s:=0&0=k%(i:=2to k)&s+:=1&i=k&s=1&p:=k-1&n-:=1&n=0
t:="";until t[1:1]:=char(97+p%26)&p:=p/26-1&p<0;return t
end

```

Try it online!
> 0 votes

# Answer
# Pyth, 27 bytes

`VQ.VhZIP_b=ZbB;p*\a/Z26@GtZ`

Explaination:

```
                            # Implicit Q = eval(input())
                            # Implicit Z = 0
VQ                          # for N in range(Q)
  .VhZ                      #     for b in infinite_range(Z+1)
      IP_b                  #         if is_prime(b)
          =Zb               #             Z = b
             B;             #             break
             p*\a/Z26       # print("a"*Z//26, end="")
                     @GtZ   #
                            # Implicit print(G[Z-1])

```
> 0 votes

---
Tags: code-golf, primes
---


title: Time to settle this: Java vs C++

text:
# Question
Title: Time to settle this: Java vs C++
## Story

In an unnamed company, some people use Java and some use C++. This was always a nuisance, and they kept on arguing which single language they should all be using. To settle the dispute, the management decided that they'll buy a translator program that will be able to rewrite their C++ programs to Java and vice versa. An important part of the translator will be a routine that will rewrite all the identifiers. This is because Java coders in the company write multiword identifiers in a different way than C++ coders in the company do. We will now describe both methods. In Java a multiword identifier is constructed in the following manner: the first word is written starting with a lowercase letter, and the following ones are written starting with an uppercase letter, no separators are used. All other letters are lowercase. Examples of Java identifiers are `javaIdentifier`, `longAndMnemonicIdentifier`, `name` and `kSP`.In C++ people use only lowercase letters in their identifiers. To separate words they use the underscore character '\_'. Examples of C++ identifiers are `cpp_identifier`, `long_and_mnemonic_identifier`, `name` (here Java and C++ people agree), and `k_s_p`.

## Task

Write the identifier translation routine/function/etc. Given an identifier, detect whether it is a Java identifier or C++ identifier (as defined below) and translate it to the other dialect. Translation must preserve the order of words and must only change the case of letters and/or add/remove underscores. You may assume all input to be valid, as checking was done for you in the superroutine.

## More formally

A Java identifier only contains characters from \[a-zA-Z\] and starts with a lowercase letter. Every uppercase character is a word boundary.

A C++ identifier only contains characters from \[a-z\_\] and additionally doesn't start or end with an underscore nor does it contain two adjacent underscores anywhere within. Every underscore is a word boundary.

Translation: switch every word boundary, that is, if it was an underscore, remove it and capitalize the following letter, if it was uppercase, prepend an underscore and lowercase the letter.

## Input

The input consists of one line that contains an identifier. It consists of letters of the English alphabet and underscores. Other standard input styles are also valid.

## Output

If the input identifier is a Java identifier, output/return its C++ version. If it is a C++ identifier, output/return its Java version. You may assume it will be at least one of those (both is possible).

## Examples

```
long_boring_identifier  |  longBoringIdentifier
otherWay                |  other_way
same                    |  same
getHTTP                 |  get_h_t_t_p
invalid_Input           |  <undefined>

```

All the standard rules apply, none of the standard loopholes are allowed.

# Answer
> 4 votes
# QuadR, 19 bytes

```
_(.)
[A-Z]
\u1
_\l&

```

Try it online!

# Answer
> 3 votes
# Node.js, 61 bytes

Contains the unprintable character `\x7F`.

```
s=>s.replace(/_.|[A-Z]/g,s=>Buffer(s[1]||''+s).map(x=>x^32))

```

Try it online!

---

# JavaScript (ES6), 72 bytes

```
s=>s.replace(/_.|[A-Z]/g,s=>s[1]?s[1].toUpperCase():'_'+s.toLowerCase())

```

Try it online!

# Answer
> 2 votes
# Retina, ~~40~~ 34 bytes

```
([A-Z])
_$1
T`Ll`lL`_.
_([A-Z])
$1

```

Try it online!

### Explanation

```
([A-Z])            # Replace all uppercase letters with
_$1                # an underscore followed by that same letter.
T`Ll`lL`_.         # Replace lowercase letters with uppercase letters and vice versa when after an underscore
_([A-Z])           # Replace an underscore followed by an uppercase letter
$1                 # with just that letter

```

# Answer
> 2 votes
# Python 3.8, 95 bytes

First golf in a while. Comments welcome.

```
lambda s:"".join(["_"*(x!=(l:=x.lower()))+l,x.upper()][p=="_"]*(x!="_")for p,x in zip("."+s,s))

```

# Answer
> 1 votes
# Zsh `-oextendedglob`, ~~82 69~~ 51 bytes

```
<<<${1//(#m)(_?|[A-Z])/${${MATCH[2]:u}:-_$MATCH:l}}

```

~~Try it online! Try it online!~~  Try it online!

Even if the flags count toward byte count, adding 14 bytes for `-oextendedglob` still undercuts the 82 byte program!

```
<<<${1//(#m)(_?|[A-Z])/${${MATCH[2]:u}:-_$MATCH:l}}
   ${1//              /                           }  # replacement
        (#m)                                         # enable $MATCH parameter
            (_?|[A_Z])                               # "?" matches any character
                         ${MATCH[2]:u}               # substitute 2nd char, uppercased
                       ${             :-_$MATCH:l}   # if empty, substitute "_" and lowercased match
<<<                                                  # print to stdout

```

---
Tags: code-golf, string
---


title: Tips for golfing in F#

text:
# Question
Title: Tips for golfing in F#
What general tips do you have for golfing in F#? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to F# (e.g. "remove comments" is not an answer). Please post one tip per answer.

# Answer
Need to provide a type annotation for a variable so that you can call a method on it? Just compare it against a literal of the type you want it to be then throw away the result:

```
let f (x:string)=x.Length
let f x=x="";x.Length

```
> 10 votes

# Answer
Use `function` instead of `match` when possible; it'll save 6 characters for 1-character variable names:

```
let f=function // ... (14 chars)

```

vs

```
let f x=match x with // ... (20 chars)

```

It can also replace any pattern match to consistently save 1 character:

```
match a with|          // ... (13 chars)
a|>function|           // ... (12 chars)
(function| (* ... *))a // (12 chars)

```
> 9 votes

# Answer
Use the prefix notation for infix operators when you can - it'll save you from having to define a function to use them.

For example, you can turn this:

```
List.map(fun i->i+2)[1;1;2;3;5;8]

```

into this:

```
List.map((+)2)[1;1;2;3;5;8]

```
> 8 votes

# Answer
# Tuple deconstruction

In case you can't get around to using variables, use tuple deconstruction instead of multiple let expressions

```
let a,b ="",[]

```

instead of

```
let a=""
let b=[]

```

# Reading from stdin

F# core library defines an alias for `System.Console.In` called `stdin`. These allow you to read input.

```
// Signature:
stdin<'T> :  TextReader

```

TextReader on msdn

The big advantage aside the fact that it's shorter than `Console` is, you don't have to open System either

# Iterating over string

string is basically a `char seq`, this allows you to use `Seq.map` directly with strings. It's also possible to use them in comprehensions `[for c in "" do]`

# Mutables/Reference cells

Using reference cells is not always shorter as every read operation comes with an additional character to deref the cell.

# General tips

* It is possible to write the complete `match .. with` inline

```
function|'a'->()|'b'->()|_->()

```
* There is no need for white-space before and after non alphanumeric characters.

```
String.replicate 42" "
if Seq.exists((<>)'@')s then
if(Seq.exists((<>)'@')s)then

```
* In case you need to left or right pad a string with spaces, you can use \[s\]printf\[n\] flags for that.

```
> sprintf "%20s" "Hello, World!";;
val it : string = "       Hello, World!"

```

Core.Printf Module
> 6 votes

# Answer
# Use id instead of x-\>x

id is an operator standing for the identity function.

```
let u x=x|>Seq.countBy (fun x->x)

```

can be written

```
let u x=x|>Seq.countBy id

```

source

I use it here
> 4 votes

# Answer
# Eta-conversion for functions

Many thanks to Laikoni for this tip in one of my solutions.

Consider a function to, say, sum a string with 3 for upper-case letters and 1 for all other characters. So:

```
let counter input = Seq.sumBy (fun x -> if Char.IsUpper x then 3 else 1) input

```

By eta-conversion this can be re-written as:

```
let counter = Seq.sumBy (fun x -> if Char.IsUpper x then 3 else 1)

```

and called in the same way as before:

```
counter "Hello world!" |> printfn "%i"

```

# The function forward-composition operator `>>`

Now suppose our original challenge would be to sum a string with 3 for upper-case letters and 1 for lower-case letters, and all other characters are excluded.

We might write this as:

```
let counter input = Seq.filter Char.IsLetter input |> Seq.sumBy (fun x -> if Char.IsUpper x then 3 else 1)

```

We can use the forward-composition operator (`>>`) to chain the two functions (`Seq.filter` and `Seq.sumBy`) together. With eta-conversion the function definition would become:

```
let counter = Seq.filter Char.IsLetter >> Seq.sumBy (fun x -> if Char.IsUpper x then 3 else 1)

```

Chris Smith did a great write-up on the `>>` operator on his MSDN blog.
> 3 votes

# Answer
# Prefer new line string over "\n"

This will start to pay off at even a single new line character in your code. One use case might be:

### (18 bytes)

```
string.Concat"\n"

```

### (17 bytes)

```
string.Concat"
"

```

Inspired from Chiru's answer for es6.

Used here
> 3 votes

# Answer
# Use .NET

.NET offers a lot of nice builtins. F# can use them, so dont forget them!

Example:

```
open System.Linq

```

It can be helpful!
> 2 votes

# Answer
# Avoid parenthesis when using one parameter and on tuple

```
let f = [(0,1);(1,4)]|>Seq.map(fst)
printfn "%A" f

```

can be written

```
let f = [0,1;1,4]|>Seq.map fst
printfn "%A" f

```
> 2 votes

# Answer
When possible `Seq` is shorter than `List`:

```
[[1];[2;3];[4];[5]|>List.collect

```

```
[[1];[2;3];[4];[5]|>Seq.collect

```

is one char shorter...
> 2 votes

# Answer
# Use for...to instead of for...in to walk a range

```
for i in[0..2]
for i=0 to 2

```
> 2 votes

# Answer
The `module` keyword can be used to shorten module names when used repeatedly. For example:

```
Array.fold ...
Seq.iter ...
List.map ...

```

can become

```
module A=Array
A.fold ...
module S=Seq
S.iter ...
module L=List
L.map ...

```

This is more useful for longer programs where module methods are used repeatedly (and must be fully named each time because they have the `RequireQualifiedAccess` modifier), and allows shaving a few chars off especially when it's more useful to use a regular CLR array (e.g., mutability) than an F# `seq` or `list`.
> 2 votes

# Answer
Use lambdas to save a byte. For example, this:

```
let f x=x*x

```

Can be expressed as this:

```
fun x->x*x

```
> 1 votes

---
Tags: code-golf, tips
---


title: Is it a Hamiltonian cycle on a grid?

text:
# Question
Title: Is it a Hamiltonian cycle on a grid?
A Hamiltonian path in a graph is a path that visits each vertex exactly once; a Hamiltonian cycle is a Hamiltonian path that is a cycle – the path forms a simple closed loop. In this challenge the graph will be a `n x n` grid, where n is an even number greater than 2. Here is an example of a Hamiltonian cycle on 12x12 rectangular grid:

```
+---------------+   +-----------------------+
|               |   |                       |
+-----------+   |   +---+   +-----------+   |
            |   |       |   |           |   |
+-------+   |   +---+   |   +-------+   |   |
|       |   |       |   |           |   |   |
|   +---+   |   +---+   |   +-------+   +---+
|   |       |   |       |   |
|   +-------+   +---+   |   +---------------+
|                   |   |                   |
+---+   +-------+   |   |   +-----------+   |
    |   |       |   |   |   |           |   |
+---+   +---+   |   +---+   +---+   +---+   |
|           |   |               |   |       |
+---+   +---+   |   +-----------+   +---+   |
    |   |       |   |                   |   |
+---+   +---+   |   +---+   +-------+   |   |
|           |   |       |   |       |   |   |
+-------+   |   +-------+   +---+   |   |   |
        |   |                   |   |   |   |
+-------+   |   +---------------+   +---+   |
|           |   |                           |
+-----------+   +---------------------------+

```

The path visits each vertex exactly once and forms a simple closed loop that do not intersect or touches itself. The grid points are not shown so that the ASCII graphic is not cluttered. There are three `-` (`---`) between two horizontally connected vertices or 3 spaces if the vertices are not connected. A single `|` connects two vertically adjacent vertices, spaces are used otherwise. Since the grid is not visible, the `+` is used only where the path takes a turn. The path will never be broken - if a segment connects two vertices, it will be `---` and never `- -`.

## Task:

You will be given an ASCII representation of a path and you need to check if it is a Hamiltonian cycle on a grid. Write a full program or a function that solves this problem.

## Input:

ASCII representation of a path. It can be: \- A mutliline string; \- A list of strings \- A list/array of characters or any format that is convenient for you. You can have an optional parameter `n` for the size of the grid. You can use alternatve ASCII representation, just explain it.

## Output:

* A consistent value indicating that the path is a Hamiltonian cycle on a grid
* A consistent value indicating that the path is not a Hamiltonian cycle on a grid. There can be several reasons for this: The path doesn’t visit all vertices; the path crosses/touches itself; there are two or more paths and not a single one. You don’t need to specify the reason – just return/print a consistent falsy value.

## Test cases:

Truthy:

```
Optional `n` = 6

+-----------+   +---+
|           |   |   |
|   +-------+   |   |
|   |           |   |
|   +-----------+   |
|                   |
+---+   +-------+   |
    |   |       |   |
+---+   +---+   |   |
|           |   |   |
+-----------+   +---+

+-------------------+
|                   |
|   +---------------+
|   |
|   |   +-----------+
|   |   |           |
|   |   |   +---+   |
|   |   |   |   |   |
|   +---+   |   |   |
|           |   |   |
+-----------+   +---+

+---+   +-----------+
|   |   |           |
|   |   |   +-------+
|   |   |   |
|   |   |   +-------+
|   |   |           |
|   +---+   +-------+
|           |
|   +---+   +-------+
|   |   |           |
+---+   +-----------+

Optional `n` = 8

+---------------------------+
|                           |
+---+   +-----------+   +---+
    |   |           |   |
+---+   +---+   +---+   +---+
|           |   |           |
|   +---+   |   +---+   +---+
|   |   |   |       |   |
+---+   |   +---+   |   +---+
        |       |   |       |
+---+   +-------+   +---+   |
|   |                   |   |
|   +-------------------+   |
|                           |
+---------------------------+

+-------------------+   +---+
|                   |   |   |
+-------+   +---+   |   |   |
        |   |   |   |   |   |
+---+   |   |   |   +---+   |
|   |   |   |   |           |
|   |   +---+   |   +---+   |
|   |           |   |   |   |
|   +-----------+   |   |   |
|                   |   |   |
+---+   +-----------+   |   |
    |   |               |   |
+---+   +-----------+   |   |
|                   |   |   |
+-------------------+   +---+

+---+   +-------------------+
|   |   |                   |
|   |   +---+   +-----------+
|   |       |   |
|   +---+   |   +-----------+
|       |   |               |
|   +---+   +---+   +---+   |
|   |           |   |   |   |
|   +-----------+   |   |   |
|                   |   |   |
|   +-------+   +---+   |   |
|   |       |   |       |   |
|   |   +---+   +---+   |   |
|   |   |           |   |   |
+---+   +-----------+   +---+

Optional `n` = 12

+---+   +-----------+   +-------------------+
|   |   |           |   |                   |
|   |   +-------+   |   +---+   +-----------+
|   |           |   |       |   |
|   +-------+   |   +-------+   +---+   +---+
|           |   |                   |   |   |
|   +-------+   +---+   +-------+   |   |   |
|   |               |   |       |   |   |   |
|   +---------------+   |   +---+   +---+   |
|                       |   |               |
|   +-------+   +-------+   +-----------+   |
|   |       |   |                       |   |
|   |   +---+   |   +-------------------+   |
|   |   |       |   |                       |
|   |   +-------+   +-----------------------+
|   |
|   +-------------------------------+   +---+
|                                   |   |   |
+-------+   +-------+   +---+   +---+   |   |
        |   |       |   |   |   |       |   |
+-------+   +---+   |   |   |   +-------+   |
|               |   |   |   |               |
+---------------+   +---+   +---------------+

+---+   +---------------------------+   +---+
|   |   |                           |   |   |
|   |   |   +-------+   +-----------+   |   |
|   |   |   |       |   |               |   |
|   |   |   +---+   |   +-------+   +---+   |
|   |   |       |   |           |   |       |
|   |   +---+   |   |   +---+   |   |   +---+
|   |       |   |   |   |   |   |   |   |
|   +-------+   |   +---+   |   +---+   +---+
|               |           |               |
+---+   +---+   |   +---+   +-------+   +---+
    |   |   |   |   |   |           |   |
+---+   |   |   +---+   +---+   +---+   +---+
|       |   |               |   |           |
|   +---+   +---------------+   +---+   +---+
|   |                               |   |
|   +-----------+   +---+   +-------+   +---+
|               |   |   |   |               |
|   +-------+   |   |   |   |   +-------+   |
|   |       |   |   |   |   |   |       |   |
|   |   +---+   |   |   +---+   +---+   |   |
|   |   |       |   |               |   |   |
+---+   +-------+   +---------------+   +---+

+---------------------------+   +---+   +---+
|                           |   |   |   |   |
|   +---------------+   +---+   |   +---+   |
|   |               |   |       |           |
|   |   +---+   +---+   +-------+   +---+   |
|   |   |   |   |                   |   |   |
|   +---+   |   +---------------+   |   |   |
|           |                   |   |   |   |
+-------+   +---+   +-----------+   |   |   |
        |       |   |               |   |   |
+---+   |   +---+   |   +-----------+   |   |
|   |   |   |       |   |               |   |
|   +---+   |   +---+   |   +-----------+   |
|           |   |       |   |               |
|   +-------+   +---+   |   |   +-------+   |
|   |               |   |   |   |       |   |
|   |   +-----------+   |   |   |   +---+   |
|   |   |               |   |   |   |       |
|   |   |   +-------+   |   +---+   +---+   |
|   |   |   |       |   |               |   |
|   |   |   |   +---+   +-------+   +---+   |
|   |   |   |   |               |   |       |
+---+   +---+   +---------------+   +-------+

```

Falsy:

```
Optional `n` = 6

; Two paths
+-------------------+
|                   |
|   +-----------+   |
|   |           |   |
|   +-----------+   |
|                   |
+-------+   +-------+
        |   |
+-------+   +-------+
|                   |
+-------------------+

; Two paths
+-------+   +-------+
|       |   |       |
|   +---+   +-------+
|   |
|   +---------------+
|                   |
|   +-----------+   |
|   |           |   |
|   +---+   +---+   |
|       |   |       |
+-------+   +-------+

; The path doesn't visit each vertex
+-----------+   +---+
|           |   |   |
|           |   |   |
|           |   |   |
+-------+   +---+   |
        |           |
+---+   +---+   +---+
|   |       |   |
|   +-------+   +---+
|                   |
+-------------------+

; The path doesn't visit each vertex and touches itself
; (so visits some points more than once)
+-------------------+
|                   |
|   +-----------+   |
|   |           |   |
|   |   +-------+   |
|   |   |           |
|   |   +-------+   |
|   |           |   |
+---+-----------+   |
    |               |
    +---------------+

; The path doesn't form a loop and touches itself
+---+   +---+   +---+
|   |   |   |   |   |
|   |   |   |   |   |
|   |   |   |   |   |
|   |   |   |   |   |
|   |   |   |   |   |
|   |   |   |   |   |
|   |   |   |   |   |
|   |   |   |   |   |
|   |   |   |   |   |
+---+---+   +---+---+

Optional `n` = 8

; Two paths
+-------------------+   +---+
|                   |   |   |
|   +-----------+   |   |   |
|   |           |   |   |   |
|   +-------+   |   +---+   |
|           |   |           |
+-------+   |   +-----------+
        |   |
+---+   +---+   +-----------+
|   |           |           |
|   |   +---+   |   +-------+
|   |   |   |   |   |
|   +---+   +---+   +-------+
|                           |
+---------------------------+

; The path doesn't visit each vertex
+---------------+   +-------+
|               |   |       |
|   +-------+   +---+       |
|   |       |               |
|   |   +---+   +---+       |
|   |   |       |   |       |
|   |   +-------+   +-------+
|   |
|   |   +-------------------+
|   |   |                   |
|   +---+   +---+   +---+   |
|           |   |   |   |   |
|   +---+   |   |   |   |   |
|   |   |   |   |   |   |   |
+---+   +---+   +---+   +---+

; The path doesn't visit each vertex
+---------------+   +-------+
|               |   |       |
|   +-----------+   +---+   |
|   |                   |   |
|   +---+   +-----------+   |
|       |   |               |
+---+   |   +-------+   +---+
    |   |           |   |
+---+   +-------+   |   |
|               |   |   |
|   +-----------+   |   |
|   |               |   |
|   +---------------+   +---+
|                           |
+---------------------------+

; Two paths
+-----------+   +-----------+
|           |   |           |
|   +---+   |   |   +-------+
|   |   |   |   |   |
|   |   |   |   |   +-------+
|   |   |   |   |           |
+---+   |   |   +-------+   |
        |   |           |   |
+---+   |   +-----------+   |
|   |   |                   |
|   |   |   +-----------+   |
|   |   |   |           |   |
|   +---+   +-----------+   |
|                           |
+---------------------------+

; The path touches itself (so visits some points more than once)
+---+   +-------------------+
|   |   |                   |
|   |   |   +---+   +-------+
|   |   |   |   |   |
|   +---+   |   |   |   +---+
|           |   |   |   |   |
+---+   +---+   |   |   |   |
    |   |       |   |   |   |
+---+   +-------+---+---+   |
|               |   |       |
+-------+   +---+   +---+   |
        |   |           |   |
+-------+   +-----------+   |
|                           |
+---------------------------+

; The path doesn't form a loop
+---------------+   +-------+
|               |           |
+-------+   +   +-------+   |
        |   |           |   |
+-------+   +-----------+   |
|                           |
|   +-------------------+   |
|   |                   |   |
|   +---+   +-----------+   |
|       |   |               |
|   +---+   +-----------+   |
|   |                   |   |
|   +---------------+   |   |
|                   |   |   |
+-------------------+   +---+

```

## Wining criteria:

The shortest solution in bytes in each language wins. I'll highly appreciate if you add explanation of the code and the algorithm you used.

# Answer
# Charcoal, ~~63~~ ~~55~~ 46 bytes

```
ＡＭ↗ Ｗ⁼№ＫＶ#¹«✳⊗⁻¹⌕ＫＶ#¦ ¿¬∨﹪ⅈ⁴﹪ⅉ²⊞υω»¿‹ＬυＸＮ²⎚«⎚¹

```

Try it online! Link is to verbose version of code. Edit: Saved 8 bytes by using a more cumbersome but still acceptable input format. Saved 9 bytes by requiring the path only uses `#`s. Explanation:

Copy the path to the canvas.

```
Ｍ↗

```

Print a space one square in from the bottom-left corner (the print command left the cursor one square below the bottom-left corner). This should break the loop of `#`s into a line.

```
Ｗ⁼№ＫＶ#¹«

```

Try to follow the line to its end, following the path of `#`s that used to have two neighbours.

```
✳⊗⁻¹⌕ＫＶ#¦

```

Overwrite the line as we go.

```
¿¬∨﹪ⅈ⁴﹪ⅉ²⊞υω»

```

Keep track of how many vertices we meet along the way.

```
 ¿‹ＬυＸＮ²⎚

```

Check whether we managed to visit every vertex. If not, then just clear the canvas.

```
«⎚¹

```

If we visited every vertex then output `1` as a truthy value (which actually prints as `-`).
> 5 votes

# Answer
# Jelly, 34 bytes

```
Ø1©ȧn⁶µŒṪạ®SỊƊƇḢ©Wḟ@ƲƬṖṪ<3Ȧȧm2m€4Ȧ

```

A monadic Link accepting a list of lists of characters (the lines) which yields `1` for a Hamiltonian or `0` otherwise. Uses the layout in the question (any non-space chars as path parts will work).

**Try it online!** Or see the test-suite.

### How?

Starts at the top-left, `[1,1]`, and finds a neighbouring non-space until no neighbours can be found, then checks if the final position is the neighbour below the top-left, `[2,1]`, (to confirm the path was a loop) and that no other non-spaces remain (to confirm there were not multiple paths). If so a final check is made that all the vertices were non-spaces too.

```
Ø1©ȧn⁶µŒṪạ®SỊƊƇḢ©Wḟ@ƲƬṖṪ<3Ȧȧm2m€4Ȧ - Link: list of lines, M
Ø1                                 - literal [1,1]
  ©                                - (copy this to the register and yield it)
   ȧ                               - logical AND (with M) -> M
     ⁶                             - literal space character
    n                              - not equal? (vectorises)
      µ                            - new monadic chain, call that N
       ŒṪ                          - truthy multidimensional indices
                     Ƭ             - collect up while distinct, applying:
                    Ʋ              -   last four links as a monad:
              Ƈ                    -     filter keep if (find neighbours):
             Ɗ                     -       last three links as a monad:
         ạ                         -         absolute difference (vectorises):
          ®                        -           current register value
           S                       -         sum
            Ị                      -         insignificant? (abs(z)<=1)
               Ḣ                   -     head (a neighbour [x,y] or 0 if none)
                ©                  -     (copy this to the register and yield it)
                 W                 -     wrap in a list
                   @               -     with swapped arguments:
                  ḟ                -       filter discard
                      Ṗ            - remove rightmost
                       Ṫ           - get rightmost (or 0 if none)
                        <3         - less than three? (vectorises)
                          Ȧ        - all non-zero when flattened?
                           ȧ       - logical AND (with N) ->
                                   - (i.e. N if the entire path looped from [1,1]
                                   -  back to [2,1] leaving nothing unconsumed
                                   -  else 0)
                            m2     - every 2nd value
                              m€4  - every 4th value of each
                                 Ȧ - all non-zero when flattened?

```
> 5 votes

# Answer
# JavaScript (ES7),  ~~126 124~~  122 bytes

Takes input as `(n)(matrix)`. Returns a Boolean value.

```
n=>g=(m,X=k=0,Y=0,d=0)=>m.map((r,y)=>r.map((c,x)=>++c|(x-X)**2+(y-Y)**2-1||g(m,x,r[++d,x%4|y%2||k++,x]=y)))|d>1?k=g:k==n*n

```

Try it online!

### How?

Starting at \\$(0,0)\\$, we flood-fill the path and increment a counter \\$k\\$ each time we go through a cell \\$(x,y)\\$ such that \\$x\equiv 0\pmod 4\\$ and \\$y\equiv 0\pmod 2\\$.

At the end of the process, we must have \\$k=n^2\\$.

We additionally make sure that no cell has more than 2 neighbors. If it does happen, we set \\$k\\$ to a non-numeric value to force the final test to fail.
> 4 votes

# Answer
# Jelly, 54 bytes

```
n⁶,Z$µØ0jm2N,¹ƇɗƝ)m2)Z×LƊ€2¦Ẏ€;"/µØ-ḟN}Ḣɗ,+¥ƭƒịṪ¥¥ƬL=L

```

Try it online!

A monadic link which takes a list of strings as input and returns a boolean. The strings use the format of the question but omitting every other character (so half the width). Full explanation to follow.
> 3 votes

# Answer
# , 125 bytes

```
p=.((,-)#:1 2)|.!.0]
f=.([:(''-:2 0~.@-.~[:,]*+/@p)' '~:])*1-1 e.[:([:,@(,]+1=(2|#\)*/4|#\@|:)([:>./]*"2 p)^:_)_(<0 0)}' '~:]

```

Try it online!

Just a first draft, but all test cases are passing. Will attempt to golf and add explanation this week.
> 2 votes

---
Tags: code-golf, decision-problem, grid
---