title: Is my Matrix Arrowhead?

text:
# Question
Title: Is my Matrix Arrowhead?
## Definition

An arrowhead matrix is a matrix that has all entries equal to **0**, except the ones on the main diagonal, top row and leftmost column. In other words, the matrix should look like this:

```
* * * * * *
* * 0 0 0 0
* 0 * 0 0 0
* 0 0 * 0 0
* 0 0 0 * 0
* 0 0 0 0 *

```

Where each *** is any non-zero entry.

## Task

Given a square matrix of non-negative integers, check whether it is arrowhead according to the definition above.

You may *not* take the size of the matrix as input, unless your language’s equivalent to an array is something like a pointer and a length (like C). It will always be at least 3 x 3.

The shortest code in bytes in each language wins.

## Input and Output

You can pick among any of the following formats for receiving input:

* A matrix in the native matrix type (if your language has one)
* A 2D array1 (an array of 1D arrays, each corresponding to one row)
* A 1D array (since the matrix is always square)
* A string (you chose the spacing, but please do not abuse this in any way).

When it comes to providing output, you can either report a truthy / falsy value following the standard decision-problem definition, or choose any two distinct and consistent values.

Moreover, you can take input and give output through any standard method, in any programming language, while taking note that these loopholes are forbidden by default. If want to pick any other format or are unsure about something, please ask in the comments.

1: or your language's equivalent (list, vector, etc.)

## Examples

Let's look at the following examples:

```
1 2 2 2
2 1 0 0
3 0 1 0
4 0 0 1

```

This is an arrowhead matrix (your programs should report a truthy value), because the elements on the main diagonal are `1 1 1 1`, those on the top row are `1 2 2 2` and those on the leftmost column are `1 2 3 4`. All other entries are **0**, so this satisfies all the conditions.

```
3 5 6
7 1 0
8 0 0

```

This matrix is *not* arrowhead because there is a **0** on the main diagonal.

```
9 9 9 9
9 9 0 0
9 7 9 0
9 0 0 9

```

This one is *not* arrowhead either, because it contains a **7** in place of a **0**.

## More test cases

Truthy:

```
[[1, 1, 1], [1, 1, 0], [1, 0, 1]]
[[1, 2, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]
[[1, 2, 2, 2], [2, 1, 0, 0], [3, 0, 1, 0], [4, 0, 0, 1]]
[[34, 11, 35, 5], [56, 567, 0, 0], [58, 0, 679, 0], [40, 0, 0, 7]]

```

Falsy:

```
[[3, 5, 6], [7, 1, 0], [8, 0, 0]]
[[9, 9, 9, 9], [9, 9, 0, 0], [9, 7, 9, 0], [9, 0, 0, 9]]
[[1, 0, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]
[[1, 6, 3, 4], [13, 2, 0, 6], [29, 0, 1, 0], [2, 0, 0, 4]]

```

# Answer
> 15 votes
# Javascript (ES6), ~~48~~ 47 bytes

*Saved 1 byte thanks to edc65*

```
m=>m.some((r,y)=>r.some((c,x)=>(x*y&&x!=y)^!c))

```

Returns `false` for arrowhead matrices and `true` for non-arrowhead matrices (allowed since any two distinct values can be used to represent true and false)

## Test cases:

```
f=m=>m.some((r,y)=>r.some((c,x)=>(x*y&&x!=y)^!c))
console.log(f([[1, 1, 1], [1, 1, 0], [1, 0, 1]]))
console.log(f([[1, 2, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]))
console.log(f([[1, 2, 2, 2], [2, 1, 0, 0], [3, 0, 1, 0], [4, 0, 0, 1]]))
console.log(f([[34, 11, 35, 5], [56, 567, 0, 0], [58, 0, 679, 0], [40, 0, 0, 7]]))
console.log(f([[3, 5, 6], [7, 1, 0], [8, 0, 0]]))
console.log(f([[9, 9, 9, 9], [9, 9, 0, 0], [9, 7, 9, 0], [9, 0, 0, 9]]))
console.log(f([[1, 0, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]))
console.log(f([[1, 6, 3, 4], [13, 2, 0, 6], [29, 0, 1, 0], [2, 0, 0, 4]]))
```

# Answer
> 12 votes
# , ~~21~~ ~~20~~ ~~19~~ ~~17~~ 15 bytes

### -4 bytes thanks to @GalenIvanov.

```
*-:1,1,.=&/:@}.

```

Takes input as a matrix (rank 2 array).

Try it online!

# Explanation

Let the edit history be a lesson to you not to golf and write an explanation at the same time.

```
* -: 1, 1,. = & /: @ }.  Let m be the input matrix.
            = & /: @ }.  Identity matrix 1 smaller than m.
                     }.    Behead (m without its first row).
                   @       Composed with.
                /:         Grade up (get len(m) - 1 unique elements)
              &            Composed with.
            =              Self-classify (compare equality with
                           unique elements)
        1,.              Prepend a column of 1s
     1,                  Prepend a row of 1s
*                        Signum (0 becomes 0, n > 0 becomes 1)
  -:                     Does it match the generated arrowhead matrix?

```

### Visual explanation

Note that this is done on the REPL (inputs are given starting with three spaces and output are given without any leading spaces). Because of that, I sometimes omit composition functions like `@` and `&` since things on the REPL are evaluated right-to-left (functions are more complex).

Suppose you have the following sample matrix:

```
   ] m =. 4 4 $ 1 2 3 4 1 1 0 0 1 0 1 0 1 0 0 1
1 2 3 4
1 1 0 0
1 0 1 0
1 0 0 1

```

First, I'd like to explain (and give a shoutout to) @GalenIvanov's very clever way of generating the identity matrix, which is the following `=&/:@}.`.

First, we behead the input matrix (`}.`).

```
   }. m
1 1 0 0
1 0 1 0
1 0 0 1

```

Then we get the indices each row would be in were the rows sorted using `/:`-grade up.

```
   /: }. m
2 1 0

```

Note that the resulting indices are *unique*: the list has no duplicate elements (and why would it? There's no way to place two elements in the same position in an array).

Finally, we use the niche but helpful `=`-self-classify. This monad compares each unique element to all of the other elements in an array. Remember how I mentioned it was important that the resulting indicies are unique? Since `=`-self-classify does the comparisons in the order that the unique elements appear in the list, the resulting output will be the identity matrix for a unique input (this is why `=@i.` is how you can make an identity matrix of a given length).

```
   = /: }. m
1 0 0
0 1 0
0 0 1
   NB. This is what is happening
   (2 = 2 1 0) , (1 = 2 1 0) ,: (0 = 2 1 0)
1 0 0
0 1 0
0 0 1

```

Once we have the identity matrix, it's a matter of adding a row of ones and a column of ones, which is done very simply (if given an atom - i.e. a single element - the `,` family will repeat it to fill when it's being added):

```
   1,. (=&/:@}. m)
1 1 0 0
1 0 1 0
1 0 0 1
   1, (1,. =&/:@}. m)
1 1 1 1
1 1 0 0
1 0 1 0
1 0 0 1

```

Then we simply compare the generated arrowhead matrix to the signum of the input matrix.

```
   * m
1 1 1 1
1 1 0 0
1 0 1 0
1 0 0 1
   (* m) -: (1, 1,. =&/:@}. m)
1

```

# Answer
> 9 votes
# APL (Dyalog Classic), ~~19~~ ~~16~~ ~~15~~ 13 bytes

-1 byte thanks to @ErikTheOutgolfer

(`⎕IO←0`)

```
×≡(∧=⌊)/¨∘⍳∘⍴

```

Try it online!

-2 bytes thanks to @ngn and @H.PWiz

## How?

(2D input matrix **S**)

* `×≡` Check whether **S** is positive only on ...
* `(∧=⌊` ... the diagonals or the top row and left column ...
* `)/¨∘⍳∘⍴` ... of **S**.

# Answer
> 9 votes
# Wolfram Language (Mathematica), 47 bytes

```
Clip@#==Array[If[1<#!=#2>1,0,1]&,{1,1}Tr[1^#]]&

```

Try it online!

Explanation: `Clip@#` replaces all the non-zero numbers in the matrix with 1s, then we compare this to an array with dimensions `{1,1}Tr[1^#]` = `{Length@#, Length@#}` with 0 in position `i,j` when `1 < i != j > 1`, and 1 otherwise.

(Roughly based on Uriel's answer.)

Here's another idea that's 16 bytes longer — feel free to steal it if you can golf it down:

```
Union@@Array[{1,#}~Tuples~2&,Length@#]==Most@Keys@ArrayRules@#&

```

Try it online!

# Answer
> 7 votes
# APL (Dyalog), ~~21~~ ~~18~~ 17 bytes

```
×≡1⍪1,(=/¨∘⍳1-⍨⍴)

```

Try it online!

**How?**

This one goes the other way -

`=/¨∘⍳` \- creates the identity matrix

`1-⍨⍴` \- for `n - 1`

`1⍪1,` \- prepends a column and a row of 1s

\- compares with

`×` \- the original matrix, after it has gone an element-wise signum-ing

# Answer
> 7 votes
# PowerShell, ~~112~~ 108 bytes

```
param($a)$o=+!(0-in$a[0]);1..($x=$a.count-1)|%{$i=$_;0..$x|%{$o*=(!($y=$a[$i][$_]),$y)[!$_-or$_-eq$i]}};!!$o

```

Try it online!

Takes input and manipulates as an array-of-arrays, since PowerShell doesn't support matrices (outside of the .NET Direct3D transform matrices support, which is something entirely different).

The whole algorithm is based on the fact that non-zero numbers are truthy and zero is falsey in PowerShell, and using multiplication to determine those truthy/falsey values.

We first take the first row, `$a[0]`, and check whether `0` is `-in` that array, store that into our `$o`utput variable. If anything in that row is zero, then the `$o` is also zero, otherwise it's one, done by a quick cast-to-int with `+`.

Next we loop from `1` up to `$a.count-1`, setting `$x` along the way -- we're going to be looping through each row one at a time.

Each iteration we set helper variable `$i` to keep track of what row we're on, then loop from `0` to `$x` to iterate each element in this row. Inside the inner loop, we're again multiplying `$o`, this time by selecting from a tuple setup as a pseudo-ternary operator.

The tuple's conditional, `!$_-or$_-eq$i`, says "when we're on the 0th column, or the column matches the row (i.e., the main diagonal)" to select the second half of the tuple when truthy or the first half when falsey. The tuple is composed of `!($y=$a[$i][$_]), $y`. The first half sets `$y` for golfing the second half, but either way we're selecting the current element. The first half does Boolean negation on it, while the second half just takes the element as-is. Thus, if we're not on the 0th column nor the main diagonal, we ensure that the element is zero by taking the Boolean-not of it. Similarly, we ensure the 0th column or main diagonal is non-zero by simply taking it.

So now that we've iterated through every element in the matrix, `$o` is either going to be `0` if some element was incorrect, or some non-zero integer if it is an arrowhead matrix. We double-Boolean-not that to get either `False` or `True` respectively, to make our output consistent, and that's left on the pipeline where printing is implicit.

# Answer
> 7 votes
# Jelly, ~~14~~ 12 bytes

```
ŒDµḢ;Ḣ€Ȧ>FẸ$

```

-2 bytes from Pietu1998

Try it online!

**Explanation**

```
[[9,7,1],
 [7,1,0],
 [7,0,1]]

```

Use the above matrix as an example input.

```
ŒDµḢ;Ḣ€Ȧ>FẸ$
ŒD              Diagonals → [[9, 1, 1], [7, 0], [1], [7], [7, 0]]
  µ             New monadic link
   Ḣ            Head → [9, 1, 1]. Alters diagonals list.
    ;Ḣ€         Append with the head of each of the other diagonals → [9, 1, 1, 7, 1, 7, 7]
       Ȧ        Logical all → 1
         FẸ$    Flatten what's left in diagonals then take logical any → [[0],[],[],[0]] → [0,0] → 0
        >       Matrix is an arrowhead iff result of Ȧ > result of Ẹ

```

# Answer
> 6 votes
# MATL, 15 bytes

```
gtZyXy,!llY(]X=

```

Input is a matrix (using `;` as row separator). Output is `1` for arrowhead, `0` otherwise.

Try it online! Or verify all test cases.

### Explanation

```
g        % Implicit input. Convert to logical values (nonzero becomes true and
         % zero becomes false)
t        % Duplicate
Zy       % Size
Xy       % Identity matrix of that size
,        % Do twice
  !      %   Transpose
  ll     %   Push 1 twice
  Y(     %   Write 1 at all entries of row 1
]        % End
X=       % Are the two matrices (input and constructed) equal? Implicit display

```

# Answer
> 5 votes
# , ~~78~~ ~~70~~ ~~69~~ ~~68~~ ~~54~~ 53 bytes

```
function(m){d=diag(nrow(m))
d[1,]=d[,1]=1
all(d!=!m)}

```

Try it online!

Porting Luis Mendo's answer is much shorter than my former approach.

Thanks to rturnbull for pointing out a bug, and golfing down a byte!

### old answer, 68 bytes:

```
function(m,i=which(!m,T))all(i[,1]-i[,2],i!=1,sum(m>0)==3*nrow(m)-2)

```

Try it online!

duckmayr's answer tests that all entries on the main diagonal and first row/column (`m[i]`) are nonzero and the rest (`m[-i]`) are zero, using some nice arithmetic to get the diagonal and the first row.

This answer, however, tests to make sure that (1) zero entries are not on the main diagonal or the first row/column, and (2) that there are, given an `n x n` matrix, `3*n-2` nonzero entries.

`which` returns the indices where its input is `TRUE`, and with the optional `arr.ind=T`, returns an array of indices for each array dimension, in this case, two.

Hence when `any(i[,1]==i[,2])`, there exists a zero on the diagonal, and when `any(i==1)`, there exists a zero in the first row or the first column.

Finally, a little arithmetic shows that the number of nonzero entries must be `3*n-2`, `n` from the first column, `n-1` from the diagonal, and `n-1` from the first row.

# Answer
> 5 votes
# Python 2, 75 bytes

```
lambda m,E=enumerate:all((x[j]>0)-(i>0<j!=i)for i,x in E(m)for j,y in E(m))

```

**Try it online!**

# Python 2, 85 bytes

Taking the array as a 1D matrix:

```
def f(m):s=len(m)**.5;print all((v<1)^(0in(p>s,p%s,p//s-p%s))for p,v in enumerate(m))

```

**Try it online!**

# Answer
> 5 votes
# C (gcc), ~~80~~ ~~75~~ 69 bytes

```
i;f(A,n)int*A;{for(i=0;i<n*n;)n*=A[i]<1^(i<n|i%n<1|i/n==i++%n);n=!n;}

```

Try it online!

Saved 5 bytes thanks to scottinet! And 6 more thanks to ceilingcat!

Reused the test code from this answer.

Linearly scans the array for any incorrect values, returning 0 for an arrowhead matrix and 1 otherwise. We check by computing the exclusive or of whether the item at a given position is zero and whether that position is on the arrow.

Encoding the information of the 2D array into one dimension leads to a fairly simple set of conditions. If we let `i` be our 0-based index into the `n` dimensional array, then `i<n` describes the first row. Similarly, `i%n==0` describes the first column and `i/n==i%n` describes the diagonal.

The best trick I found for handling the return is to set the dimension to zero when encountering an error. This causes the loop to terminate immediately, then returning the logical negation of the dimension will give us one of two distinct values. scottinet found the way to make GCC return it more nicely.

# Answer
> 3 votes
# Python 2, ~~92~~ 90 bytes

```
def f(m):l=len(m);return all((m[a%l][a/l]<1)^any([a<l,a%l<1,a/l==a%l])for a in range(l*l))

```

Try it online!

# Credits

# Answer
> 3 votes
# Haskell, 62 bytes

*-3 bytes thanks to Mr. Xcoder. -13 bytes thanks to user28667. -5 bytes thanks to Zgarb.*

```
z=zip[0..]
f m=and[(i==j||i*j<1)==(a>0)|(i,r)<-z m,(j,a)<-z r]

```

Try it online!

# Answer
> 3 votes
# Jelly, 10 bytes

```
ŒDµḢṠQṭT€E

```

Try it online!

# Answer
> 3 votes
# Python 3, ~~72~~ 71 bytes

```
lambda x,e=enumerate:any(0**n^(0<i!=j>0)for i,r in e(x)for j,n in e(r))

```

*Thanks to @xnor for golfing off 1 byte!*

Try it online!

# Answer
> 2 votes
# APL+WIN, ~~36~~ 33 bytes

```
(↑⍴m)=+/(+⌿m)=+/m←×m×n∘.×n←⍳↑⍴m←⎕

```

Prompts for screen input of an APL 2d matrix.

# Answer
> 2 votes
# Clojure, ~~212~~ ~~206~~ 188 bytes

-6 bytes by removing some missed spaces, and shortcutting `range`. I might have to let this sit so I can think of a better way.

-18 bytes thanks to @NikoNyrh, and creating shortcuts for `map`.

```
(fn[m](let[r range a map z zero?](and(every? #(not(z %))(concat(m 0)(rest(a #(% 0)m))(a get m(r))))(every? z(apply concat(into(a #(take(dec %)%2)(r)(a rest m))(a take-last(r)(reverse(rest m)))))))))

```

Awful, just awful. I don't know why I can't wrap my head around a reasonable solution.

Takes a nested vector as input.

```
(defn arrowhead? [matrix]
  (let [; Get the 0th cell of the 0th row, then the 1st cell of the 1st row...
        main-diagonal (map get matrix (range))

        ; Get the 0th cell of each row
        first-col (rest (map #(% 0) matrix))
        arrowhead (concat (matrix 0) first-col main-diagonal)

        ;
        right-rest (map take-last (range) (reverse (rest matrix)))
        left-rest (map #(take (dec %) %2) (range) (map rest matrix))
        rest-matrix (apply concat (into left-rest right-rest))]

    ; And check them
    (and (every? pos? %) arrowhead
         (every? zero? rest-matrix))))

```

---

I tried rewriting this from scratch using a different method, and it ended up longer. Instead of manually carving out the "rest" sections of the matrix, I instead decided to try generating all the coordinates in the matrix, generating the coordinates of the arrowhead, then use `clojure.set/difference` to get the non-arrowhead cells. Unfortunately, the call to that built-in is costly:

# 223 bytes

```
(fn[m](let[l(range(count m))g #(get-in m(reverse %))e every? a(for[y l x l][x y])k #(map % l)r(concat(k #(do[% %]))(k #(do[0%]))(k #(do[% 0])))](and(e #(zero?(g %))(clojure.set/difference(set a)(set r)))(e #(pos?(g %)))r)))

(defn arrowhead? [matrix]
  (let [length-range (range (count matrix))
        get-cell #(get-in matrix (reverse %))
        all-coords (for [y length-range
                         x length-range]
                     [x y])

        k #(map % length-range)

        diag (k #(do[% %]))
        top-side (k #(do [0 %]))
        left-side (k #(do [% 0]))
        arrowhead (concat diag top-side left-side)

                   ; 22 bytes! Ouch
        rest-cells (clojure.set/difference (set all-coords) (set arrowhead))]

    (and (every? #(zero? (get-cell %)) rest-cells)
         (every? #(pos? (get-cell %)) arrowhead))))

```

# Answer
> 2 votes
# Pyth, ~~22~~ 21 bytes

This is definitely not the language for matrix manipulation.

```
.As.e+!MWk.Db,0k,@bkh

```

For each row `b` and its index `k` in the matrix (`.e`), grabs the first and `k`th entries (left side and diagonal) with `,@bkh` and (`+`) all the other entries with `.Db,0k`. If `k` isn't 0 to correspond to the first row (`Wk`), then `!`not `M` all of those entries. Once all of those have been selected, make sure all of them are true. (`.As`) If there's a 0 where there shouldn't be, then the corresponding location will be grabbed as is and mess up the and, and if there's a nonzero where there shouldn't be, it'll be `!` notted to 0, which is also false.

Test suite.

-1 bytes for swapping the orders around.

# Answer
> 2 votes
# Pip, ~~31~~ ~~23~~ 22 bytes

```
{0<_!=B>0MC#a==0=_MMa}

```

This is a function that takes a 2D nested list of numbers. Try it online!

### Explanation

A whole lot of comparisons going on here. The first thing to know is that comparison operators in Pip can be chained together, like in Python: `5>4>3` is `5>4 and 4>3` (true), not `(5>4)>3` (false). The second is that this doesn't apply to `==`, the "exactly equals" operator. Another difference: regular comparisons have higher precedence than the mapping operators `MC` and `MM` and can be used in lambda expressions, while `==` has lower precedence and can't.

```
{                    }  Define a function with argument a:
 0<_!=B>0MC#a            Generate a matrix (as nested lists) that has 0 on the first row,
                          first column, and main diagonal, and 1 elsewhere (see below for
                          details)
               0=_MMa    Map the function 0=_ to the elements of the elements of a,
                          generating a matrix that is 0 where a is nonzero and vice versa
             ==          Test if the two matrices are equal, returning 0 or 1 accordingly

```

To generate the first matrix, we use `MC`, "map-coords." This operator takes a number, generates a square coordinate grid of that size, and maps a function to each (x,y) coordinate pair, returning a list of lists of the results. For example, `{a+b} MC 3` would give the result `[[0; 1; 2]; [1; 2; 3]; [2; 3; 4]]`.

Here, the size of the grid is `#a`, the size of our original argument. The function is `0<_!=B>0`, which is a shorter way of writing `{0 < a != b > 0}`:

```
{        }  Function; a and b are the arguments (in our case, row and column)
 0<a        Return 1 (truthy) if a is greater than 0
    !=b     and a is not equal to b
       >0   and b is greater than 0

```

This returns 0 for the first row/column and the main diagonal, and 1 elsewhere.

# Answer
> 2 votes
# Husk, ~~12 11~~ 10 bytes

```
≡¹´Ṫ§^*=ŀL

```

Try it online!

## Explanation

```
≡¹´Ṫ§^*=ŀL  Input is a k×k array A.
         L  The length, k.
        ŀ   The range [0,1..k-1].
  ´Ṫ        Outer product with itself by this function:
             Arguments are two numbers x and y.
       =     Equality of x and y
    §^       to the power of
      *      x times y.
≡¹          Does the result have the same shape and distribution of truthy values as A?

```

The idea is that Husk defines 0 to the power of 0 as 1, so the outer product has 1s on the first row and column. Also, 1 to the power of any number is 1, so the outer product has 1s on the diagonal. Other entries are 0 to the power of some positive number, which is 0. This gives a binary arrowhead matrix, which we compare to the input with .

# Answer
> 2 votes
## Clojure, ~~128~~ ~~95~~ ~~92~~ 85 bytes

```
#(every? neg?(for[R[(range(count %))]i R j R]((if((set[i(- i j)j])0)- dec)((% i)j))))

```

It is always exciting to see two consecutive opening brackets.

Original version:

```
#(and(apply =(map assoc(for[i(rest %)](subvec i 1))(range)(repeat 0)))(every? pos?(concat(map nth %(range))(% 0)(map first %))))

```

The first part works by `assoc`ing diagonal elements of the sub-matrix to zero, and checking that all rows are equal :) I used a similar trick at Jacobian method.

Latter part `concat`enates the diagonal + first row and column and checks that they are positive.

# Answer
> 2 votes
# Javascript (ES6), 58 bytes

My solution for Javascript:

```
m=>m.some((r,i)=>m[0][i]*r[0]*r[i]==0|r.filter(c=>i*c)[2])

```

Not as clever as Herman's answer, but I just felt like I should post it here too.

```
isArrowHead=m=>m.some((r,i)=>m[0][i]*r[0]*r[i]==0|r.filter(c=>i*c)[2])

console.log("-----should be false-----")

console.log(isArrowHead([[1, 1, 1], [1, 1, 0], [1, 0, 1]]))
console.log(isArrowHead([[1, 2, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]))
console.log(isArrowHead([[1, 2, 2, 2], [2, 1, 0, 0], [3, 0, 1, 0], [4, 0, 0, 1]]))
console.log(isArrowHead([[34, 11, 35, 5], [56, 567, 0, 0], [58, 0, 679, 0], [40, 0, 0, 7]]))

console.log("-----should be true-----")

console.log(isArrowHead([[3, 5, 6], [7, 1, 0], [8, 0, 0]]))
console.log(isArrowHead([[9, 9, 9, 9], [9, 9, 0, 0], [9, 7, 9, 0], [9, 0, 0, 9]]))
console.log(isArrowHead([[1, 0, 3, 4], [1, 1, 0, 0], [1, 0, 1, 0], [1, 0, 0, 1]]))
console.log(isArrowHead([[1, 6, 3, 4], [13, 2, 0, 6], [29, 0, 1, 0], [2, 0, 0, 4]]))

console.log("-----end-----")
```

# Answer
> 2 votes
# Stax, 11 bytesCP437

```
ä¢⌠┐xⁿtH↔BU

```

Try it online!

Unpacked version with 13 bytes:

```
B|AsF:10i^\=*

```

Finally tied Husk and beaten by Jelly by just one byte ...

## Explanation

```
B                Push tail (all except 1st row) of the input array, then push the head (1st row)
 |A              All elements in the head are truthy
                 This will be used as an accumulator
   sF            For each element in the tail, execute the rest of the program
     :1          All truthy indices
       0i^\      Expected truthy indices (0 and the current row number)
           =     The truthy indices are as expected
            *    Perform logical "and" with the accumulator
                 Implicit output of the final accumulator

```

# Answer
> 1 votes
# , ~~81~~ 79 bytes

```
function(x){n=nrow(x);i=c(seq(1,n^2,n+1),1:n,seq(1,n^2,n));all(x[i]>0,x[-i]<1)}

```

-2 bytes thanks to Mr. Xcoder

Try it online!

# Answer
> 1 votes
# PowerShell, 186 bytes

```
$a=$($args);if($a[0]-contains0){0;exit};0..($a.Length-1)|%{if($a[$_][0]-eq0-or$a[$_][$_]-eq0){0;exit};$r=$a[$_];$d=$_;if($_-ne0){1..($r.Length-1)|%{if($r[$_]-ne0-and$_-ne$d){0;exit}}}};1

```

Try it online!

# Answer
> 1 votes
# C, 117 bytes

```
i,j,r;f(A,n)int*A;{for(i=r=0;i<n;++i)for(j=-1;++j<n;(!i||!j||i==j)&&!A[i*n+j]&&++r)i*j&&i-j&&A[i*n+j]&&++r;return!r;}

```

Try it online!

# Answer
> 1 votes
# Perl 5, 136 + 2 (`-ap`) = 138 bytes

```
push@a,[@F]}{push@b,"@{$a[0]}"=~/\b0\b/;map{//;map$a[$'][$_]=!$a[$'][$_],0,$';shift@{$a[$']};push@b,@{$a[$']}}1..$#a;say!("@b"=~y/ 0//c)

```

Try it online!

# Answer
> 1 votes
# Clean, 79 bytes

```
import StdEnv
?[h:m]=prod h>0&&and[u>0&&n!!x>0&&sum n==n!!x\\[u:n]<-m&x<-[0..]]

```

Try it online!

# Answer
> 1 votes
# Japt, 16 bytes

```
Ëe@!X^!(E*Y*nE
e

```

Test it online!

Man, this takes me back to the good old days when Japt was regularly much longer than other golfing langs...

# Answer
> 1 votes
# K (oK), ~~27~~ 30 bytes

**Solution:**

```
x~a*x|a:a|+(a:1,(#1_x)#0)|=#x:

```

Try it online!

**Explanation:**

I must be doing something dumb as the APL solutions are less than half the byte count...

24 bytes spent creating the arrowhead. `or` together the following three matrices:

```
/ assume 4x4 matrix
=#x
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

+(a:1,(#1_x)#0)
1 0 0 0
1 0 0 0
1 0 0 0
1 0 0 0

a
1 1 1 1
0 0 0 0
0 0 0 0
0 0 0 0

```

Full breakdown:

```
x~a*x|a:a|+(a:1,(#1_x)#0)|=#x: / the solution
                            x: / save input as x
                           #   / count length
                          =    / identity matrix
                         |     / or with
           (            )      / do this together
                      #0       / take from 0
                ( 1_x)         / drop first of x
                 #             / count
              1,               / prepend 1
            a:                 / save as a
          +                    / flip rows/cols
         |                     / or with
        a                      / a
      a:                       / save as a
     |                         / or with
    x                          / x
  a*                           / multiply by arrowhead
x~                             / matches input?

```

# Answer
> 1 votes
# 05AB1E, ~~42~~ ~~29~~ ~~28~~ 27 bytes

```
vyNèP}IнPIøнPPĀiI¦€¦D€às€OQ

```

Can most definitely without any doubt be golfed quite a bit.. I've only just started with 05AB1E; matrices aren't my strong suit; nor are they 05AB1E's strong suit.. All and all not a great combination..

Try it online or verify all test cases.

**Explanation:**

```
vyNè }       # Take the diagonal of the input-matrix
    P        # and calculate its product
             #  i.e. [[1,2,3,4],[5,6,0,0],[7,0,8,0],[9,0,0,10]] → [1,6,8,10] → 480
Iн           # Take the first row
  P          # and take its product as well
             #  i.e. [[1,2,3,4],[5,6,0,0],[7,0,8,0],[9,0,0,10]] → [1,2,3,4] → 24
Iøн          # Take the first column
   P         # and take its product as well
             #  i.e. [[1,2,3,4],[5,6,0,0],[7,0,8,0],[9,0,0,10]] → [1,5,7,9] → 315
      P      # Take the product of all three results,
             #  i.e. [480, 24, 315] → 3628800
       Āi    # If this result is larger than 0
             # (which means the diagonal, first row, and first column contain no zeros)
             #   i.e. 3628800 > 0 → 1
I¦           #  Take the input and remove the first row
             #   i.e. [[1,2,3,4],[5,6,0,0],[7,0,8,0],[9,0,0,10]]
             #          → [[5,6,0,0],[7,0,8,0],[9,0,0,10]]
  €¦         #  And also remove the first item of each row
             #   i.e. [[5,6,0,0],[7,0,8,0],[9,0,0,10]] → [[6,0,0],[0,8,0],[0,0,10]]
    D        #  Duplicate that
     €à      #  Take the max of each
             #   i.e. [[6,0,0],[0,8,0],[0,0,10]] → [6,8,10]
     s€O     #  As well as the sum of each
             #   i.e. [[6,0,0],[0,8,0],[0,0,10]] → [6,8,10]
        Q    #  And check if all maximums and sums are equal
             #  (this means each column and row only contains two numbers (row/column
             #  and diagonal); everything else is a zero)

```

# Answer
> 1 votes
# 05AB1E, 23 bytes

```
ćsøćsε¾èˆ)¼}˜OŠ¯)ćs˜ĀP‹

```

Try it online!

This was initially a comment on Kevin's answer, but they told me I should post it separately, and so I did. I should be able to shave off a couple of bytes shortly.

# Answer
> 1 votes
# , 52 bytes

```
function(m)all(rbind(1,cbind(1,diag(nrow(m)-1)))-!m)

```

Try it online!

One-liner doing the same as the other R solution by Giuseppe for the same byte count. Giuseppe managed to save one byte before I even posted this!

# Answer
> 0 votes
# JavaScript ES6, ~~97~~ ~~85~~ 82 bytes

```
x=>x.map((_,i)=>p(0,i)+p(i,0)+p(i,i),p=(i,j)=>x[i][j]=+!x[i][j])&&!/[1-9]/.test(x)

```

```
F =
x=>x.map((_,i)=>p(0,i)+p(i,0)+p(i,i),p=(i,j)=>x[i][j]=+!x[i][j])&&!/[1-9]/.test(x)

console.log(F([[1,2,3,4,5,6],[9,5,0,0,0,0],[4,0,3,0,0,0],[4,0,0,3,0,0],[4,0,0,0,3,0],[4,0,0,0,0,3]]))

console.log(F([[1,2,3,4,5,6],[9,5,0,0,0,0],[4,0,3,0,0,0],[4,0,7,3,0,0],[4,0,0,0,3,0],[4,0,0,0,0,3]]))

console.log(F([[1,2,0,4,5,6],[9,5,0,0,0,0],[4,0,3,0,0,0],[4,0,0,3,0,0],[4,0,0,0,3,0],[4,0,0,0,0,3]]))
```

# Answer
> 0 votes
# C# (.NET Core), 73 + 18 = 91 bytes

```
using System.Linq;
a=>a.SelectMany((b,i)=>b.Select((n,j)=>i<1||j<1||i==j?n>0:n<1)).All(v=>v)

```

Try it online!

The input is an array of integer-arrays (`int[][]`) the output is `bool`.

Ungolfed full program:

```
using System.Linq;
class Program
{
    static void Main(string[] args)
    {
        System.Func<int[][], bool> f =
        a => a.SelectMany(                          //Iterates through all elements of the outer array, applies the following function and flattens the result
            (b, i) =>                               //b is the inner array, i is it's index
                b.Select(                           //Iterates through all elements of the current array (b) and applies the following function
                    (n, j) =>                       //n is the integer, j is it's index in the inner array (b)
                        i < 1 || j < 1 || i == j ?  //If the current element is in the first row, first column or the diagonal
                        n > 0 :                     //Check if the element is not 0
                        n < 1))                     //else check if the element is 0
            .All(v => v);                           //Check if the value of all elements of the flattened result is true, the result is returned implicitly

        //Truthy test cases
        System.Console.WriteLine(f(new int[][] { new[] { 1, 1, 1 }, new[] { 1, 1, 0 }, new[] { 1, 0, 1 } }));
        System.Console.WriteLine(f(new int[][] { new[] { 1, 2, 3, 4 }, new[] { 1, 1, 0, 0 }, new[] { 1, 0, 1, 0 }, new[] { 1, 0, 0, 1 } }));
        System.Console.WriteLine(f(new int[][] { new[] { 1, 2, 2, 2 }, new[] { 2, 1, 0, 0 }, new[] { 3, 0, 1, 0 }, new[] { 4, 0, 0, 1 } }));
        System.Console.WriteLine(f(new int[][] { new[] { 34, 11, 35, 5 }, new[] { 56, 567, 0, 0 }, new[] { 58, 0, 679, 0 }, new[] { 40, 0, 0, 7 } }));

        //Falsey test cases
        System.Console.WriteLine(f(new int[][] { new[] { 3, 5, 6 }, new[] { 7, 1, 0 }, new[] { 8, 0, 0 } }));
        System.Console.WriteLine(f(new int[][] { new[] { 9, 9, 9, 9 }, new[] { 9, 9, 0, 0 }, new[] { 9, 7, 9, 0 }, new[] { 9, 0, 0, 9 } }));
        System.Console.WriteLine(f(new int[][] { new[] { 1, 0, 3, 4 }, new[] { 1, 1, 0, 0 }, new[] { 1, 0, 1, 0 }, new[] { 1, 0, 0, 1 } }));
        System.Console.WriteLine(f(new int[][] { new[] { 1, 6, 3, 4 }, new[] { 13, 2, 0, 6 }, new[] { 29, 0, 1, 0 }, new[] { 2, 0, 0, 4 } }));
    }
}

```

# Answer
> 0 votes
# PHP, 80 bytes

```
foreach($_GET[a]as$i=>$r)foreach($r as$k=>$v)($i&&$k&&$i!=$k)==$v&&$b=1;echo!$b;

```

# Answer
> 0 votes
# APL NARS, 48 bytes, 24 chars

```
{(×⍵)≡1⍪1,(⍳∘.=⍳)¯1+↑⍴⍵}

```

test:

```
   y←{(×⍵)≡1⍪1,(⍳∘.=⍳)¯1+↑⍴⍵}
   a1 a2 a3
 1 2 2 2   3 5 6   9 9 9 9
 2 1 0 0   7 1 0   9 9 0 0
 3 0 1 0   8 0 0   9 7 9 0
 4 0 0 1           9 0 0 9
   y¨a1 a2 a3
1 0 0

```

# Answer
> 0 votes
# Java 8, 95 bytes

A lambda from `int[][]` to `int` (0 is false, 1 is true).

```
m->{int i=0,d=m.length,r,c,f=1;while(i<d*d)f=m[r=i/d][c=i++%d]<1==(r*c*(r-c)!=0)?f:0;return f;}

```

Try It Online

## Ungolfed

```
m -> {
    int
        i = 0,
        d = m.length,
        r, c,
        f = 1
    ;
    while (i < d * d)
        f =
            m[r = i/d][c = i++%d] < 1
                == (r * c * (r-c) != 0) ?
                    f
                    : 0
        ;
    return f;
}

```

# Answer
> 0 votes
# Ruby, 65 bytes

```
->a{(r=0...a.size).all?{|i|r.all?{|j|(a[i][j]>0)^(i!=j&&i*j>0)}}}

```

Try it online!

# Answer
> 0 votes
# Attache, 33 bytes

```
{DrawMatrix["\\<:^>",#_]==Clip!_}

```

Try it online!

`DrawMatrix` takes a string and a matrix size and "draws" it. In this case, we generate a base arrowhead matrix, like so:

```
\<:^>
\      draw a line from the top left to the bottom right
 <:    move to the left
   ^   draw a line up to the top
    >  draw a line right to the left

```

Then, we check for equality with the input matrix, replacing nonzeroes with `1`.

---
Tags: code-golf, array, decision-problem, matrix
---


title: Hexagonal maze time!

text:
# Question
Title: Hexagonal maze time!
Time for another maze challenge, but not as you know it.

The rules for this challenge are a little different than most maze challenges. The tile types are defined as follows:

* `S`: The location on the maze you start at
* `E`: The location you are trying to get to
* `0`: Wall that you can't cross
* `+`: Floor that you can cross

You can travel in one of six directions: up-left, up-right, left, right, down-left, or down-right.

```
\ /
-S-
/ \

```

The maze does not wrap. The goal is to find the shortest path string to get from `S` to `E`.

### Input:

Input is space separated lines like the mazes shown. No trailing space will follow a line.

### Output:

A string of `R`, `L`, and `F` where

* `R` rotates you right (clockwise) 60 degrees
* `L` rotates you left (counter clockwise) 60 degrees
* `F` moves you one space in the direction you are pointing

You start pointing `left-up`

***The shortest path is counted by the length of the string produced, not the number of positions visited. Your program must print the shortest path as the solution.***

If the maze is unsolvable you should output *`Invalid maze!`*.

(`>>>` is the output)

```
     0 0 0 0
    0 + 0 + 0
   0 0 0 + + 0
  0 + 0 + 0 + 0
 0 0 + + 0 0 + 0
0 0 + 0 + 0 0 + 0
 E 0 + 0 0 + + 0
  + + 0 + 0 + 0
   0 0 0 0 0 +
    + 0 + + +
     0 S 0 0

>>>RFRFFLFLFRFFLFFFLFLFFRFLFLFRFRFRF

  + 0 0 0 0 0 0
 0 0 0 0 0 + + 0
0 0 E 0 + 0 0 + 0
 0 0 0 0 0 0 0 +
  0 + 0 0 + + +
   0 0 + + 0 0
    S + 0 0 0

>>>Invalid maze!

0 E S

>>>LF

 E + 0
0 + + +
 0 0 S
  + +

>>>FFLF

  E
 0 +
0 + +
 0 +
  S

>>>RFFLFF

 0 E + 0 0
0 + 0 0 + +
 + 0 + + + 0
  + 0 + 0 + 0
   + + + 0 S

>>>FFLFLFFRFRFFRFF

 E 0 + + 0
0 + 0 + + 0
 + + + 0 + 0
  + 0 0 0 0 0
   + + + + 0
    + 0 S 0

>>>FLFFRFFRFLF

```

(Note that some of the mazes have other solutions that are the same length but are not listed here)

# Answer
> 19 votes
# Python 2, 291 bytes

```
def f(M):
 Y=map(max,M).index("S");X=M[Y].find("S");V={()};Q=[(0,0,0,1,"")]
 while Q:
    try:x,y,u,v,p=s=Q.pop(0);c=(Y>=y<=X-2*x)*ord(M[Y-y][X-2*x-y])
    except:c=0
    if c==69:return p
    if{c%2*s[:4]}-V:V|={s[:4]};Q+=(x+u,y+v,u,v,p+"F"),(x,y,-v,u+v,p+"R"),(x,y,u+v,-u,p+"L")
 return"Invalid maze!"

```

A function, `f`, taking the maze as a list of rows, and returning a solution, if one exists.

## Explanation

Performs a breadth-first search on the graph of position/direction pairs to find the shortest path from `S` to `E`.

What's interesting is finding a compact way to represent positions and directions on a hexagonal grid, that admits simple "stepping" (i.e., moving in a certain direction) and rotation. It's tempting to use complex numbers here, to represent coordinates on a "real" hexagonal grid, but this is not a very good idea for a number of reasons, the most serious of which is the fact that we need to plug in a √3 somewhere to make it work (sin 60° = √3/2), which, when using floating-point numbers, is a no go if we need absolute precision (e.g., for keeping track of the states we've already visited;) you can try firing up your JavaScript console and typing `Math.sqrt(3)*Math.sqrt(3) == 3` and see for yourself.

But, we can use a little trick! Instead of using complex numbers, let's define *hexagonal numbers* in a similar vein, as a pair of real numbers *a* \+ *bh*, where *h* plays a similar role to the imaginary *i* when dealing with complex numbers. Just like with complex numbers, we can associate the pair (*a*, *b*) with a point on the plane, where the real axis points right, the imaginary axis points 60° up, and they both intersect the unit regular hexagon when the real and the imaginary parts equal 1, respectively. Mapping this coordinate system to the cells of the maze is trivial.

Unlike *i*, the constant *h* is defined by the relation *h*2 = *h* \- 1 (solving for *h* might reveal some insights.) And that's it! Hexagonal numbers can be added and multiplied, using the above relation, much like complex numbers: (*a* \+ *bh*) + (*c* \+ *dh*) = (*a* \+ *c*) + (*b* \+ *d*)*h*,
and (*a* \+ *bh*) · (*c* \+ *dh*) = (*ac* \- *bd*) + (*ad* \+ *bc* \+ *bd*)*h*. These operations have the same geometric interpretation as their complex counterparts: addition is vector addition, and multiplication is scaling and rotation. In particular, to rotate a hexgonal number 60° counter-clockwise, we multiply it by *h*:
(*a* \+ *bh*) · *h* = -*b* \+ (*a* \+ *b*)*h*, and to rotate the same number 60° clockwise, we divide by *h*:
(*a* \+ *bh*) / *h* = (*a* \+ *bh*) · (1 - *h*) = (a + b) - *ah*. For example, we can take the unit hexagonal number pointing right, 1 = (1, 0), a full circle, going counter-clockwise, by multiplying it by *h* six times:
(1, 0) · *h* = (0, 1); (0, 1) · *h* = (-1, 1); (-1, 1) · *h* = (-1, 0); (-1, 0) · *h* = (0, -1); (0, -1) · *h* = (1, -1);
(1, -1) · *h* = (1, 0).

The program uses hexagonal numbers in this fashion to represent the current position in the maze and the current direction, to advance in the specified direction, and to rotate the direction to the left and to the right.

# Answer
> 38 votes
# Hexagony, 2437 bytes

The long-awaited program is here:

```
(.=$>({{{({}}{\>6'%={}{?4=$/./\_><./,{}}{<$<\?{&P'_("'"#<".>........_..\></</(\.|/<>}{0/'$.}_.....><>)<.$)).><$./$\))'"<$_.)><.>%'2{/_.>(/)|_>}{{}./..>#/|}.'/$|\})'%.<>{=\$_.\<$))<>(|\4?<.{.%.|/</{=....$/<>/...'..._.>'"'_/<}....({{>%'))}/.><.$./{}{\>$\|$(<><$?..\\<.}_>=<._..\(/.//..\}\.)))))<...2/|$\){}/{..><>).../_$..$_>{0#{{((((/|#.}><..>.<_.\(//$>))<(/.\.\})'"#4?#\_=_-..=.>(<...(..>(/\")<((.\=}}}\>{}{?<,|{>/...(...>($>{)<.>{=P&/(>//(_.)\}=#=\4#|)__.>"'()'\.'..".(\&P'&</'&\$_></}{)<\<0|\<.}.\"\.(.(.(/(\..{.>}=P/|><.(...(..."/<.{"_{{=..)..>})<|><$}}/\}}&P<\(/._...>\$'/.>}/{}}{)..|/(\'.<(\''"")$/{{}})<..'...}}>3#./\$<}|.}|..$.><${{}/>.}}{{<>(""''/..>){<}\?=}{\._=/$/=_>)\{_\._..>)</{\=._.....>(($>}}<.>5#.\/}>)<>-/(.....{\<>}}{{/)\$>=}}}))<...=...(\?{{{?<\<._...}.><..\}}/..>'P&//(\......(..\})"'/./&P'&P{}}&P'<{}\{{{({{{(.\&P=<.><$"&1}(./'"?&'&"\.|>}{?&"?&'P&/|{/&P''</(\..>P&{/&/}{}&'&},/"&P'&?<.|\}{&?"&P'&P'<._.>"&}\(>))<\=}{}<.{/}&?"&"&/"&"?&}\.|>?&"?&{{}}?&//x'&{((<._\($|(}.\/}{/>=&'P&"&/".{3?<.|\"&P'&P}{}&P'<.>&{}}?&"&'P&\=}}<.}/2?".?''5?"/?1{(}\."..../{},<../&//&"&P'&P'&"&"</{}}{{/>"?1''?.'({/}}{}<..>?&"?&}}$>)|P/<.>"&'P&'P&"&"&{/........._/"\$#1}/._.........|,($<'"}'?/_$P#"$0'${)$})$)|........(>/\.#1?<$<|.....>?&}$>=?&"?&/1$..>I;n;v;a;l;i;d;P0;m;a\|\"(}}({=/..$_...\"&P=},}}&P'<.|><....................;...>1"(}}){=/_....>'P&'P&}}_?&/#.>}?4'%\/<...@;1P;e;z<._><>"))'?=<.$$=..\&P}{&</\"><_'|/'&=}<.>{{.<.........|>(/>3")}}){=/=/_.>}P&"?/"<).}_.>?4{=:<.|_...........\$\2$'>4")}}({/."\{&P'&?/><.?|>P...."/=(>(/./(}{{\..>(<>(<>?5'"((..'/...#,</,}{{\.......;.F>..\(...}....._.._..._..._........__..'$......\.<R..$.>))<$}{{&P'&?}<.\$$.\...................$\.<>L\.\(('_"\>}P&"?&{/__/=(.(<.>_)..<...>....\..._.<.....&?=\}=&?"&<.."'>.\>))<.|>))\.|$.>&"?&{{}=P&}?&=}/{\.>&{{P/{">)<|\{<(|\(_(<>\_\?"&P'&P}{{{&<=_.>\&\?"&?<|'{/(/>{{/_>.{/=/\\.>'P&"?&"?&"?/._(\)\\>?&"/_|.>/.$/|$..\\><..\&?}{{}&P'&<}.._>{<|\{}<._$>-")<.>_)<|{)$|..>}=P&"?&"?/...{"./>'P&/=_\{?(/>(<>\(|)__.\&?}}{}&P<}.$.\&P'&P'&<\})))&=<\)<'.'_,><.>"?&'P&'/.|>?&{{}?&"?/>&"?&"?&}}<.".(\\\&?={&P<{..\"&?"&P'&<.?....|.$'\$/\"/.,.>{}{}=/..>&'P&}{{}P/\{}&P{(&?"&?"<'.(\&?"&<}..\?"&?"&<.>P&={}}?&}}P&'P&/.'.>&"?/..>P&}}{{P/\}&P'&?={&?<$}=\"."\P'<{..\'&P'&<....>'P&{}P&"?&{{<\\..>&/$.>}{?&"?/|'$&.P&$P\$'&P={(/..\P\\.\{&?"&?\...\?{{}=<$&P'&P<.,./<?\...{}=P\"&<.>=P&""'?&'P&'/$.#1.>{?1#=$\&'P/\}&P'&?={(,}<._?_&\&?{=&{*=}4<.>P&"?&"?&'P&/1_$>}?&}}=?&){?/\{}&P'&?={&?#<$

```

Try it online!

"Readable" version:

```
                             ( . = $ > ( { { { ( { } } { \ > 6 ' % = { } { ? 4 = $ / .
                            / \ _ > < . / , { } } { < $ < \ ? { & P ' _ ( " ' " # < " .
                           > . . . . . . . . _ . . \ > < / < / ( \ . | / < > } { 0 / ' $
                          . } _ . . . . . > < > ) < . $ ) ) . > < $ . / $ \ ) ) ' " < $ _
                         . ) > < . > % ' 2 { / _ . > ( / ) | _ > } { { } . / . . > # / | }
                        . ' / $ | \ } ) ' % . < > { = \ $ _ . \ < $ ) ) < > ( | \ 4 ? < . {
                       . % . | / < / { = . . . . $ / < > / . . . ' . . . _ . > ' " ' _ / < }
                      . . . . ( { { > % ' ) ) } / . > < . $ . / { } { \ > $ \ | $ ( < > < $ ?
                     . . \ \ < . } _ > = < . _ . . \ ( / . / / . . \ } \ . ) ) ) ) ) < . . . 2
                    / | $ \ ) { } / { . . > < > ) . . . / _ $ . . $ _ > { 0 # { { ( ( ( ( / | #
                   . } > < . . > . < _ . \ ( / / $ > ) ) < ( / . \ . \ } ) ' " # 4 ? # \ _ = _ -
                  . . = . > ( < . . . ( . . > ( / \ " ) < ( ( . \ = } } } \ > { } { ? < , | { > /
                 . . . ( . . . > ( $ > { ) < . > { = P & / ( > / / ( _ . ) \ } = # = \ 4 # | ) _ _
                . > " ' ( ) ' \ . ' . . " . ( \ & P ' & < / ' & \ $ _ > < / } { ) < \ < 0 | \ < . }
               . \ " \ . ( . ( . ( / ( \ . . { . > } = P / | > < . ( . . . ( . . . " / < . { " _ { {
              = . . ) . . > } ) < | > < $ } } / \ } } & P < \ ( / . _ . . . > \ $ ' / . > } / { } } {
             ) . . | / ( \ ' . < ( \ ' ' " " ) $ / { { } } ) < . . ' . . . } } > 3 # . / \ $ < } | . }
            | . . $ . > < $ { { } / > . } } { { < > ( " " ' ' / . . > ) { < } \ ? = } { \ . _ = / $ / =
           _ > ) \ { _ \ . _ . . > ) < / { \ = . _ . . . . . > ( ( $ > } } < . > 5 # . \ / } > ) < > - /
          ( . . . . . { \ < > } } { { / ) \ $ > = } } } ) ) < . . . = . . . ( \ ? { { { ? < \ < . _ . . .
         } . > < . . \ } } / . . > ' P & / / ( \ . . . . . . ( . . \ } ) " ' / . / & P ' & P { } } & P ' <
        { } \ { { { ( { { { ( . \ & P = < . > < $ " & 1 } ( . / ' " ? & ' & " \ . | > } { ? & " ? & ' P & /
       | { / & P ' ' < / ( \ . . > P & { / & / } { } & ' & } , / " & P ' & ? < . | \ } { & ? " & P ' & P ' <
      . _ . > " & } \ ( > ) ) < \ = } { } < . { / } & ? " & " & / " & " ? & } \ . | > ? & " ? & { { } } ? & /
     / x ' & { ( ( < . _ \ ( $ | ( } . \ / } { / > = & ' P & " & / " . { 3 ? < . | \ " & P ' & P } { } & P ' <
    . > & { } } ? & " & ' P & \ = } } < . } / 2 ? " . ? ' ' 5 ? " / ? 1 { ( } \ . " . . . . / { } , < . . / & /
   / & " & P ' & P ' & " & " < / { } } { { / > " ? 1 ' ' ? . ' ( { / } } { } < . . > ? & " ? & } } $ > ) | P / <
  . > " & ' P & ' P & " & " & { / . . . . . . . . . _ / " \ $ # 1 } / . _ . . . . . . . . . | , ( $ < ' " } ' ? /
 _ $ P # " $ 0 ' $ { ) $ } ) $ ) | . . . . . . . . ( > / \ . # 1 ? < $ < | . . . . . > ? & } $ > = ? & " ? & / 1 $
  . . > I ; n ; v ; a ; l ; i ; d ; P 0 ; m ; a \ | \ " ( } } ( { = / . . $ _ . . . \ " & P = } , } } & P ' < . |
   > < . . . . . . . . . . . . . . . . . . . . ; . . . > 1 " ( } } ) { = / _ . . . . > ' P & ' P & } } _ ? & / #
    . > } ? 4 ' % \ / < . . . @ ; 1 P ; e ; z < . _ > < > " ) ) ' ? = < . $ $ = . . \ & P } { & < / \ " > < _ '
     | / ' & = } < . > { { . < . . . . . . . . . | > ( / > 3 " ) } } ) { = / = / _ . > } P & " ? / " < ) . } _
      . > ? 4 { = : < . | _ . . . . . . . . . . . \ $ \ 2 $ ' > 4 " ) } } ( { / . " \ { & P ' & ? / > < . ? |
       > P . . . . " / = ( > ( / . / ( } { { \ . . > ( < > ( < > ? 5 ' " ( ( . . ' / . . . # , < / , } { { \
        . . . . . . . ; . F > . . \ ( . . . } . . . . . _ . . _ . . . _ . . . _ . . . . . . . . _ _ . . ' $
         . . . . . . \ . < R . . $ . > ) ) < $ } { { & P ' & ? } < . \ $ $ . \ . . . . . . . . . . . . . .
          . . . . . $ \ . < > L \ . \ ( ( ' _ " \ > } P & " ? & { / _ _ / = ( . ( < . > _ ) . . < . . . >
           . . . . \ . . . _ . < . . . . . & ? = \ } = & ? " & < . . " ' > . \ > ) ) < . | > ) ) \ . | $
            . > & " ? & { { } = P & } ? & = } / { \ . > & { { P / { " > ) < | \ { < ( | \ ( _ ( < > \ _
             \ ? " & P ' & P } { { { & < = _ . > \ & \ ? " & ? < | ' { / ( / > { { / _ > . { / = / \ \
              . > ' P & " ? & " ? & " ? / . _ ( \ ) \ \ > ? & " / _ | . > / . $ / | $ . . \ \ > < . .
               \ & ? } { { } & P ' & < } . . _ > { < | \ { } < . _ $ > - " ) < . > _ ) < | { ) $ | .
                . > } = P & " ? & " ? / . . . { " . / > ' P & / = _ \ { ? ( / > ( < > \ ( | ) _ _ .
                 \ & ? } } { } & P < } . $ . \ & P ' & P ' & < \ } ) ) ) & = < \ ) < ' . ' _ , > <
                  . > " ? & ' P & ' / . | > ? & { { } ? & " ? / > & " ? & " ? & } } < . " . ( \ \
                   \ & ? = { & P < { . . \ " & ? " & P ' & < . ? . . . . | . $ ' \ $ / \ " / . ,
                    . > { } { } = / . . > & ' P & } { { } P / \ { } & P { ( & ? " & ? " < ' . (
                     \ & ? " & < } . . \ ? " & ? " & < . > P & = { } } ? & } } P & ' P & / . '
                      . > & " ? / . . > P & } } { { P / \ } & P ' & ? = { & ? < $ } = \ " . "
                       \ P ' < { . . \ ' & P ' & < . . . . > ' P & { } P & " ? & { { < \ \ .
                        . > & / $ . > } { ? & " ? / | ' $ & . P & $ P \ $ ' & P = { ( / . .
                         \ P \ \ . \ { & ? " & ? \ . . . \ ? { { } = < $ & P ' & P < . , .
                          / < ? \ . . . { } = P \ " & < . > = P & " " ' ? & ' P & ' / $ .
                           # 1 . > { ? 1 # = $ \ & ' P / \ } & P ' & ? = { ( , } < . _ ?
                            _ & \ & ? { = & { * = } 4 < . > P & " ? & " ? & ' P & / 1 _
                             $ > } ? & } } = ? & ) { ? / \ { } & P ' & ? = { & ? # < $

```

Tested on Esoteric IDE: TIO might time out on some of the larger test cases but all verified. Many thanks to Timwi, this wouldn't have been possible without the IDE.

There's quite a bit of empty space, so I might have been able to fit this onto a side-length 28 hexagon (instead of side-length 29) but that will be a massive task so I'm probably not going to attempt it.

# Basic Explanation

Click the images for a larger and more detailed version.

## Functions

*Note: Divisions are generally correct but may occasionally be a rough guess.*

This code is quite "functional" - as much as Hexagony allows it to be. There are eight main functions in this code labelled in the above diagram, named by the numbers with which they are called (so their instruction pointer numbers are that number mod 6). In (rough) order of calling, they are (quoted names are locations in memory which will be explained later):

* S: The starting function - reads the input and sets up the "reference array", then starts the "path stack" with the three paths `F`, `R` and `L` ready for main processing. Instruction pointer 0 moves to function 0 while the execution moves to function 1.
* 1 (-11): The main function - uses 2 to get a path, 3 to check its validity, and if valid goes to function -110/-10 twice and then 4 three times to copy the new paths across into the "path stack", finishing by returning to itself. May call function 5 if the path is at the end location.
* 2: Gets the next path off the "path stack" ready for processing, calls function -1 if no paths left on the stack. Returns to function 1.
* 3: Takes a pair of values as well as the move number and checks the "reference array" to see whether the current path has ended at a valid location. A valid location is either the start within the first 3 moves, or any `+` within 2 moves of it first being reached. Returns to function 1.
* -10/-110: Copies the current path. Returns to function 1.
* 0: Helps function 1 to manage direction of movement with `F`. Returns to function 1.
* 4: Takes a copy of the current path and interlinked with function 1 changes it into the same path with either `F`, `R` or `L` appended. Returns to function 1.
* 5: Takes the path and prints out the correct path (e.g. `FFLF`), then terminates the program.
* -1: Prints `Invalid maze!` and terminates.
* (Double arrows): Due to lack of space, function 1/-11 had to go off into the space above function -1.

## Memory

Note: Thanks to Esoteric IDE again for the diagram

The memory consists of three main parts:

* Reference array: The grid is stored columns 2 apart, with a value at each step:
    + 0 represents either a , `0` or a valid place that was accessed more moves ago than would be required to exit the place in any direction.
    + 1 represents a `+` that hasn't yet been reached.
    + (higher number) represents the move number where there will have been enough moves to exit the place in any direction.
    + 10 also represents a new-line: these are never reached assuming they immediately follow the last non-white-space character.
* Rail: Consists of `-1`s with a single `-2` on the left, allows memory pointer to quickly return to the core processing area.
* Path stack: Stores each of the untested paths in order by path ID (which is directly related to move number so the shorter paths are tested first). The path is stored as follows:
+ Rot: the rotation at the end of the current path: 0 for up-left and increasing clockwise to 5
    + Move: the current move number (instructions - 1)
    + Path: the current path, stored in quaternary with `F`, `R`, `L` as `1`, `2`, `3` respectively
    + x/y: coordinates at the end of the current path: x+1 `-1`s right then y values up (though y=0 is processed as 1 anyway for the purposes of separating the rail from the reference data)

Other important memory locations:

1. The x/y of the `E` is stored here.
2. This space is used to transition paths in and out of memory.
3. This location is the centre of where each path is stored during processing.

# Answer
> 6 votes
# Python 3, 466 bytes

Would have probably ended up smaller if I used depth-first search or something. This monstrosity uses Dijkstra and is quite fast, but very long.

The code defines a function `S` that takes a multiline string with the maze and returns the result.

```
def F(M,L,c):y=M[:M.index(c)].count("\n");return L[y].index(c),y
def S(M):
 L=M.split("\n");Q=[("",)+F(M,L,"S")+(0,)];D={};R=range;H=len;U=R(2**30)
 while Q:
  C,*Q=sorted(Q,key=H);w,x,y,d=C
  for e in R(H(L)>y>-1<x<H(L[y])>0<H(D.get(C[1:],U))>H(w)and(L[y][x]in"+SE")*6):D[C[1:]]=w;E=(d+e)%6;Q+=[(w+",R,RR,RRR,LL,L".split(",")[e]+"F",x+[-1,1,2,1,-1,-2][E],y+[-1,-1,0,1,1,0][E],E)]
 J=min([D.get(F(M,L,"E")+(d,),U)for d in R(6)],key=H);return[J,"Invalid maze!"][J==U]

```

Here is a test of the code.

### Ungolfed

```
def find_char(maze, lines, char):
    y = maze[:maze.index(char)].count("\n")
    return lines[y].index(char), y
def solve(maze):
    lines = maze.split("\n")
    x, y = find_char(maze, lines, "S")
    queue = [("", x, y, 0)]
    solutions = {}
    very_long = range(2**30)
    x_for_direction = [-1,1,2,1,-1,-2]
    y_for_direction = [-1,-1,0,1,1,0]
    rotations = ["","R","RR","RRR","LL","L"]
    while len(queue) > 0:
        queue = sorted(queue, key=len)
        current, *queue = queue
        route, x, y, direction = current
        if 0 <= y < len(lines) and 0 <= x < len(lines[y]) and lines[y][x] in "+SE" and len(solutions.get(current[1:], very_long)) > len(route):
            solutions[current[1:]] = route
            for change in range(6):
                changed = (direction + change) % 6
                queue += [(route + rotations[change] + "F", x + x_for_direction[changed], y + y_for_direction[changed], changed)]
    end_x, end_y = find_char(maze, lines, "E")
    solution = min([solutions.get((end_x, end_y, direction), very_long) for direction in range(6)], key=len)
    return "Invalid maze!" if solution == very_long else solution

```

# Answer
> 3 votes
# Groovy, 624 bytes. *Fore!*

Time time get the ball rolling with a big one. Takes multi-line string as arg to `Q`

```
Q={a->d=[0]*4
a.eachWithIndex{x,y->f=x.indexOf('S');e=x.indexOf('E');
if(f!=-1){d[0]=f;d[1]=y}
if(e!=-1){d[2]=e;d[3]=y}}
g=[]
s={x,y,h,i,j->if(h.contains([x, y])|y>=a.size()||x>=a[y].size()|x<0|y<0)return;k = a[y][x]
def l=h+[[x, y]]
def m=j
def n=1
if(h){
o=h[-1]
p=[x,y]
q=[p[0]-o[0],p[1]-o[1]]
n=[[-2,0]:0,[-1,-1]:1,[1,-1]:2,[2,0]:3,[1,1]:4,[-1,1]:5][q]
r=n-i
m=j+((r==-5|r==5)?' LR'[(int)r/5]:['','R','RR','LL','L'][r])+'F'}
if(k=='E')g+=m
if(k=='+'|k=='S'){s(x-2,y,l,n,m)
s(x+2,y,l,n,m)
s(x+1,y+1,l,n,m)
s(x+1,y-1,l,n,m)
s(x-1,y+1,l,n,m)
s(x-1,y-1,l,n,m)}}
s(d[0],d[1],[],1,'')
print(g.min{it.size()}?:"Invalid maze!")}

```

Ungolfed version:

```
def map =
        """
  + 0 0 0 0 0 0
 0 0 0 0 0 + + 0
0 0 E 0 + 0 0 + 0
 0 0 0 0 0 0 0 +
  0 + 0 0 + + +
   0 0 + + 0 0
    S + 0 0 0""".split('\n').findAll()
//map =
//        """
// 0 + +
//E + 0 S 0
// 0 0 0 +
//  + + +""".split('\n').findAll()

//map = [""]// TODO remove this, this is type checking only
//map.remove(0)
//reader = System.in.newReader()
//line = reader.readLine()
//while (line != '') {
//    map << line
//    line = reader.readLine()
//}

startAndEnd = [0, 0, 0, 0]
map.eachWithIndex { it, idx ->
    s = it.indexOf('S'); e = it.indexOf('E');
    if (s != -1) {
        startAndEnd[0] = s; startAndEnd[1] = idx
    }
    if (e != -1) {
        startAndEnd[2] = e; startAndEnd[3] = idx
    }
}

def validPaths = []
testMove = { x, y, visited ->// visited is an array of x y pairs that we have already visited in this tree
    if (visited.contains([x, y]) || y >= map.size() || x >= map[y].size() || x < 0 || y < 0)
        return;

    def valueAtPos = map[y][x]
    def newPath = visited + [[x, y]]

    if (valueAtPos == 'E') validPaths += [newPath]
    if (valueAtPos == '+' || valueAtPos == 'S') {
        println "$x, $y passed $valueAtPos"
        testMove(x - 2, y, newPath)
        testMove(x + 2, y, newPath)

        testMove(x + 1, y + 1, newPath)
        testMove(x + 1, y - 1, newPath)

        testMove(x - 1, y + 1, newPath)
        testMove(x - 1, y - 1, newPath)
    }
}

//if (!validPath) invalid()
testMove(startAndEnd[0], startAndEnd[1], [])
println validPaths.join('\n')

//println validPath

def smallest = validPaths.collect {
    def path = ''
    def orintation = 1
    it.inject { old, goal ->
        def chr = map[goal[1]][goal[0]]
        def sub = [goal[0] - old[0], goal[1] - old[1]]
        def newOrin = [[-2, 0]: 0, [-1, -1]: 1, [1, -1]: 2, [2, 0]: 3, [1, 1]:4, [-1, 1]:5][sub]
        def diff = newOrin - orintation// 5L -5R
        def addedPath= ((diff==-5||diff==5)?' LR'[(int)diff/5]:['', 'R', 'RR', 'LL', 'L'][diff]) + 'F'//(diff == 0) ? '' : (diff > 0 ? 'R'*diff : 'L'*(-diff)) + 'F'
//        println "old:$old, goal:$goal chr $chr, orintation $orintation, sub:$sub newOrin $newOrin newPath $addedPath diff $diff"
        path += addedPath
        orintation = newOrin
        goal
    }
    path
}.min{it.size()}
//println "paths:\n${smallest.join('\n')}"
if (smallest)
    println "path $smallest"
else
    println "Invalid maze!"

```

# Answer
> 3 votes
# C#, ~~600~~ 574 bytes

Complete program, accepts input from STDIN, output to STDOUT.

*Edit: there was a bug in the wrap handling (didn't break on any of the given test cases) which would have added 1 byte, so I did a bit more golfing to compensate.*

```
using Q=System.Console;struct P{int p,d;static void Main(){string D="",L;int w=0,W=0,o,n=1;for(;(L=Q.ReadLine())!=null;D+=L)w=(o=(L+="X").Length+1)>w?o:w;for(;W<D.Length;)D=D.Insert(W+1,"".PadLeft(D[W++]>87?w-W%w:0));P[]K=new P[W*6];var T=new string[W*6];P c=K[o=0]=new P{p=D.IndexOf('S')};for(System.Action A=()=>{if(c.p>=0&c.p<W&System.Array.IndexOf(K,c)<0&&D[c.p]%8>0){T[n]=T[o]+L;K[n]=c;n=D[c.p]==69?-n:n+1;}};o<n;o++){c=K[o];L="R";c.d=++c.d%6;A();L="L";c.d=(c.d+4)%6;A();L="F";c=K[o];c.p+=new[]{~w,1-w,2,1+w,w-1,-2}[c.d%6];A();}Q.WriteLine(n>0?"Invalid maze!":T[-n]);}}

```

It starts by reading in the map, appending `(` to each line so that it knows where it ends, and can go back and add in a load of spaces to make the map rectangular, and with a row of spaces along the right side (this saves us doing wrapping checks as will be explained below). It works out the width of rectangle at some point in this, and ascertains the total length of the Map.

Next, it initialises everything for a Breadth-First-Search. Two biggish arrays are created, one to store all the states we need to explore in our search, the other to record the route we took to get to each state. The initial state is added to the due array, with the head and tail pointers pre-set someway above. Everything is 1-indexed.

We then iterate until the tail crashes into the head, or at least it *appears* to have crashed into the head. For each state we've visited, we attempt to add a new state at the same position where we are rotated left or right, and then one where we have moved forward. The directions are indexed, with the initial direction (defaulting to `0`) corresponding to "up-left".

When we try to queue a state, it is bound checked, but not wrap checked, because of the columns of spaces on the right side, which is picked up on by the "are we allowed to be here?" check (you aren't allowed to be on spaces). If the state is queued, we then check if it's on the `E` cell, and if it is, we set the head of the queue to be minus itself, which causes the main loop to exit, and tells the last line of the program to print out the corresponding route, rather than the failure message (which shows if we run out of states to expand (the tail crashes into the head)).

```
using Q=System.Console;

// mod 8 table (the block of zeros is what we are after - it's everywhere we /can't/ go)
//   0 (space)
// O 0
// X 0
// S 3
// + 3
// E 5

struct P
{
    int p,d;
    static void Main()
    {
        // it's probably a bad thing that I have my own standards for naming this stupid read sequence by now
        string D="", // map
        L; // line/path char

        int w=0, // width
        W=0, // full length
        o, // next state to expand
        n=1; // next state to fill

        for(;(L=Q.ReadLine())!=null;D+=L) // read in map
            w=(o=(L+="X").Length+1)>w?o:w; // assertain max length (and mark end, and remove any need for wrap checking)

        // now we need to add those trailing spaces...
        for(;W<D.Length;)
            D=D.Insert(W+1,"".PadLeft(D[W++]>87?w-W%w:0)); // inject a load of spaces if we hit an X

        P[]K=new P[W*6]; // create space for due states (can't be more states than 6*number of cells)
        var T=new string[W*6]; // create space for routes (never done it this way before, kind of exciting :D)
        P c=K[o=0]=new P{p=D.IndexOf('S')}; // set first state (assignment to c is just to make the lambda shut up about unassigned variables)

        // run bfs
        for(

            System.Action A=()=> // this adds c to the list of states to be expanded, if a whole load of checks pass
            {
                if(//n>0& // we havn't already finished - we don't need this, because we can't win on the first turn, so can't win unless we go forward, which we check last
                   c.p>=0&c.p<W& // c is within bounds
                   System.Array.IndexOf(K,c)<0&& // we havn't seen c yet (the && is to prevent the following lookup IOBing)
                   D[c.p]%8>0) // and we can move here (see table at top of code)
                {
                    T[n]=T[o]+L; // store route
                    K[n]=c; // store state
                    n=D[c.p]==69?-n:n+1; // check if we are at the end, if so, set n to be negative of itself so we know, and can look up the route (otherwise, increment n)
                }
            }

            ;o<n;o++) // o<n also catches n<0
        {
            c=K[o]; // take current
            L="R"; // say we are going right
            c.d=++c.d%6; // turn right
            A(); // go!

            L="L"; // say we are going left
            c.d=(c.d+4)%6; // turn left
            A(); // go!

            L="F"; // say we - you get the picture
            c=K[o];
            c.p+=new[]{~w,1-w,2,1+w,w-1,-2}[c.d%6]; // look up direction of travel (~w = -w-1)
            A();
        }

        // check if we visited the end
        Q.WriteLine(n>0?"Invalid maze!":T[-n]); // if n<0, then we found the end, so spit out the corresponding route, otherwise, the maze is invlida
    }
}

```

Like most of my Graph-Searches on this site, I am making good use of C# structs, which default to compare by literal value.

# Answer
> 2 votes
# Python 2, 703 bytes

Not as good as the other two versions, but at least it works haha. Set `M` to the maze.

Since I have no experience at solving mazes, it just goes by a brute force approach, where it'll find all the solutions it can that doesn't involve crossing back over itself. It calculates the turns from the shortest ones, and then chooses the shortest result from that.

```
z=zip;d=z((-1,1,-2,2,-1,1),(-1,-1,0,0,1,1));E=enumerate;D={};t=tuple;o=list;b=o.index
for y,i in E(M.split('\n')):
 for x,j in E(o(i)):
  c=(x,y);D[c]=j
  if j=='S':s=c
  if j=='E':e=c
def P(s,e,D,p):
 p=o(p);p.append(s);D=D.copy();D[s]=''
 for i in d:
  c=t(x+y for x,y in z(s,i))
  if c not in p and c in D:
   if D[c]=='E':L.append(p+[c])
   if D[c]=='+':P(c,e,D,p)
def R(p):
 a=[0,1,3,5,4,2];h=d[0];x=p[0];s=''
 for c in p[1:]:
  r=t(x-y for x,y in z(c,x));n=0
  while h!=r:n+=1;h=d[a[(b(a,b(d,h))+1)%6]]
  s+=['L'*(6-n),'R'*n][n<3]+'F';x=t(x+y for x,y in z(x,h))
 return s
L=[];P(s,e,D,[])
try:l=len(min(L))
except ValueError:print"Invalid maze!"
else:print min([R(i)for i in L if len(i)==l],key=len)

```

Messy ungolfed version:

```
maze = """
     0 0 0 0
    0 + 0 + 0
   0 0 0 + + 0
  0 + 0 + 0 + 0
 0 0 + + 0 0 + 0
0 0 + 0 + 0 0 + 0
 E 0 + 0 0 + + 0
  + + 0 + 0 + 0
   0 0 0 0 0 +
    + 0 + + +
     0 S 0 0
     """
directions = [(-1, -1), (1, -1),
              (-2, 0), (2, 0),
              (-1, 1), (1, 1)]

maze_dict = {}
maze_lines = maze.split('\n')
for y, row in enumerate(maze_lines):
    if row:
        for x, item in enumerate(list(row)):
            coordinates = (x, y)
            maze_dict[coordinates] = item
            if item == 'S':
                start = coordinates
            elif item == 'E':
                end = coordinates

list_of_paths = []

def find_path(start, end, maze_dict, current_path=None):
    if current_path is None:
        current_path = []
    current_path = list(current_path)
    current_path.append(start)
    current_dict = maze_dict.copy()
    current_dict[start] = '0'

    for direction in directions:
        new_coordinate = (start[0] + direction[0], start[1] + direction[1])

        if new_coordinate in current_path:
            pass

        elif new_coordinate in current_dict:
            if current_dict[new_coordinate] == 'E':
                list_of_paths.append(current_path + [new_coordinate])
                break
            elif current_dict[new_coordinate] == '+':
                find_path(new_coordinate, end, current_dict, current_path)

find_path(start, end, maze_dict)

def find_route(path):

    heading_R = [0, 1, 3, 5, 4, 2]
    heading = (-1, -1)
    current_pos = path[0]
    current_heading = directions.index(heading)
    output_string = []
    for coordinate in path[1:]:
        required_heading = (coordinate[0] - current_pos[0], coordinate[1] - current_pos[1])

        count_R = 0
        while heading != required_heading:
            count_R += 1
            heading_index = directions.index(heading)
            heading_order = (heading_R.index(heading_index) + 1) % len(heading_R)
            heading = directions[heading_R[heading_order]]

        if count_R:
            if count_R > 3:
                output_string += ['L'] * (6 - count_R)
            else:
                output_string += ['R'] * count_R

        output_string.append('F')
        current_pos = (current_pos[0] + heading[0], current_pos[1] + heading[1])
    return ''.join(output_string)

routes = []
try:
    min_len = len(min(list_of_paths))
except ValueError:
    print "Invalid maze!"
else:
    for i in list_of_paths:
        if len(i) == min_len:
            routes.append(find_route(i))

    print 'Shortest route to end: {}'.format(min(routes, key=len))

```

---
Tags: code-golf, path-finding, hexagonal-grid, maze
---


title: Sort a string by a given ordering

text:
# Question
Title: Sort a string by a given ordering
Your challenge is to sort a string, but rather than by the normal alphabetical order (abc..xyz), you will be sorting strings by a specified alphabet.

You must write a program or function that takes two inputs: An alphabet **A** and an string **S**. Both will only contain lowercase English letters, and both will contain at least one character.

You must move letters in **S** so that the letter that appears first in **A** appears first, then whichever letter appears second in **A**, etc. There may be some letters in **S** that do not appear in **A**, these should be left at the end and not moved around relative to each other.

Test cases:

```
A       S               Result
axd     haxuizzxaxduxha aaaxxxxdhuizzuh
a       xyz             xyz
abc     dcba            abcd
il      nmiuplliu       iillnmupu
asdf    qwerty          qwerty

```

Fewest bytes wins!

# Answer
# 05AB1E, 4 bytes

```
Rvy†

```

Try it online!

**Explanation**

```
R     # Reverse the alphabet
 vy   # For each letter ...
   †  # Push S with the current letter filtered to the front

```
> 5 votes

# Answer
# Python 3, ~~50 47 46~~ 44 bytes

*-3 bytes thanks to ngn!*

*-1 byte thanks to mypetlion*

```
lambda a,s:s.sort(key=lambda c:a.find(c)%27)

```

Try it online!

Takes in a string as the alphabet and a list of chars as the string and sorts the list in place.

The `%27` ensures that if the character is not in the alphabet, the index returned puts it after the rest of the alphabet.
> 9 votes

# Answer
## Haskell, 42 bytes

```
a#s=[c|c<-a,d<-s,c==d]++[c|c<-s,all(/=c)a]

```

Try it online!

```
a#s=                     -- take alphabet a and string s
        c<-a             -- for all c in a
             d<-s        --   for all d in s
    [c|       c==d]             keep c if c equals d
   ++                    -- append
    [c|c<-s        ]     --   all c of s
         ,all(/=c)a      --   that are not in a

```
> 7 votes

# Answer
# Perl 6,  ~~55~~  43 bytes

```
->\A,\S{[~] S.comb.sort:{%(A.comb.antipairs){$_}//∞}}

```

Try it

```
->\A,\S{[~] S.comb.sort:{A.index($_)//∞}}

```

Try it

## Expanded:

```
-> \A, \S {
  [~]  # reduce using &infix:«~» (shorter than `.join`)

    S.comb.sort: # split into character list and sort by:

      {  # bare block lambda with implicit parameter $_

        A.index( $_ ) # get the position

        //  # if it is undefined (not in `A`)
        ∞   # return Inf instead (so it comes at end of result)
      }
}

```
> 7 votes

# Answer
# Stax, 6 bytes

```
{xrINo

```

Run and debug it

This sorts by a block that does this.

* Reverse the alphabet.
* Get the index of each character in the reversed alphabet. Missing yields -1.
* Negate the index.
> 6 votes

# Answer
# Haskell, 40 34 bytes

**-6** bytes huge thanks to Laikoni.

```
foldr(\c->r(==c)<>r(/=c))
r=filter

```

Try it online!

The first line is an expression that takes two arguments: **S** and **A**.
> 6 votes

# Answer
# Python 2, 38 bytes

```
def f(a,s):s.sort(None,a[::-1].find,1)

```

**a** must be a string, **s** a list of strings of length 1. **f** sorts **s** in place.

Try it online!

### Alternate version, string I/O, 48 bytes

```
lambda a,s:`sorted(s,None,a[::-1].find,1)`[2::5]

```

Try it online!

### How it works

`s.sort(None,a[::-1],1)` is shorthand for `s.sort(cmp=None,key=a[::-1],reverse=1)`.

From the docs:

> *reverse* is a boolean value. If set to `True`, then the list elements are sorted as if each comparison were reversed.
> 5 votes

# Answer
# K (ngn/k), 9 bytes

```
{y@>-x?y}

```

Try it online!

`{`...`}` is a function with arguments `x` and `y`

`x?y` finds for each element in `y` the index of its first occurrence in `x`; if an element is not found in `x`, its index is considered `0N` (-263)

`-` negates all indices except that it keeps the `0N`-s intact, because 263≡-263 (mod 264)

`>` returns a sort-descending permutation

`y@` indexes `y` with that
> 4 votes

# Answer
# , 5 bytes

```
]/:i.

```

Dyadic verb, taking the alphabet on its left and the string to be sorted on the right.

`i.` finds the indeces of string's characters in the alphabet, the alphabet length if not found.

```
   'axd' i. 'haxuizzxaxduxha'
3 0 1 3 3 3 3 1 0 1 2 3 1 3 0

```

`/:` sorts its left agrument according to the order specified in the right one.

`]` the rigth argument (the string)

```
  'haxuizzxaxduxha' /: 3 0 1 3 3 3 3 1 0 1 2 3 1 3 0
aaaxxxxdhuizzuh

```

Try it online!
> 4 votes

# Answer
# APL (Dyalog Unicode), 5 bytesSBCS

Anonymous tacit prefix function, taking `[string,ordering]` as argument.

```
⍋⍨/⌷⊃

```

Try it online!

`/` Reduce by the following function:

… namely the reversed-arguments version of the following function:

grade the right string according to the left ordering (missing letters go at the end)

use that to index into…

the first element of the argument (i.e. the string)
> 4 votes

# Answer
# Python 2, ~~35~~ 50 bytes

```
lambda a,s:sorted(s,key=lambda c:-a[::-1].find(c))

```

Try it online!

Takes `a` and `s` as strings; returns a list of singelton strings.

Note: Ouch! Gained 15 bytes to fix...
> 4 votes

# Answer
# Charcoal, 13 bytes

```
Ｆθ×ι№ηιΦη¬№θι

```

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

```
 θ              First input
Ｆ               Loop over characters
     η          Second input
      ι         Current character
    №           Count matches
   ι            Current character
  ×             Repeat
                Implicitly print
        η       Second input
       Φ        Filter
           θ    First input
            ι   Current character
          №     Count matches
         ¬      Logical not
                Implicitly print non-matching characters

```
> 3 votes

# Answer
# JavaScript (SpiderMonkey), 50 bytes

Takes input in currying syntax `(a)(s)`, where **a** is a string and **s** is an array of characters. Returns an array of characters.

```
a=>s=>s.sort((b,c)=>(g=c=>-1/a.search(c))(b)-g(c))

```

Try it online!

### How?

We define the helper function **g()** as:

```
c => -1 / a.search(c)

```

which returns:

* **1** if **c** does not belong to the alphabet
* a float value in **\[-Inf, 0)** based on the position of **c** in the alphabet otherwise (-Inf, -1, -1/2, -1/3, etc.)

We sort **s\[ \]** by computing **g(b) - g(c)** for each pair of characters **(b, c)** passed to the callback of **sort()**.

Because the implementation of **sort()** in SpiderMonkey is stable, all characters of **s\[ \]** that do not belong to the alphabet are simply moved at the end in order of appearance and are let unchanged when they are compared with each other.

---

# JavaScript (ES6), 61 bytes

Takes input in currying syntax `(a)(s)`, where both **a** and **s** are arrays of characters. Returns a string.

```
a=>s=>a.map(C=>s=s.filter(c=>c!=C||!(o+=c)),o='')&&o+s.join``

```

Try it online!
> 3 votes

# Answer
# Jelly, 4 bytes

```
fⱮ;ḟ

```

A dyadic link accepting the string on the left and the alphabet on the right (as lists of characters) and returning the result (also as a list of characters).

**Try it online!**

### How?

```
fⱮ;ḟ - Link: string; alphabet                                    e.g. smallnotxl; xl
 Ɱ   - map (for each character in the alphabet):                      1=x; 2=l
f    -   filter keep (keep occurrences of this character from string)   x    lll -> xlll
   ḟ - filter discard (discard all alphabet characters from string)   smanot
  ;  - concatenate                                                    xlllsmanot

```
> 3 votes

# Answer
# , ~~69 62~~ 58 bytes

```
function(a,s)c(rep(a,rowSums(outer(a,s,"=="))),s[!s%in%a])

```

Try it online!

Input and output are vectors of individual characters.

Explanation:

```
function(a,s)c(                              ,           ) #combine:
                   a,                                      #[each char in a
               rep(                                        #each repeated
                     rowSums(               )              #the number of
                             outer(a,s,"==")               #occurrence in s]
                                              s            #with s
                                               [ s%in%a]   #all chars in a
                                                !          #omitted

```
> 3 votes

# Answer
# Brain-Flak (BrainHack), 118 bytes

```
{({}(<>))<>}{}<>{<>([[]()]<{<>(({})<({}<>[({}<>)]){(<()>)}{}{}>)<>}<>({}<{({}<>)<>}<>>)>[]){({}()<(({}))>)}{}{}<>{}}<>

```

Try it online!

Input is the first string, followed by a null, followed by the second string. A version that uses a newline as the separator instead adds 24 bytes:

# Brain-Flak, 142 bytes

```
(()){{}(({}(<>))[(()()()()()){}]<>)}{}<>{<>([[]()]<{<>(({})<({}<>[({}<>)]){(<()>)}{}{}>)<>}<>({}<{({}<>)<>}<>>)>[]){({}()<(({}))>)}{}{}<>{}}<>

```

Try it online!

### Explanation

```
# Move A to other stack reversed
# Zeroes are pushed under each character for later.
# (This is the only part that needs to change in order to use newline as separator.)
{({}(<>))<>}{}<>

# For each character in A, starting at the end:
{

  # Track current length of S.
  <>([[]()]<

    # For each character in S:
    {

      # While keeping character from A
      <>(({})<

        # Move character from S to second stack and push difference
        ({}<>[({}<>)])

        # Delete character if equal
        {(<()>)}{}{}

      >)

    <>}

    # Move S back to first stack while maintaining character from A
    <>({}<{({}<>)<>}<>>)

  # Push difference between old and new lengths of S
  >[])

  # Insert character from A at beginning of S that many times
  {({}()<(({}))>)}{}{}

<>{}}<>

```
> 3 votes

# Answer
# C (gcc), 97 bytes

```
f(D,d,S,s,i,o)char*D,*S;{
  while(d--){
    for(i=o=s;i--;)S[i]-D[d]?S[--o]=S[i]:0;
    while(o--)S[o]=D[d];
  }
}

```

All whitespaces (spaces and newlines) in the code above are only for readability and should be removed.

The dictionary is passed in `D` and have length `d`, the string is passed in `S` and have length `s`. `i` and `o` should be omitted.

Try it online!
> 2 votes

# Answer
# Pyth,  ~~9~~  5 bytes

```
ox+vz

```

Try it here!

```
ox+vz    Full program. Input format: "S" \n "A".
o        Sort the characters of S by (variable: N)...
 x       ... N's index in...
  +vz    ... A + N

```
> 2 votes

# Answer
## Perl 5 with `-pF`, 43 bytes

```
$_=<>;print$F[0]x s/@{[shift@F]}//g while@F

```

Try it online!
> 2 votes

# Answer
# Java 8, 98 bytes

```
a->s->{for(int i=a.length;i-->0;s=s.replaceAll("[^"+a[i]+"]","")+s.replaceAll(a[i],""));return s;}

```

Try it online.

**Explanation:**

```
a->s->{       // Method with String-array and String parameters, and String return-type
  for(int i=a.length;i-->0;
              //  Loop backwards over the alphabet
    s=        //   Replace the current `s` with:
      s.replaceAll("[^"+a[i]+"]","")
              //    All the current characters of `a` in `s`
      +s.replaceAll(a[i],""));
              //    Concatted with everything else
  return s;}  //  Return the modified `s`

```
> 2 votes

# Answer
# Prolog (SWI), 136 bytes

```
X/_/[X|_].
X/Y/[Z|R]:-Y\=Z,X/Y/R.
i(_,X,[],[X]).
i(A,X,[Y|R],[X,Y|R]):-X/Y/A.
i(A,X,[Y|R],[Y|S]):-i(A,X,R,S).
A*S*T:-foldl(i(A),S,[],T).

```

Try it online! Example usage:

```
[i,l]*[n,m,i,u,p,l,l,i,u]*S.
S = [i, i, l, l, n, m, u, p, u]

```
> 2 votes

# Answer
# Clean, 61 bytes

```
import StdEnv
$a s=[c\\c<-a,k<-s|k==c]++[c\\c<-s|all((<>)c)a]

```

Try it online!

Defines the function `$ :: [Char] [Char] -> [Char]`.

Unsurprisingly, this is literally nimi's Haskell answer but longer.
> 1 votes

# Answer
# Jelly, 7 bytes

```
i@oİ$¥Þ

```

Try it online!
> 1 votes

# Answer
# APL+WIN, 12 bytes

Prompts for screen input of S then A:

```
s[(,⎕)⍋s←,⎕]

```

Try it online! Courtesy of Dyalog Classic
> 1 votes

# Answer
# PynTree, 13 bytes

```
§yz:ṡzCæf+yxx

```

Try it online!

Port of Jo King's Python answer.

# Explanation

```
§yz:ṡzCæf+yxx  Anonymous lambda
§              lambda  ,
 y                    y
  z                     z
   :                     :
    ṡ                     sorted( ,lambda x:
     z                           z
      C                                     (          )( )
       æf                                    (   ).find
         +                                     +
          y                                   y
           x                                    x
            x                                            x

```
> 1 votes

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


title: Get duplicates from an array

text:
# Question
Title: Get duplicates from an array
So, I have an array

```
['a', 42, 'b', 42, 'a']

```

I want to alert users to the fact that 42 and 'a' appear in it twice.

```
some_function(['a', 42, 'b', 42, 'a'])

```

should return

```
['a', 42]

```

---

Write some code to extract the duplicates from an array.

* It should accept an array as input.
* The array can have multiple types of object.
* Duplication should be defined as per the language's standard equality function (examples are from ruby).
* It outputs an array of the duplicated items.
* The order of the returned items is irrelevant.
* Duplicates should only appear in the returned array once.
* Golf rules, do it in the smallest number of bytes.

Test cases

```
[1,2,3] => []

[1,2,3,2,1] => [1,2]

[1.0, 2, 2.0, 1.0] => [1, 2] or [1.0, 2.0] or [1, 2.0] or [1.0, 2]

[1, '1', '1.0'] => []

[nil, nil, false, false, true, true] => [nil, false, true]

```

# Answer
# Python 2, ~~39~~ 38 bytes

```
lambda l:{v for v in l if~-l.count(v)}

```

Try it online!

---

# Python 3, 37 bytes

```
lambda l:[*map(l.remove,{*l})]and{*l}

```

Try it online!
> 4 votes

# Answer
# Brachylog, 9 bytes

```
ọ{tℕ₂&h}ˢ

```

Try it online!

### Explanation

```
ọ           Occurrences
 {     }ˢ   Select:
     &h       The elements…
  tℕ₂         …which occur at least 2 times

```
> 4 votes

# Answer
# 05AB1E, 8 bytes

```
{γʒg≠}€н

```

Try it online!

**Explanation**

```
{γ       # Sort input and split into chunks of identical elements
  ʒg≠}   # Keeps chunks of length != 1
      €н # Map with the first element of each chunk

```
> 4 votes

# Answer
# Pyth, 5 bytes

```
{.-Q{

```

Try it here!

### How it works?

```
{.-Q{ – Full program.
    { – Deduplicate.
 .-Q  – And apply bagwise subtraction between the input Q and the above.
{     – Deduplicate the result.

```
> 4 votes

# Answer
# Javascript ES6, 48 bytes

```
a=>[...new Set(a.filter((b,c)=>a.indexOf(b)<c))]

```

Test cases

```
f=
a=>[...new Set(a.filter((b,c)=>a.indexOf(b)<c))];

tests=[
    [1,2,3],
    [1,2,3,2,1],
    [1.0, 2, 2.0, 1.0],
    [1, '1', '1.0'],
    [undefined, undefined, false, false, true, true],
    [1,2,1,1,1,2,1,2,2,1,1]
]
console.log(tests.map(b=>f(b)))
```
> 3 votes

# Answer
# MATL, ~~13~~ 12 bytes

```
"GX@&)m?6Mvu

```

Try it online!

*Thanks to Luis Mendo for saving a byte!*

using `m` is the only way I could use mixed-type equality checking. Takes input as a row cell array.

```
		% (implicit input x)
"		% for loop:
GX@&)		% push input and index, then get x(i) and x(-i),
                % where x(-i) means "x excluding element at index i"
    m		% ismember -- true if x(i) is in x(-i)
     ?		% if true
      6M	% get x(i)
	v	% concatenate with prior results
	 u	% and take unique values
		% implicit end of if
		% implicit end of for loop
		% implicit end of program, output results as cell array

```
> 3 votes

# Answer
# \[R\], 58 bytes

```
function(x)x[duplicated(x)]

```

(My original code was nonsense.)

This works with an array input (in R an "atomic vector") but all the elements have to have the same type, or will be coerced to the most general type.

This also works with a list input (the only way in R an "array"-ish object can have elements of different types) which is what the challenge seems to want. The list elements can be other lists, atomic vectors, matrices, data frames - anything, really.

But then the "equality" function used by `duplicated` is fairly strict and won't give the same answers as the challenge test cases indicate, which is a flaw in the challenge specs and not this answer.
> 3 votes

# Answer
# Jelly, 4 bytes

```
œ-QQ

```

Try it online!

The last test case (`[None, None, False, False, True, True]`) isn't possible in Jelly.
> 2 votes

# Answer
# Javascript (ES6), 51 bytes

```
a=>[...new Set(a.sort().filter((v,i)=>v===a[i+1]))]

```

run on tio.

Try it:

```
a=a=>[...new Set(a.sort().filter((v,i)=>v===a[i+1]))]

console.log(a([1,2,3]));
console.log(a([1,2,3,2,1]));
console.log(a([1.0, 2, 2.0, 1.0]));
console.log(a([1, '1', '1.0']));
console.log(a([null, null, false, false, true, true]));
console.log(a([1,1,1,3,2,3,2,3,4]));
```
> 2 votes

# Answer
# PHP, 75 bytes

```
function a($b){return array_unique(array_diff_assoc($b,array_unique($b)));}

```

Try it online!
> 2 votes

# Answer
# Powershell, ~~38~~ 32 bytes

```
($args|group|?{$_.count-1}).Name

```

Try it online, thanks AdmBorkBork

using:

1. save the code to a file `get-duplicates.ps1`
2. run `.\get-duplicates.ps1 'a' 42 'b' 42 'a' 42`

Known issues: Powershell supress `$null` value. Result of

```
 .\get-duplicates.ps1 $null $null $false $false $true $true

```

is `False, True` without `null`.
> 2 votes

# Answer
# Java (JDK 10), 77 bytes

```
l->{java.util.Set.copyOf(l).forEach(l::remove);return l.stream().distinct();}

```

Try it online!
> 2 votes

# Answer
# Japt `-h`, 7 bytes

```
â £kX â

```

Try it online!

## Explanation:

```
â £kX â
â         // Get all unique items from the input
  £       // Map X through the results
   kX     //   Remove X from the input
      â   //   Get unique items
-h        // Return the last item

```
> 2 votes

# Answer
# Crystal, 42 bytes

```
def f(a)a.reject{|x|a.count(x)<2}.uniq
end

```

Try it online!

Sometimes, when you can't get the desired results, the problem can be solved... by running your code in a different language.

Initially, I tried solving this in Ruby, but ironically, despite the OP's statement that all test cases correspond to Ruby comparison rules, the above code when run in Ruby actually fails for the third test case, as both `uniq` and array intersection operator use stricter equality checks. However, it passes all tests in Crystal (which shares most of its syntax with Ruby) at the expense of having to declare it as a defined function (`->` proc would be longer in Crystal).

As a bonus, here is the golfier Ruby-only version of the code (doesn't pass test 3):

### Ruby, 33 bytes

```
->a{a.reject{|x|a.count(x)<2}|[]}

```

Try it online!
> 2 votes

# Answer
# Gaia, 4 bytes

```
:uDu

```

Try it online!

`:` duplicates the input, `u` uniquifies it, `D` retrieves the multiset difference between the two and `u` uniquifies the result.
> 1 votes

# Answer
# Husk, 4 bytes

```
uṠ-u

```

Try it online!

**Explanation**

```
     -- input, e.g. [2,1,1,3,2,2]
   u -- remove duplicates: [2,1,3]
 Ṡ-  -- subtract this from original list: [2,1,1,3,2,2] - [2,1,3] = [1,2,2]
u    -- remove duplicates: [1,2]

```
> 1 votes

# Answer
# Physica, 33 bytes

```
->a:Set@Filter[->e:a.count@e>1;a]

```

Try it online!
> 1 votes

# Answer
# Haskell, 33 bytes

```
nub.((\\)<*>nub)
import Data.List

```

Try it online! Port of my Husk answer.

The point-free version given above is equivalent to `f x=nub$x\\nub x` which is one byte longer.

---

### Haskell, 50 bytes

```
([]#)
a#(x:r)=([x|any(==x)r,all(/=x)a]++a)#r
a#_=a

```

Try it online! Alternative without imports.
> 1 votes

# Answer
# Stax, 5 bytes

```
═H+U(

```

Run and debug it

Explanation:

```
cu|-uJ Full program, unpacked
cu     Copy and make unique
  |-   Remove each element once
    u  Make unique again
     J Join by space. 'm' would be equally long, but as F has a lower charcode, it can be packed better.

```
> 1 votes

# Answer
# Retina, ~~23~~ 22 bytes

```
Lmsl`(.+)(?=.+^\1$)
D`

```

Try it online! Explanation:

```
Lmsl`(.+)(?=.+^\1$)

```

List duplicated lines. The `m` modifier allows the `^` and `$` to match the start and end of a line in the lookahead. The `s` modifier allows us to look ahead past newlines using just `.+`. The `l` modifier automatically anchors the match to whole lines. I can't use the `p` flag though as the match could be more than one line at once, however the next stage will deal with that.

```
D`

```

Deduplicate that list.
> 1 votes

# Answer
# Proton, 32 bytes

```
l=>set(v for v:l if~-l.count(v))

```

Try it online!

Port of TFeld's Python answer. Could be shorter but `{...}` apparently doesn't work for setcomps.
> 1 votes

# Answer
# Red, 46 bytes

```
func[b][foreach c unique b[alter b c]unique b]

```

Doesn't work for numbers in different representation as float or string.

Try it online!
> 1 votes

---
Tags: code-golf
---


title: Math Operations with Strings

text:
# Question
Title: Math Operations with Strings
# Challenge :

*Inspired by Alphabet Position Finder*

Given an string and one of two possible mathematical operator (`+` or `-`) as input, your task is to return the operation of each alphabet position from the string.

# Example :

```
Input: "Hello World", "+"
=> "Hello World" = [8, 5, 12, 12, 15, 23, 15, 18, 12, 4] (converted to their equivalents)
=> sum alphabet positions = [8 + 5 + 12 + 12 + 15 + 23 + 15 + 18 + 12 + 4]
Output: 124

```

---

# Note :

* Ignore non-alphabetical characters
* You must use 1-indexing (a = 1, b = 2, ..., z = 26)
* If empty string submitted return a falsy value
* Operator can be taken as `+`/`-`. `1`/`-1`, truthy/falsey, etc.

# Test Cases :

```
"Hello World", "-"             => -108
"I Love golfing", "+"          => 133
"She doesnt love you :(", "+"  => 224
"@#t%489/*-o", "-"             => 5
"", "-"                        => 0
"a", "-"                       => 1

```

# Answer
# Java (JDK 10), 79 bytes

```
s->o->{int r=0,i=0;for(int c:s)r+=(c&=95)%32*(c>64&c<91?i++<1?1:o:0);return r;}

```

Try it online!

### Original answer before the question was clarified

Java (JDK 10), 46 bytes
```
s->o->s.chars().reduce(0,(a,b)->a+b%32*(44-o))

```

Try it online!
> 3 votes

# Answer
# Python 2, ~~70~~ 66 bytes

```
lambda s,o:eval(o.join(`ord(c)%32`for c in s if c.isalpha())or'0')

```

Try it online!
> 2 votes

# Answer
# Japt 2.0 `-F0`, ~~19~~ 15 bytes

```
OvUf\l ®c %HÃqV

```

Test it online

## Explanation:

```
 OvUf\l ®c %HÃqV
 Ov                 // Japt eval:
   U                //   First input
    f\l             //   Match [A-Za-z]
        ®    Ã      //   Map; At each item:
         c          //     Char-Code
           %H       //     %32
              qV    //   Join with Second input (operator)
-F0                 // If the first input (string) is empty, output 0

```
> 1 votes

# Answer
# Japt v2.0a0, ~~12~~ 13 bytes

+1 bytes to handle empty strings :(

```
r\L ¬®c uHÃrV

```

Try it

Original 12 byte version which would be valid if an error counts as a falsey value.

```
f\L ®c uHÃrV

```

Try it

---

## Explanation

```
                  :Implicit input of string U and operator string V
r                 :Remove
 \L               : /[^a-z]/gi
    ¬             :Split
     ®            :Map
      c           :  Character code
        u         :  Modulo
         H        :   32
          Ã       :End map
           rV     :Reduce by V

```
> 1 votes

# Answer
# JavaScript (Node.js), 92 82 67 bytes

```
t=>o=>t?eval(t.match(/[a-z]/gi).map(x=>parseInt(x,36)-9).join(o)):0

```

Try it online!
> 0 votes

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

```
T=>_=>eval([...T].map(a=>a.charCodeAt()%32).join(_))

```

Try it online!

---

# Explanation :

```
T =>                            // first input for lambda function `text` (T)
    _ =>                        // second input, the separator
        eval(                   // evaluate a string
            [...T]              // conver `T` into a comma separated array of its char
            .map(a=>            // map over them `a` is representing the char
                a.charCodeAt()  // a.charCodeAt(0)
                    % 32)       // find remainder of it when divided by 32
                .join(_)        // and join them using the separator
        )                       // end eval

```

---

# Note :

This completely ignores non-alphabetic words since the challenge seems to change after every two minutes, I chose this. (Can be changed if OP wants me to)

---

I posted this on the other challenge, just changed .join to .join(o) :

# JavaScript (Node.js), 57 bytes

```
t=>o=>t.match(/[a-z]/gi).map(i=>parseInt(i,36)-9).join(o)

```

Try it online!

---
> 0 votes

# Answer
# 05AB1E, 9 bytes

```
áÇ32%Iý.E

```

Semi-port of *@JonathanAllan*'s 05AB1E answer for the linked challenge.
Outputs nothing as falsey values if the input doesn't contain any letters.

No TIO, because `.E` isn't on TIO yet. Here an alternative version that does `.E` manually `áÇ32%Iý“…¢(“s')J.e`: Try it online or verify all test cases.

**Explanation:**

```
á        # Only keep letters of the first input-string
         #  i.e. "Hello World" → "HelloWorld"
 Ç       # Get the list of the unicode values of each letter
         #  i.e. "HelloWorld" → [72,101,108,108,111,87,111,114,108,100]
  32%    # modulo-32 each
         #  i.e. [72,101,108,108,111,87,111,114,108,100] → [8,5,12,12,15,23,15,18,12,4]
Iý       # Join it with the operator input
         #  [8,5,12,12,15,23,15,18,12,4] and "-" → "8-5-12-12-15-23-15-18-12-4"
  .E     # Run it as Python-eval
         #  i.e. "8-5-12-12-15-23-15-18-12-4" → -108

```

More details on the commit of `.E`, prove it works, and the alternative version here in a similar answer of mine.
> 0 votes

# Answer
# CJam, 24 bytes

```
q~el{'`-_0>*}%{},0+':@+~

```

Try it online!

Could probably be more efficient, had to add 0 to the array to handle the empty string.
> 0 votes

# Answer
# Jelly, 10 bytes

```
ŒuØAiⱮḟ0jV

```

Try it online!

# Explanation

```
ŒuØAiⱮḟ0jV  Main link
Œu          Uppercase the input
     Ɱ      For each character
    i       take its index in
  ØA        the uppercase alphabet
      ḟ0    Filter; remove 0s
        j   String-join by the right element
         V  Evaluate

```

-4 bytes thanks to Mr. Xcoder
> 0 votes

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