title: Determinant of an Integer Matrix

text:
# Question
Title: Determinant of an Integer Matrix
Given a square integer matrix as input, output the determinant of the matrix.

## Rules

* You may assume that all elements in the matrix, the determinant of the matrix, and the total number of elements in the matrix are within the representable range of integers for your language.
* Outputting a decimal/float value with a fractional part of 0 is allowed (e.g. `42.0` instead of `42`).
* Builtins are allowed, but you are encouraged to include a solution that does not use builtins.

## Test Cases

```
[[42]] -> 42
[[2, 3], [1, 4]] -> 5
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] -> 0
[[13, 17, 24], [19, 1, 3], [-5, 4, 0]] -> 1533
[[372, -152, 244], [-97, -191, 185], [-53, -397, -126]] -> 46548380
[[100, -200, 58, 4], [1, -90, -55, -165], [-67, -83, 239, 182], [238, -283, 384, 392]] -> 571026450
[[432, 45, 330, 284, 276], [-492, 497, 133, -289, -28], [-443, -400, 56, 150, -316], [-344, 316, 92, 205, 104], [277, 307, -464, 244, -422]] -> -51446016699154
[[416, 66, 340, 250, -436, -146], [-464, 68, 104, 471, -335, -442], [159, -407, 310, -489, -248, 370], [62, 277, 446, -325, 47, -193], [460, 460, -418, -28, 234, -374], [249, 375, 489, 172, -423, 125]] -> 39153009069988024
[[-246, -142, 378, -156, -373, 444], [186, 186, -23, 50, 349, -413], [216, 1, -418, 38, 47, -192], [109, 345, -356, -296, -47, -498], [-283, 91, 258, 66, -127, 79], [218, 465, -420, -326, -445, 19]] -> -925012040475554
[[-192, 141, -349, 447, -403, -21, 34], [260, -307, -333, -373, -324, 144, -190], [301, 277, 25, 8, -177, 180, 405], [-406, -9, -318, 337, -118, 44, -123], [-207, 33, -189, -229, -196, 58, -491], [-426, 48, -24, 72, -250, 160, 359], [-208, 120, -385, 251, 322, -349, -448]] -> -4248003140052269106
[[80, 159, 362, -30, -24, -493, 410, 249, -11, -109], [-110, -123, -461, -34, -266, 199, -437, 445, 498, 96], [175, -405, 432, -7, 157, 169, 336, -276, 337, -200], [-106, -379, -157, -199, 123, -172, 141, 329, 158, 309], [-316, -239, 327, -29, -482, 294, -86, -326, 490, -295], [64, -201, -155, 238, 131, 182, -487, -462, -312, 196], [-297, -75, -206, 471, -94, -46, -378, 334, 407, -97], [-140, -137, 297, -372, 228, 318, 251, -93, 117, 286], [-95, -300, -419, 41, -140, -205, 29, -481, -372, -49], [-140, -281, -88, -13, -128, -264, 165, 261, -469, -62]] -> 297434936630444226910432057

```

# Answer
> 29 votes
# Jelly, 15 bytes

```
LŒ!ðŒcIṠ;ị"Pð€S

```

Try it online!

## How it works

```
LŒ!ðŒcIṠ;ị"Pð€S   input
L                 length
 Œ!               all_permutations
   ð        ð€    for each permutation:
    Œc                take all unordered pairs
      I               calculate the difference between
                      the two integers of each pair
       Ṡ              signum of each difference
                      (positive -> 1, negative -> -1)
        ;             append:
         ị"             the list of elements generated by taking
                        each row according to the index specified
                        by each entry of the permutation
           P          product of everything
              S   sum

```

## Why it works -- mathy version

The operator **det** takes a matrix and returns a scalar. An *n*-by-*n* matrix can be thought of as a collection of *n* vectors of length *n*, so **det** is really a function that takes *n* vectors from ℤ*n* and returns a scalar.

Therefore, I write **det**(*v*1, *v*2, *v*3, ..., *v**n*) for **det** \[*v*1 *v*2 *v*3 ... *v*n\].

Notice that **det** is linear in each argument, i.e. **det**(*v*1 \+ λ*w*1, *v*2, *v*3, ..., *v**n*) = **det**(*v*1, *v*2, *v*3, ..., *v**n*) + λ **det**(*w*1, *v*2, *v*3, ..., *v**n*). Therefore, it is a linear map from (ℤ*n*)*n* to ℤ.

It suffices to determine the image of the basis under the linear map. The basis of (ℤ*n*)*n* consists of *n*-fold tensor products of the basis elements of ℤ*n*, i.e. e.g. e5 ⊗ e3 ⊗ e1 ⊗ e5 ⊗ e1. Tensor products that include identical tensors must be sent to zero, since the determinant of a matrix in which two columns are identical is zero. It remains to check what the tensor products of distinct basis elements are sent to. The indices of the vectors in the tensor product form a bijection, i.e. a permutation, in which even permutations are sent to 1 and odd permutations are sent to -1.

For example, to find the determinant of \[\[1, 2\], \[3, 4\]\]: note that the columns are \[1, 3\] and \[2, 4\]. We decompose \[1, 3\] to give (1 e1 \+ 3 e2) and (2 e1 \+ 4 e2). The corresponding element in the tensor product is (1 e1 ⊗ 2 e1 \+ 1 e1 ⊗ 4 e2 \+ 3 e2 ⊗ 2 e1 \+ 3 e2 ⊗ 4 e2), which we simplify to (2 e1 ⊗ e1 \+ 4 e1 ⊗ e2 \+ 6 e2 ⊗ e1 \+ 12 e2 ⊗ e2). Therefore:

**det** \[\[1, 2\], \[3, 4\]\]
= **det**(1 e1 \+ 3 e2, 2 e1 \+ 4 e2)
= **det**(2 e1 ⊗ e1 \+ 4 e1 ⊗ e2 \+ 6 e2 ⊗ e1 \+ 12 e2 ⊗ e2)
= **det**(2 e1 ⊗ e1) + **det**(4 e1 ⊗ e2) + **det**(6 e2 ⊗ e1) + **det**(12 e2 ⊗ e2)
= 2 **det**(e1 ⊗ e1) + 4 **det**(e1 ⊗ e2) + 6 **det**(e2 ⊗ e1) + 12 **det**( e2 ⊗ e2)
= 2 (0) + 4 (1) + 6 (-1) + 12 (0)
= 4 - 6
= -2

Now it remains to prove that the formula for finding the parity of the permutation is valid. What my code does is essentially find the number of inversions, i.e. the places where an element on the left is bigger than an element on the right (not necessarily consecutively).

For example, in the permutation 3614572, there are 9 inversions (31, 32, 61, 64, 65, 62, 42, 52, 72), so the permutation is odd.

The justification is that each transposition (swapping two elements) either adds one inversion or takes away one inversion, swapping the parity of the number of inversions, and the parity of the permutation is the parity of the number of transpositions needed to achieve the permutation.

Therefore, in conclusion, our formula is given by:

## Why it works -- non-mathy version

where σ is a permutation of *n* the group of all permutations on *n* letters, and **sgn** is the sign of the permutation, AKA (-1) raised to the parity of the permutation, and *a**ij* is the (*ij*)th entry in the matrix (*i* down, *j* across).

# Answer
> 14 votes
# Jelly, ~~16~~ ~~15~~ ~~12~~ 10 bytes

```
Ḣ×Zß-Ƥ$Ṛḅ-

```

Uses Laplace expansion. *Thanks to @miles for golfing off ~~3~~ 5 bytes!*

Try it online!

### How it works

```
Ḣ×Zß-Ƥ$Ṛḅ-  Main link. Argument: M (matrix / 2D array)

Ḣ           Head; pop and yield the first row of M.
      $     Combine the two links to the left into a monadic chain.
  Z         Zip/transpose the matrix (M without its first row).
   ß-Ƥ      Recursively map the main link over all outfixes of length 1, i.e., over
            the transpose without each of its rows.
            This yields an empty array if M = [[x]].
 ×          Take the elementwise product of the first row and the result on the
            right hand. Due to Jelly's vectorizer, [x] × [] yields [x].
       Ṛ    Reverse the order of the products.
        ḅ-  Convert from base -1 to integer.
                [a]          -> (-1)**0*a
                [a, b]       -> (-1)**1*a + (-1)**0*b = b - a
                [a, b, c]    -> (-1)**2*a + (-1)**1*b + (-1)**0*c = c - b + a
                etc.

```

# Answer
> 12 votes
# , 3 bytes

*Trivial Solution*

```
det

```

Try it online!

# , ~~94~~ ~~92~~ 89 bytes

*re-implemented solution*

*outgolfed by Jarko Dubbeldam*

```
d=function(m)"if"(x<-nrow(m),m[,1]%*%sapply(1:x,function(y)(-1)^y*-d(m[-y,-1,drop=F])),1)

```

Try it online!

Recursively uses expansion by minors down the first column of the matrix.

```
f <- function(m){
 x <- nrow(m)                 # number of rows of the matrix
 if(sum(x) > 1){              # when the recursion reaches a 1x1, it has 0 rows
                              # b/c [] drops attributes
  minor <- function(y){
   m[y] * (-1)^y *
   -d(m[-y,-1])                # recurse with the yth row and first column dropped
   }
  minors <- sapply(1:x,minor) # call on each row
  sum(minors)                 # return the sum
 } else {
  m                           # return the 1x1 matrix
 }
}

```

# Answer
> 11 votes
# Haskell, 71 bytes

*-3 bytes thanks to Lynn. Another one bytes the dust thanks to Craig Roy.*

```
f[]=1
f(h:t)=foldr1(-)[v*f[take i l++drop(i+1)l|l<-t]|(i,v)<-zip[0..]h]

```

Try it online! *Added `-O` flag for optimization purposes. It is not necessary.*

## Explanation (outdated)

`f` recursively implements cofactor expansion.

```
f[[x]]=x

```

This line covers the base case of a **1** × **1** matrix, in which case the determinant is `mat[0, 0]`.

```
f(h:t)=

```

This uses Haskell's *pattern matching* to break the matrix into a *head* (the first row) and a *tail* (the rest of the matrix).

```
          [                                     |(i,v)<-zip[0..]h]

```

Enumerate the head of the matrix (by zipping the infinite list of whole numbers and the head) and iterate over it.

```
           (-1)*i*v

```

Negate the result based on whether its index is even since the calculation of the determinant involves alternating addition and subtraction.

```
                     [take i l++drop(i+1)l|l<-t]

```

This essentially removes the **ith** column of the tail by taking **i** elements and concatenating it with the row with the first **(i + 1)th** elements dropped for every row in the tail.

```
                   *f

```

Calculate the determinant of the result above and multiply it with the result of `(-1)*i*v`.

```
       sum

```

Sum the result of the list above and return it.

# Answer
> 8 votes
## Wolfram Language (Mathematica), between 14 and 42 bytes

We've had a 3-byte built-in and a 53-byte solution that completely avoids built-ins, so here are some weirder solutions somewhere in between.

The Wolfram Language has a lot of very intense functions for decomposing matrices into products of other matrices with simpler structure. One of the simpler ones (meaning I've heard of it before) is Jordan decomposition. Every matrix is similar to a (possibly complex-valued) upper triangular matrix made of diagonal blocks with a specific structure, called the Jordan decomposition of that matrix. Similarity preserves determinants, and the determinant of a triangular matrix is the product of the diagonal elements, so we can compute the determinant with the following **42 bytes**:

```
1##&@@Diagonal@Last@JordanDecomposition@#&

```

The determinant is also equal to the product of the eigenvalues of a matrix, with multiplicity. Luckily, Wolfram's eigenvalue function keeps track of multiplicity (even for non-diagonalisable matrices), so we get the following **20 byte** solution:

```
1##&@@Eigenvalues@#&

```

The next solution is kind of cheating and I'm not really sure why it works. The Wronskian of a list of *n* functions is the determinant of the matrix of the first *n*-1 derivatives of the functions. If we give the `Wronskian` function a matrix of integers and say that the variable of differentiation is 1, somehow it spits out the determinant of the matrix. It's weird, but it doesn't involve the letters "`Det`" and it's only **14 bytes**

```
#~Wronskian~1&

```

(The Casoratian determinant works as well, for 1 more byte: `#~Casoratian~1&`)

In the realm of abstract algebra, the determinant of an *n* x *n* matrix (thought of as the map k → k that is multiplication by the determinant) is the *n*th exterior power of the matrix (after picking an isomorphism k → ⋀n kn). In Wolfram language, we can do this with the following **26 bytes**:

```
HodgeDual[TensorWedge@@#]&

```

And here's a solution that works for positive determinants only. If we take an *n*-dimensional unit hypercube and apply a linear transformation to it, the *n*-dimensional "volume" of the resulting region is the absolute value of the determinant of the transformation. Applying a linear transformation to a cube gives a parallelepiped, and we can take its volume with the following **39 bytes** of code:

```
RegionMeasure@Parallelepiped[Last@#,#]&

```

# Answer
> 6 votes
# Proton, 98 bytes

```
f=m=>(l=len(m))-1?sum((-1)**i*m[0][i]*f([[m[k][j]for k:1..l]for j:0..l if j-i])for i:0..l):m[0][0]

```

Try it online!

-3 bytes thanks to Mr. Xcoder
-3 bytes thanks to Erik the Outgolfer
-1 byte thanks to S.S. Anne

Expansion over the first row

# Answer
> 6 votes
# Haskell, 59 bytes

```
p%(l:r)=l!!0*f(tail<$>p++r)-(p++[l])%r
[]%_=1
p%_=0
f=([]%)

```

Try it online!

# Answer
> 5 votes
# C,  ~~176~~  125 bytes

*Thanks to @ceilingcat for golfing 42 bytes, and thanks to both @Lynn and @Jonathan Frech for saving a byte each!*

```
d(M,n)int*M;{int i=n--,s=*M*!n,c,T[n*n];for(;i--;s+=M[i]*(1-i%2*2)*d(T,n))for(c=n*n;c--;T[c]=M[n-~c+c/n+(c%n>=i)]);return s;}

```

Calculates the determinant using the Laplace expansion along the first row.

Try it online!

**Unrolled:**

```
d(M, n)int*M;
{
    int i=n--, s=*M*!n, c, T[n*n];
    for (; i--; s+=M[i]*(1-i%2*2)*d(T,n))
        for (c=n*n; c--;)
            T[c] = M[n-~c+c/n+(c%n>=i)];
    return s;
}

```

# Answer
> 5 votes
# Jelly, 43 bytes

Finally I've done writing my non-builtin solution in a golfing language!

```
ḣ⁹’’¤;ṫḊ€Ç×⁸ị@⁹’¤¤ḷ/¤
çÐ€⁸J‘¤µJ-*×NS
ÇḢḢ$Ṗ?

```

Thanks to *HyperNeutrino* for saving a byte!

Try it online! (spaced code for clarity)

*terribly long way to remove n'th elements from a list, will improve later*

---

This answer had been outgolfed by answers of HyperNeutrino, Dennis and Leaky Nun. Jelly is *very* popular as a golfing language.

Quick explanation:

```
ÇḢḢ$Ṗ?    Main link.
     ?    If
    Ṗ     after remove the last element, the value is not empty (truthy)
Ç         then execute the last link
 ḢḢ$      else get the element at index [1, 1].

çÐ€⁸J‘¤µJ-*×NS     Helper link 1, take input as a matrix.
çÐ€                Apply the previous link, thread right argument to
   ⁸J‘¤            the range [2, 3, ..., n+1]
       µ           With the result,
        J-*        generate the range [-1, 1, -1, 1, ...] with that length
           ×N      Multiply by negative
             S     Sum

ḣ⁹’’¤;ṫḊ€Ç×⁸ị@⁹’¤¤ḷ/¤    Helper link 2, take left input as a matrix, right input as a number in range [2..n+1]
ḣ
 ⁹’’¤                    Take head ρ-2 of the matrix
     ;                   concatenate with
      ṫ                  tail ρ (that is, remove item ρ-1)
       Ḋ€                Remove first column
         Ç               Calculate determinant of remaining matrix
          ×         ¤    multiply by
                  ḷ/     the first column,
            ị@           row #
              ⁹’¤        ρ-1 (just removed in determinant calculation routine) of
           ⁸     ¤       the matrix.

```

# Answer
> 5 votes
# Jelly, 24 bytes

```
œcL’$ṚÑ€
J-*×Ḣ€×ÇSµḢḢ$Ṗ?

```

Try it online!

# Explanation

```
œcL’$ṚÑ€         Helper Link; get the next level of subdeterminants (for Laplace Expansion)
œc               Combinations without replacement of length:
  L’$            Length of input - 1 (this will get all submatrices, except it's reversed)
     Ṛ           Reverse the whole thing
      Ñ€         Get the determinant of each of these
J-*×Ḣ€×ÇSµḢḢ$Ṗ?  Main Link
              ?  If the next value is truthy
             Ṗ   Remove the last element (truthy if the matrix was at least size 2)
J-*×Ḣ€×ÇSµ       Then expand
          ḢḢ$    Otherwise, get the first element of the first element (m[0][0] in Python)
J                [1, 2, ..., len(z)]
 -*              (-1 ** z) for each z in the length range
   ×             Vectorizing multiply with
    Ḣ€           The first element of each (this gets the first column); modifies each row (makes it golfier yay)
      ×Ç         Vectorizing multiply with the subdeterminants
        S        Sum

```

-2 bytes thanks to user202729's solution

# Answer
> 5 votes
# , 32 bytes

```
function(m)Re(prod(eigen(m)$va))

```

Uses Not a Tree's algorithm of taking the eigenvalues of the matrix and taking the real part of their product.

Try it online!

# Answer
> 5 votes
## CJam (50 45 bytes)

```
{:A_,{1$_,,.=1b\)/:CAff*A@zf{\f.*1fb}..-}/;C}

```

This is an anonymous block (function) which takes a 2D array on the stack and leaves an integer on the stack.

Online test suite

### Dissection

This implements the Faddeev-LeVerrier algorithm, and I think it's the first answer to take that approach.

> The objective is to calculate the coefficients \\$c\_k\\$ of the characteristic polynomial of the \\$n\times n\\$ matrix \\$A\\$, $$p(\lambda )\equiv \det(\lambda I\_{n}-A)=\sum \_{k=0}^{n}c\_{k}\lambda ^{k}$$ where, evidently, \\$c\_n = 1\\$ and \\$c\_0 = (−1)^n \det A\\$.
>
> The coefficients are determined recursively from the top down, by dint of the auxiliary matrices \\$M\\$, $$\begin{aligned}M\_{0}&\equiv 0&c\_{n}&=1\qquad &(k=0)\\M\_{k}&\equiv AM\_{k-1}+c\_{n-k+1}I\qquad \qquad &c\_{n-k}&=-{\frac {1}{k}}\mathrm {tr} (AM\_{k})\qquad &k=1,\ldots ,n~.\end{aligned}$$

The code never works directly with \\$c\_{n-k}\\$ and \\$M\_k\\$, but always with \\$(-1)^k c\_{n-k}\\$ and \\$(-1)^{k+1}AM\_k\\$, so the recurrence is $$(-1)^k c\_{n-k} = \frac1k \mathrm{tr} ((-1)^{k+1} AM\_{k}) \\ (-1)^{k+2} AM\_{k+1} = (-1)^k c\_{n-k}A - A((-1)^{k+1}A M\_k)$$

```
{               e# Define a block
  :A            e#   Store the input matrix in A
  _,            e#   Take the length of a copy
  {             e#     for i = 0 to n-1
                e#       Stack: (-1)^{i+2}AM_{i+1} i
    1$_,,.=1b   e#       Calculate tr((-1)^{i+2}AM_{i+1})
    \)/:C       e#       Divide by (i+1) and store in C
    Aff*        e#       Multiply by A
    A@          e#       Push a copy of A, bring (-1)^{i+2}AM_{i+1} to the top
    zf{\f.*1fb} e#       Matrix multiplication
    ..-         e#       Matrix subtraction
  }/
  ;             e#   Pop (-1)^{n+2}AM_{n+1} (which incidentally is 0)
  C             e#   Fetch the last stored value of C
}

```

# Answer
> 4 votes
# MATL, 3 bytes / 5 bytes

### With built-in function

```
&0|

```

Try it online!

### Without built-in

*Thanks to Misha Lavrov for pointing out a mistake, now corrected*

```
YvpYo

```

Try it online!

This computes the determinant as the product of the eigenvalues, rounded to the closest integer to avoid floating-point inaccuracies.

```
Yv       % Implicit input. Push vector containing the eigenvalues
p        % Product
Yo       % Round. Implicit display

```

# Answer
> 4 votes
# Octave, 28 bytes

```
@(x)round(prod(diag(qr(x))))

```

Try it online!

This uses the QR decomposition of a matrix **X** into an orthgonal matrix **Q** and an upper triangular matrix **R**. The determinant of **X** is the product of those of **Q** and **R**. An orthogonal matrix has unit determinant, and for a triangular matrix the determinant is the product of its diagonal entries. Octave's `qr` function called with a single output gives **R**.

The result is rounded to the closest integer. For large input matrices, floating-point inaccuracies may produce an error exceeding `0.5` and thus produce a wrong result.

# Answer
> 3 votes
# Octave, 30 bytes

```
@(x)-prod(diag([~,l,~]=lu(x)))

```

Try it online!

or, the boring 4 byte solution (saved 6 bytes thanks to Luis Mendo (forgot the rules regaring builtin functions)):

```
@det

```

### Explanation:

Coming up! :)

# Answer
> 3 votes
# TI-Basic, 2 bytes

```
det(Ans

```

Ah, well.

Please don't upvote trivial answers.

As a high school student (who's forced to own one of these calculators), this function is hella useful so...

# Answer
> 3 votes
# Wolfram Language (Mathematica), ~~53~~ 52 bytes

```
1##&@@@(t=Tuples)@#.Signature/@t[Range@Tr[1^#]&/@#]&

```

Try it online!

Unfortunately, computing the determinant of an *n* by *n* matrix this way uses O(*n**n*) memory, which puts large test cases out of reach.

## How it works

The first part, `1##&@@@(t=Tuples)@#`, computes all possible products of a term from each row of the given matrix. `t[Range@Tr[1^#]&/@#]` gives a list of the same length whose elements are things like `{3,2,1}` or `{2,2,3}` saying which entry of each row we picked out for the corresponding product.

We apply `Signature` to the second list, which maps even permutations to `1`, odd permutations to `-1`, and non-permutations to `0`. This is precisely the coefficient with which the corresponding product appears in the determinant.

Finally, we take the dot product of the two lists.

---

If even `Signature` is too much of a built-in, at **73 bytes** we can take

```
1##&@@@(t=Tuples)@#.(1##&@@Order@@@#~Subsets~{2}&/@t[Range@Tr[1^#]&/@#])&

```

replacing it by `1##&@@Order@@@#~Subsets~{2}&`. This computes `Signature` of a possibly-permutation by taking the product of `Order` applied to all pairs of elements of the permutation. `Order` will give `1` if the pair is in ascending order, `-1` if it's in descending order, and `0` if they're equal.

---

*-1 byte thanks to @user202729*

# Answer
> 3 votes
# Haskell, 62 bytes

```
a#((b:c):r)=b*d(a++map tail r)-(a++[c])#r
_#_=0
d[]=1
d l=[]#l

```

Try it online! (Footer with test cases taken from @totallyhuman's solution.)

`d` computes the determinant using a Laplace expansion along the first column. Needs three bytes more than the permanent.

# Answer
> 3 votes
# Python 2, 75 bytes

```
f=lambda m,p=[]:m[0][0]*f(zip(*p+m[1:])[1:])-f(m[1:],p+m[:1])if m else[]==p

```

Try it online!

# Answer
> 3 votes
# Java (OpenJDK 8), ~~195 192 177~~ 176 bytes

```
long d(int[][]m){long D=0;for(int i=m.length,l=i-1,t[][]=new int[l][l],j,k;i-->0;D+=m[0][i]*(1-i%2*2)*(l<1?1:d(t)))for(j=l*l;j-->0;)t[j/l][k=j%l]=m[1+j/l][k<i?k:k+1];return D;}

```

Try it online!

Like many other answers, this also uses the Laplace formula. A slightly less golfed version:

```
long d(int[][]m){
  long D=0;
  int i=m.length,l=i-1,t[][]=new int[l][l],j,k
  for(;i-->0;)
    for(j=l*l;j-->0;)
      t[j/l][k=j%l]=m[1+j/l][k<i?k:k+1];
    D+=m[0][i]*(1-i%2*2)*(l<1?1:d(t));
  return D;
}

```

# Answer
> 2 votes
# Wolfram Language (Mathematica), 3 bytes

```
Det

```

Try it online!

Per the meta consensus, mainly upvote nontrivial solutions that take effort to write.

# Answer
> 2 votes
# Python 3, ~~**238 bytes**~~, ~~**227 bytes**~~, ~~**224 bytes**~~, **216 bytes**

```
from functools import*
from itertools import*
r=range;n=len;s=sum
f=lambda l:s(reduce(lambda p,m:p*m,[l[a][b]for a,b in zip(r(n(l)),j)])*(-1)**s(s(y<j[x]for y in j[x:])for x in r(n(l)))for j in permutations(r(n(l))))

```

Try it online!

My solution uses the definition of a determinant for calculations. Unfortunately, the complexity of this algorithm is `n!` and I can not show the passage of the last test, but in theory this is possible.

# Answer
> 2 votes
# Python 2, 95 bytes

*-12 bytes thanks to Lynn.*

Port of my Haskell answer.

```
f=lambda m:sum((-1)**i*v*f([j[:i]+j[i+1:]for j in m[1:]])for i,v in enumerate(m[0]))if m else 1

```

Try it online!

# Answer
> 2 votes
# Java 8, ~~266~~ ~~261~~ ~~259~~ 258 bytes

```
long d(int[][]m){long r=0;int i=0,j,k,l=m.length,t[][]=new int[l-1][l-1],q=m[0][0];if(l<3)return l<2?q:q*m[1][1]-m[0][1]*m[1][0];for(;i<l;r+=m[0][i]*(1-i++%2*2)*d(t))for(j=0;++j<l;)for(k=l;k-->0;){q=m[j][k];if(k<i)t[j-1][k]=q;if(k>i)t[j-1][k-1]=q;}return r;}

```

Look mom, no build-ins.. because Java has none.. \>.\>

-7 bytes thanks to *@ceilingcat*.

**Explanation:**

Try it here. (Only the last test case is too big to fit in a `long` of size 263-1.)

```
long d(int[][]m){             // Method with integer-matrix parameter and long return-type
  long r=0;                   //  Return-long, starting at 0
  int i=0,j,k,                //  Index-integers
      l=m.length,             //  Dimensions of the square matrix
      t[][]=new int[l-1][l-1],//  Temp-matrix, one size smaller than `m`
      q=m[0][0];              //  The first value in the matrix (to reduce bytes)
  if(l<3)                     //  If the dimensions are 1 or 2:
    return l<2?               //   If the dimensions are 1:
      q                       //    Simply return the only item in it
     :                        //   Else (the dimensions are 2):
      q*m[1][1]-m[0][1]*m[1][0];
                              //    Calculate the determinant of the 2x2 matrix
                              //  If the dimensions are 3 or larger:
  for(;i<l;                   //  Loop (1) from 0 to `l` (exclusive)
      r+=                     //    After every iteration: add the following to the result:
         m[0][i]              //     The item in the first row and `i`'th column,
         *(1-i++%2*2)         //     multiplied by 1 if `i` is even; -1 if odd,
         *d(t))               //     multiplied by a recursive call with the temp-matrix
    for(j=0;                  //   Reset index `j` to 0
        ++j<l;)               //   Inner loop (2) from 0 to `l` (exclusive)
      for(k=l;k-->0;){        //    Inner loop (3) from `l-1` to 0 (inclusive)
        q=m[j][k];            //     Set the integer at location `j,k` to reduce bytes
        if(k<i)               //     If `k` is smaller than `i`:
          t[j-1][k]=q;        //      Set this integer at location `j-1,k`
        if(k>i)               //     Else-if `k` is larger than `i`:
          t[j-1][k-1]=q;      //      Set this integer at location `j-1,k-1`
                              //     Else: `k` and `i` are equals: do nothing (implicit)
      }                       //    End of inner loop (3)
                              //   End of inner loop (2) (implicit / single-line body)
                              //  End of loop (1) (implicit / single-line body)
  return r;                   //  Return the result-long
}                             // End of method

```

# Answer
> 2 votes
# JavaScript (ES6), 91

Recursive Laplace

```
q=(a,s=1)=>+a||a.reduce((v,[r],i)=>v-(s=-s)*r*q(a.map(r=>r.slice(1)).filter((r,j)=>j-i)),0)

```

*Less golfed*

```
q = (a,s=1) => // s used as a local variable
  a[1] // check if a is a single element array
       // if array, recursive call expanding along 1st column
  ? a.reduce((v,[r],i) => v-(s=-s)*r*q(a.map(r=>r.slice(1)).filter((r,j)=>j-i)),0)
  : +a // single element, convert to number

```

**Test**

```
q=(a,s=1)=>+a||a.reduce((v,[r],i)=>v-(s=-s)*r*q(a.map(r=>r.slice(1)).filter((r,j)=>j-i)),0)

TestCases=`[[42]] -> 42
[[2, 3], [1, 4]] -> 5
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] -> 0
[[13, 17, 24], [19, 1, 3], [-5, 4, 0]] -> 1533
[[372, -152, 244], [-97, -191, 185], [-53, -397, -126]] -> 46548380
[[100, -200, 58, 4], [1, -90, -55, -165], [-67, -83, 239, 182], [238, -283, 384, 392]] -> 571026450
[[432, 45, 330, 284, 276], [-492, 497, 133, -289, -28], [-443, -400, 56, 150, -316], [-344, 316, 92, 205, 104], [277, 307, -464, 244, -422]] -> -51446016699154`
.split('\n')

TestCases.forEach(r=>{
  [a,k] = r.split (' -> ')
  a = eval(a)
  d = q(a)
  console.log('Test '+(k==d ? 'OK':'KO')+
    '\nMatrix '+a.join('|')+
    '\nResult '+d+
    '\nCheck  '+k)
})
```

# Answer
> 2 votes
## SageMath, various

Here are a bunch of methods for computing the determinant that I found interesting, all programmed in SageMath. They can all be tried here.

### Builtin, 3 bytes

```
det

```

This one isn't too interesting. Sage provides global-level aliases to many common operations that would normally be object methods, so this is shorter than `lambda m:m.det()`.

---

### Real Part of Product of Eigenvalues, 36 bytes

```
lambda m:real(prod(m.eigenvalues()))

```

Unfortunately, `eigenvalues` is not one of those global-level aliases. That, combined with the fact that Sage doesn't have a neat way to compose functions, means we're stuck with a costly `lambda`. This function symbolic values which are automatically converted to numeric values when printed, so some floating point inaccuracy may be present in some outputs.

---

### Product of Diagonal in Jordan Normal Form, 60 bytes

```
lambda m:prod(m.jordan_form()[x,x]for x in range(m.nrows()))

```

In Jordan Normal form, an NxN matrix is represented as a block matrix, with N blocks on the diagonal. Each block consists of either a single eigenvalue, or a MxM matrix with a repeated eigenvalue on the diagonal and `1`s on the super-diagonal (the diagonal above and to the right of the "main" diagonal). This results in a matrix with all eigenvalues (with multiplicity) on the main diagonal, and some `1`s on the super-diagonal corresponding to repeated eigenvalues. This returns the product of the diagonal of the Jordan normal form, which is the product of the eigenvalues (with multiplicty), so this is a more roundabout way of performing the same computation as the previous solution.

Because Sage wants the Jordan normal form to be over the same ring as the original matrix, this only works if all of the eigenvalues are rational. Complex eigenvalues result in an error (unless the original matrix is over the ring `CDF` (complex double floats) or `SR`). However, this means that taking the real part is not necessary, compared to the above solution.

---

### Product of Diagonal in Smith Decomposition

```
lambda m:prod(m.smith_form()[0].diagonal())

```

Unlike Jordan normal form, Smith normal form is guaranteed to be over the same field as the original matrix. Rather than computing the eigenvalues and representing them with a block diagonal matrix, Smith decomposition computes the elementary divisors of the matrix (which is a topic a bit too complicated for this post), puts them into a diagonal matrix `D`, and computes two matrices with unit determinant `U` and `V` such that `D = U*A*V` (where `A` is the original matrix). Since the determinant of the product of matrices equals the product of the determinants of the matrices (`det(A*B*...) = det(A)*det(B)*...`), and `U` and `V` are defined to have unit determinants, `det(D) = det(A)`. The determinant of a diagonal matrix is simply the product of the elements on the diagonal.

### Laplace Expansion, 109 bytes

```
lambda m:m.nrows()>1and sum((-1)**j*m[0,j]*L(m[1:,:j].augment(m[1:,j+1:]))for j in range(m.ncols()))or m[0,0]

```

This performs Laplace expansion along the first row, using a recursive approach. `det([[a]]) = a` is used for the base case. It should be shorter to use `det([[]]) = 1` for the base case, but my attempt at that implementation had a bug that I haven't been able to track down yet.

---

### Leibniz's Formula, 100 bytes

```
L2 = lambda m:sum(sgn(p)*prod(m[k,p[k]-1]for k in range(m.ncols()))for p in Permutations(m.ncols()))

```

This directly implements Leibniz's formula. For a much better explanation of the formula and why it works than I could possibly write, see this excellent answer.

---

### Real Part of `e^(Tr(ln(M)))`, 48 bytes

```
lambda m:real(exp(sum(map(ln,m.eigenvalues()))))

```

This function returns symbolic expressions. To get a numerical approximation, call `n(result)` before printing.

This is an approach that I haven't seen anyone use yet. I'm going to give a longer, more-detailed explanation for this one.

Let `A` be a square matrix over the reals. By definition, the determinant of `A` is equal to the product of the eigenvalues of `A`. The trace of `A` is equal to the sum of `A`'s eigenvalues. For real numbers `r_1` and `r_2`, `exp(r_1) * exp(r_2) = exp(r_1 + r_2)`. Since the matrix exponential function is defined to be analogous to the scalar exponential function (especially in the previous identity), and the matrix exponential can be computed by diagonalizing the matrix and applying the scalar exponential function to the eigenvalues on the diagonal, we can say `det(exp(A)) = exp(trace(A))` (the product of `exp(λ)` for each eigenvalue `λ` of `A` equals the sum of the eigenvalues of `exp(A)`). Thus, if we can find a matrix `L` such that `exp(L) = A`, we can compute `det(A) = exp(trace(L))`.

We can find such a matrix `L` by computing `log(A)`. The matrix logarithm can be computed in the same way as the matrix exponential: form a square diagonal matrix by applying the scalar logarithm function to each eigenvalue of `A` (this is why we restriced `A` to the reals). Since we only care about the trace of `L`, we can skip the construction and just directly sum the exponentials of the eigenvalues. The eigenvalues can be complex, even if the matrix isn't over the complex ring, so we take the real part of the sum.

# Answer
> 1 votes
# Python 2 \+ numpy, 29 bytes

```
from numpy.linalg import*
det

```

Try it online!

# Answer
> 1 votes
# Julia, 3 bytes

```
det

```

Try it online!

# Answer
> 1 votes
# Pari/GP, 6 bytes

```
matdet

```

Try it online!

---

# Pari/GP, 52 bytes

```
f(a)=if(#a,sum(n=1,#a,-(-1)^n*a[1,n]*f(a[^1,^n])),1)

```

Try it online!

# Answer
> 0 votes
# Jelly, 2 bytes

```
ÆḊ

```

Try it online!

~~Currently only built-in solution. :(~~ Looks like others have managed to find out interesting non-built-in solutions.

# Answer
> 0 votes
# Excel VBA, ~~58~~ 50 Bytes

Returns the determinant of the matrix entered into the the upper left corner of the default `Sheet1` object.

```
?Evaluate("MDeterm("+Sheet1.UsedRange.Address+")")

```

-8 Bytes thanks to Greedo

# Answer
> 0 votes
# , 5 bytes

```
-/ .*

```

Try it online!

# Answer
> 0 votes
# MY, 3 (4?) bytes

```
ω∥↵

```

Try it online!

Precision is a little weird (the second test case is 5.000000000000001), this can be fixed at a cost of one byte: `ω∥⌊↵`

# Answer
> 0 votes
# TI-Basic (83 series), ~~137~~ 133 bytes

```
Ans→[A]
For(N,max(dim(Ans)),2,-1
 Matr▶list(Ans,N,C
 1+sum(not(cumSum(not(not(∟C→R
 If R>N
 Then
  0[A]→[A]
 Else
  rowSwap([A],R,N
  *row(cos(π(R≠N))Ans(N,N),Ans,1
  *row(-Ans(N,N)⁻¹,Ans,N
  For(I,1,N
   *row+(Ans(I,N),Ans,N,I→[A]
  End
 End
End
Ans(1,1

```

(Indentation is purely decorative and doesn't appear on the calculator.)

Instead of the built-in `det(`, does row reduction by hand. The pivots are built backwards, starting at the (*n*,*n*)th entry and going back to the (1,1)th (or is that (1,1)st?).

Every time we need to divide by a number to set the pivot to 1, we multiply the first row by the same number (possibly negated, if we needed to swap rows), so that the determinant of the matrix stays the same. (If we didn't find a pivot, we zero out the entire matrix.) As a result, at the end, the ~~(1,1)th~~ ~~(1,1)st~~ top left entry holds the determinant.

# Answer
> 0 votes
## Python 3, ~~153~~ 149 Bytes

```
def d(n):
 l=len(n);r=range(0,l)
 if l==1:return n[0][0]
 else:return sum([(-1)**i*n[0][i]*d([[n[a][b]for b in r if b!=i]for a in r[1:]])for i in r])

```

I'm new to code golf, so I wouldn't be surprised if this could be improved. It's calculated in a pretty basic way; by summing the product of each element of the first row with the determinant of its respective minor, with a sign change based on the element's position.

Edit: Realized I could shorten it by using a single character for the function name :/

# Answer
> 0 votes
## Clojure, 141 bytes

```
(fn D[A](apply +(map *(cycle[1 -1])(first A)(if(next A)(for[R[(range(count A))]i R](D(for[a(rest A)](for[j(remove #{i}R)](nth a j)))))[1]))))

```

Laplace's formula, longer than I'd like...

# Answer
> 0 votes
# APL(NARS), 64 chars, 128 bytes

```
{1≥k←↑⍴w←⍵:⍵⋄2=k:-/⌽w[2;]×⌽w[1;]⋄v←⍳k⋄-/w[1;]×∇¨{w[v∼1;v∼⍵]}¨⍳k}

```

This would be the formula used in the schools, it is easy, much easier than i tought... if w is a 2x2 matrix -/⌽w\[2;\]×⌽w\[1;\] rotate first row multiply with second row than reverse and make difference in pratice it does: (w\[1;1\]×w\[2;2\])-w\[1;2\]×w\[2;1\] else if it is a matrix nxn with n\>2 multiply the first row with its adjunt Matrix (if i remember well the name), and make -/; test:

```
  D←{1≥k←↑⍴w←⍵:⍵⋄2=k:-/⌽w[2;]×⌽w[1;]⋄v←⍳k⋄-/w[1;]×∇¨{w[v∼1;v∼⍵]}¨⍳k}
  D ⊃(1 9 3)(4 ¯5  6)(7 8 9)
162
  D 3 3 ⍴ ⍳20
0
  D ⊃(1 0)(0 1)
1
  D ,89
89
  D  1
1
  D 'ac'
RANK ERROR

```

# Answer
> 0 votes
# 05AB1E, 23 bytes

```
ā<œε©2.ÆíÆ.±Iε®Nèè}«P}O

```

Port of *@LeakyNun*'s Jelly answer.

Try it online or verify all but one test cases (the biggest test case times out on TIO).

**Explanation:**

```
ā             # Push a list in the range [1, (implicit) input-length]
 <            # Decrease it by 1 to make the range [0, input-length)
  œ           # Get all permutations of this list
   ε          # Map each permutation to:
    ©         #  Store the permutation in variable `®` (without popping)
     2.Æ      #  Get all 2-element combinations of this list
        í     #  Reverse each inner list
         Æ    #  Reduce each by subtraction
          .±  #  And take their signum (-1 if a<0; 0 if a==0; 1 if a>0)
    I         #  Push the input
     ε        #  Map each row to:
      ®       #   Get the current permutation from variable `®`
       Nè     #   Use the map-index to index into this permutation
         è    #   And use that to index into the row
     }«       #  After the map: merge the two lists together
       P      #  And take its product
   }O         # After the outer map: sum all value
              # (after which it is output implicitly as result)

```

# Answer
> 0 votes
# Maple, 11 bytes

Documentaiton

```
Determinant

```

```
LinearAlgebra[Determinant](Matrix([[2, 3, 1], [3, 2, 3], [0, 3, 2]]));
LinearAlgebra[Determinant](LinearAlgebra[HilbertMatrix](4));

```

---
Tags: code-golf, math, array, matrix, linear-algebra
---


title: Is it a plausible chess move?

text:
# Question
Title: Is it a plausible chess move?
*Not a duplicate of the valid move challenge because that asks for specific pieces*.

## Backstory

The other night I was doing a little trolling with ChatGPT and chess. I was trying to get it to call me out for making illegal moves, as a lot of the time, you can feed it whatever nonsense you want. While doing so, I wondered if it didn't recognise invalid moves because they were technically valid under some board arrangement. I then thought I'd make a code golf challenge.

## The Challenge

Given a start and end square on an 8x8 chess board, determine whether the move is possible on any legal chess board.

Alternatively, can any kind of piece make a move from the start square to the end square.

## Chess Pieces

For this challenge, you only need to know how the knight and queen move. King and pawn moves can be considered equivalent to a queen moving a single square. A rook move is a queen move restricted to vertical and horizontal movement. A bishop move is a queen move restricted to diagonal movement. Castling and En Passant (holy hell) aren't relevant either.

A valid move from the square highlighted in red is any square marked with a green circle:

This includes the vertical, horizontal and diagonal movement of the queen, as well as the L-shaped movement of the knight.

## Rules

* The positions will be given in algebraic chess notation (letter then number of the square).
* The start and end squares will never be the same square.
* The start and end squares will always be valid squares on an 8x8 chess board.
* Positions can be given in any reasonable and convenient format, including:
    + Strings (e.g. `["f4", "b8"]`)
    + A list of strings (e.g. `[["f", "4"], ["b", "8"]]`)
    + A list of numbers that represent the character codes of each string item (e.g. `[[102, 52], [98, 56]]`)
    + A string, number pairs (e.g. `[["f", 4], ["b", 8]]`)
    + A list of row/column pairs (e.g `[[5, 3], [1, 7]]` OR `[[6, 4], [2, 8]]`). Can be 0-indexed or 1-indexed. Your choice.
* Output in any reasonable and convenient format.
* This is , so make sure your answer is as short as possible.

## Test Cases

```
start, end -> plausible?
a1, a4 -> True
b2, d3 -> True
b2, e3 -> False
b2, c3 -> True
a1, h8 -> True
c7, g3 -> True
c7, g2 -> False

```

# Answer
> 15 votes
# Octave, 24 bytes

```
@(a,b)imag((a-b)**4)<28i

```

Try it online!

Takes two complex numbers as inputs.

## How?

Port of @xnor's python answer plus a trick or two by myself.

Trick 1:

@xnor's test polynomial a^3b-b^3a times 4i is the imaginary part of (a+ib)^4 = a^4 + 4i a^3b - 6a^2b^2 - 4i ab^3 + b^4

*Note:* a and b here as defined in @xnor's code; in my code they have a slightly different meaning.

Trick 2:

Octave implicitly takes absolute values before comparing complex numbers. We abuse that by comparing to 28i instead of 28 to save an explicit call to abs.

# Answer
> 15 votes
# Python 2, 29 bytes

```
lambda a,b:abs((a-b)**4%1)<28

```

Try it online!

Based on @xnor's answer. Takes two complex numbers as input.

# Python 2, 42 bytes

```
lambda x,y,X,Y:abs((X-x+1j*(Y-y))**4%1)<28

```

Try it online!

The same with less opportunistic input format (4 integers).

## How?

Recall that in polar coordinates complex multiplication adds angles.

Therefore all queen-like moves (and only those) when taken to 4th power will end up on the real axis, i.e. have vanishing imaginary part.

Explicitly, if the difference of source and destination is \\$x+yi\\$ then the imaginary part of its fourth power is \\$4 \times \left( x^3y - x y^3\right)\\$ which happens to be @xnor's test polynomial (up to the prefactor 4). As observed by @xnor this has absolute value (4x) 6 at knight's moves and greater for all other (non-queen) moves.

Implementation detail: In Python 2 but not 3 the imaginary part can be isolated by `%1`.

# Answer
> 12 votes
# Python 3, 47 bytes

```
lambda x,y,X,Y:-7<(a:=X-x)*(b:=Y-y)*(a*a-b*b)<7

```

Try it online!

Test cases from mousetail.

**Python 2, 49 bytes**

```
lambda x,y,X,Y:-7<(X-x)**3*(Y-y)-(X-x)*(Y-y)**3<7

```

Try it online!

No walrus here.

# Answer
> 8 votes
# JavaScript (ES6), 42 bytes

Expects `(x0,y0,x1,y1)`, where all arguments are integers. They can be 0-indexed coordinates, 1-indexed coordinates or ASCII codes.

Returns a Boolean value.

```
(x,y,X,Y)=>!((x-=X)*x+(y-=Y)*y-5&&x/y^y/x)

```

Try it online!

### Commented

```
(                //
  x, y,          // (x, y) = coordinates of source square
  X, Y           // (X, Y) = coordinates of target square
) =>             //
!(               //
  (x -= X) * x + // we compute x = x - X and y = y - Y
  (y -= Y) * y   // if the squared Euclidean distance x² + y²
  - 5            // is not equal to 5, this is not a knight move
  &&             //
  x / y ^ y / x  // we compute x / y and y / x
                 // XOR'ing both terms together gives 0 if:
                 // - either x = 0 or y = 0 (rook move), in which case one
                 //   of the terms is ±infinity and the other one is 0
                 //   (see note below)
                 // - x = ±y (bishop move), in which case both terms are
)                //   equal

```

### Note

According to the ECMAScript specification of NumberBitwiseOp(*op*, *x*, *y*), the arguments of a bitwise operation are first converted with the abstract operation ToInt32(*argument*) whose first two steps are:

> 1. Let *number* be ? ToNumber(*argument*).
> 2. If *number* is \\$\text{NaN}\\$, \\$+0\_\mathbb{F}\\$, \\$-0\_\mathbb{F}\\$, \\$+\infty\_\mathbb{F}\\$, or \\$-\infty\_\mathbb{F}\\$, return \\$+0\_\mathbb{F}\\$.

That's why `±infinity ^ 0` is `0`.

# Answer
> 8 votes
# 05AB1E, ~~12~~ 8 bytes

```
αDËsP3‹~

```

-4 bytes porting *AndrovT*'s Vyxal answer.

Input as two pairs of codepoints.

Try it online or verify all test cases or verify every single pair of chessboard positions.

**Original 12 bytes answer:**
Port of *@Arnauld*'s JavaScript answer.

```
αW_snDO5QsËM

```

Input as two pairs of codepoints.

Try it online or verify all test cases or verify every single pair of chessboard positions.

**Explanation:**

```
              #  first input ("f4"): [102,52]; second input ("b8"): [98,56]
α             # Absolute difference of the values in the two (implicit) input-pairs
              #  [abs(98-102),abs(56-52)] → STACK: [4,4]
 D            # Duplicate the pair
              #  STACK: [4,4],[4,4]
  Ë           # Check if the values in the pair are the same
              #  STACK: [4,4],1
   s          # Swap so the pair is at the top of the stack again
              #  STACK: 1,[4,4]
    P         # Take the product of the pair
              #  STACK: 1,16
     3‹       # Check whether this is smaller than 3 (thus 0, 1 or 2)
              #  STACK: 1,0
       ~      # Bitwise-OR to check either of the two is truthy
              #  STACK: 1
              # (after which the top of the stack is output implicitly as result)

```

```
              #  first input ("f4"): [102,52]; second input ("b8"): [98,56]
α             # Absolute difference of the values in the two (implicit) input-pairs
              #  [abs(98-102),abs(56-52)] → STACK: [4,4]
 W            # Get the minimum (without popping)
              #  STACK: [4,4],4
  _           # Check if this minimum is 0 (1 if 0; 0 otherwise)
              #  STACK: [4,4],0
   s          # Swap so the earlier pair is at the top again
              #  STACK: 0,[4,4]
    n         # Take the square of both values
              #  STACK: 0,[16,16]
     D        # Duplicate this pair
              #  STACK: 0,[16,16],[16,16]
      O       # Sum the copy
              #  STACK: 0,[16,16],32
       5Q     # Check whether this sum is equal to 5 (1 if 5; 0 otherwise)
              #  STACK: 0,[16,16],0
         s    # Swap so the earlier squared pair is at the top again
              #  STACK: 0,0,[16,16]
          Ë   # Check whether both values in the pair are the same
              #  STACK: 0,0,1
           M  # Push the largest value on the stack, to check if any is truthy
              #  STACK: 0,0,1,1
              # (after which the top of the stack is output implicitly as result)

```

# Answer
> 7 votes
# Vyxal, ~~7~~ 6 bytes

```
εꜝ2v∴≈

```

Try it Online!

*-1 byte by @Johnathan Allan*

Takes input as two pairs of numbers.

```
εꜝ2v∴≈
ε      # absolute difference
 ꜝ     # keep truthy
  2v∴  # vectorized maximum with 2
     ≈ # are all equal?

```

# Answer
> 5 votes
# T-SQL, 63 bytes

input is a table

```
SELECT 1/~((a-c)*(b-d)/3*(a-c)*(b-d)*(abs(a-c)-abs(b-d)))FROM @

```

**Try it online**

# Answer
> 4 votes
# Jelly, 6 bytes

```
ạḟ0»2E

```

A dyadic Link that accepts one cell reference on the left and the other on the right, each as a pair of integers\* and yields `1` if plausible or `0` if not.

* The indexing of the inputs does not matter so long as it is unscaled and the two pairs use consistent indexing; they could also be the ordinals of the characters (since only files and ranks, individually, need to have equivalent indexing).

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

### How?

```
ạḟ0»2E - Link: A=[StartRow, StartFile]; B=[EndRow, EndFile]
ạ      - absolute difference (vectorises)
           -> [abs(StartRow-EndRow), abs(StartFile-EndFile)]
 ḟ0    - filter out zeros -- remove the zero from any rook move
   »2  - max with two (vectorises) -- cast king/horsey moves to 2 step queen moves
     E - all equal? -- are we left with a queen move, or < 2 elements (was a rook)?

```

# Answer
> 3 votes
# Excel, ~~77~~ 72 bytes

```
=LET(
    a,INDIRECT(A1&":"&B1),
    b,ROWS(a),
    c,COLUMNS(a),
    OR(b=1,c=1,b=c,b*c=6)
)

```

Expects strings (e.g. "f4", "b8") in cells `A1` and `B1`. Returns a Boolean.

# Answer
> 3 votes
# Charcoal, 23 bytes

```
Ｆ²⊞υＮＵＭυ↔⁻ιＮ⊞υ↔↨υ±¹‹Πυ³

```

Try it online! Link is to verbose version of code. Takes input as four integers and outputs a Charcoal boolean, i.e. `-` for plausible, nothing if not. Explanation: Inspired by @xnor's Python answer.

```
Ｆ²⊞υＮ

```

Input the first pair of coordinates.

```
ＵＭυ↔⁻ιＮ

```

Take the absolute difference of them and the second pair of coordinates.

```
⊞υ↔↨υ±¹

```

Push the absolute difference of the two absolute differences.

```
‹Πυ³

```

Test whether the product is less than `3`.

22 bytes with some evaluate hackery to port @loopywalt's Octave answer:

```
‹↔ＵＶ⁺Ｘ↨Ｅ⁴ＮＵＶ1j⁴.imag²⁵

```

Try it online! Link is to verbose version of code. Takes input as four integers and outputs a Charcoal boolean, i.e. `-` for plausible, nothing if not. Explanation:

```
        ⁴               Literal integer `4`
       Ｅ                Map over implicit range
         Ｎ              Next input number
      ↨                  Interpret as base
             1j          Literal string `1j`
           ＵＶ            Evaluate as Python
     Ｘ                  Raised to power
              ⁴         Literal integer `4`
    ⁺                   Concatenated with
               .imag    Literal string `.imag`
  ＵＶ                    Evaluate as Python
 ↔                      Absolute value
‹                       Is less than
                    ²⁵  Literal integer `25`
                        Implicitly print

```

# Answer
> 2 votes
# Python, ~~78~~ 73 bytes

```
lambda i,j:((a:=abs(i[0]-j[0]))==(b:=abs(i[1]-j[1])))|(a<1)|(b<1)|(a<3>b)

```

Attempt This Online!

# Python, 65 bytes

Alternate input format, credit to 97.100.97.109

```
lambda u,v,x,y:((a:=abs(u-x))==(b:=abs(v-y)))|(a<1)|(b<1)|(a<3>b)

```

Attempt This Online!

# Answer
> 2 votes
# Retina 0.8.2, 67 bytes

```
(.)(.)(.)(.)
$1$*1-$3$*1,$2$*1-$4$*
(1+)-\1

^1..1$|^(1+),\1$|^,|,$

```

Try it online! Takes input as a string of four digits but test suite converts from test case format for convenience. Explanation:

```
(.)(.)(.)(.)
$1$*1-$3$*1,$2$*1-$4$*

```

Convert to unary, preparing to subtract the `x` and `y` coordinates from each other.

```
(1+)-\1

```

Take the absolute difference of both the `x` and `y` coordinates.

```
^1..1$|^(1+),\1$|^,|,$

```

Match either a knight move, a bishop move, or one of two possible rook moves.

# Answer
> 2 votes
# Scala, ~~237~~ 221 bytes

Saved 16 bytes thanks to the comment.

Golfed version. Try it online!

```
type S=String
type I=Int
def f(a:S,b:S)={def s(s:S)={(s(0).toInt-'a'.toInt,8-s(1).asDigit)};def v(x:I,y:I,c:I,d:I)={val xD=x-c;val yD=y-d;xD*xD+yD*yD==5||xD==0||yD==0||xD*xD==yD*yD};val(x,y)=s(a);val(c,d)=s(b);v(x,y,c,d)}

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    val testCases = List(
      ("a1", "a4"), // True
      ("b2", "d3"), // True
      ("b2", "e3"), // False
      ("b2", "c3"), // True
      ("a1", "h8"), // True
      ("c7", "g3"), // True
      ("c7", "g2")  // False
    )

    testCases.foreach { case (a, b) =>
      val (x1, y1) = squareCoordinates(a)
      val (x2, y2) = squareCoordinates(b)
      println(s"$a $b ${isValidMove(x1, y1, x2, y2)}")
    }
  }

  def squareCoordinates(s: String): (Int, Int) = {
    (s(0).toInt - 'a'.toInt, 8 - s(1).asDigit)
  }

  def isValidMove(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = {
    val xDiff = x1 - x2
    val yDiff = y1 - y2
    xDiff * xDiff + yDiff * yDiff == 5 || xDiff == 0 || yDiff == 0 || xDiff * xDiff == yDiff * yDiff
  }
}

```

# Answer
> 2 votes
# Thunno 2, 9 bytes

```
-ADạsp2©|

```

Port of AndrovT's Vyxal answer.

#### Explanation

```
-ADạsp2©|  # Implicit input
-A         # Absolute difference
  D        # Duplicate
   ạ       # All are equal?
    s      # Swap
     p     # Product
      2©   # Less than or equal to 2
        |  # Logical or
           # Implicit output

```

# Answer
> 2 votes
# , 17 15 14 bytes

```
[:(=+.3>*)/|@-

```

Try it online!

*Port of Neil's Charcoal / xnor's Python answers*

*Also -1 thanks to an idea from AndrovT's answer*

# , original, 21 bytes

```
1 e.(*:^:4@*,5=|*|)@-

```

Try it online!

*5 idea from Arnauld's answer*

For the rest, we take the difference between in the inputs as complex numbers, normalize the vector, then square it 4 times. If the original vector was on one of the compass directions (rook) or one of the diagonals (queen/bishop), it will eventually settle at 1.

We then check if the result is 1 or 5.

# Answer
> 1 votes
# Nekomata \+ `-e`, 7 bytes

```
-AZ‼2M≡

```

Attempt This Online!

A port of @Jonathan Allan's Jelly answer.

```
-AZ‼2M≡
-A          Absolute difference
  Z‼        Remove zeros
    2M      Max with 2
      ≡     All equal?

```

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


title: Which weekday was it?

text:
# Question
Title: Which weekday was it?
This challenge, I hope, is simple to understand. Given a date-string (given in any format you prefer, **so long as it has 4 digits of year and 2 digits of day and month**), calculate the weekday for the particular date-string. You must output 7 different values, corresponding to the weekday you have calculated.

It's okay if your program only theoretically (given enough time and memory) prints the correct weekday, as long as it can calculate for years between 2000 and 2002.

If you're using a built-in, consider adding a non-built-in approach as well. Built-in solutions won't be considered for being accepted.

Make sure to account for leap years!

## Test cases

Input format is `DD/MM/YYYY`, output is one of `Su, Mo, Tu, We, Th, Fr, Sa` (both can be adjusted for your choice)

```
Input -> Output
12/11/2001 -> Mo
29/02/2000 -> Tu
04/07/2002 -> Th
11/08/2000 -> Fr

```

This is , so shortest answer wins!

**EDIT**: When I said "No built-ins", I meant that *built-ins that automatically calculate the weekday for a particular date* were *discouraged*, not prohibited. If the built-in aids in finding the weekday, no problem, but if it directly calculates the weekday then I *discourage* it.

# Answer
# Nibbles, ~~21~~ ~~20.5~~ ~~16.5~~ 15.5 bytes (31 nibbles)

*Edit: -4 bytes thanks to Arnauld*

```
%-+/*23@9+_$?-@2 2/%_3~7

```

Saturday is `0` ... Friday is `6`.

Uses Arnauld's simplified approach.

```
%-+/*23@9+_$?-@2 2/%_3~7
    *23@                     # month times 23
   /    9                    # integer-divided by 9
  +                          # add this to
         +_$                 # the year plus the day
 -                           # and subtract
            ?-@2             # if the month is ≤2
                 2           # 2
                             # otherwise
                   %_3       # year modulo 3
                  /   ~      # integer-divided by 2
%                      7     # finally, modulo 7

```
> 2 votes

# Answer
# Excel (ms365), 12 bytes

```
=WEEKDAY(A1)

```

Outputs numbers \[1-7\] where Sunday == 1;

---

# Excel (ms365), 14 bytes

```
=WEEKDAY(A1,2)

```

Outputs numbers \[1-7\] where Monday == 1:

---

# Excel (ms365), 15 bytes

```
=TEXT(A1,"ddd")

```

Outputs lowercase text \[mo-su\]:

---

# Excel (ms365), 23 bytes

```
=PROPER(TEXT(A1,"ddd"))

```

Outputs text \[Mo-Su\] capitalizing the first letter:

---

**Note:** Excel will recognize the date-strings as actual dates. Therefor having date-strings and date-numbers would have the same effect.
> 10 votes

# Answer
# , ~~31~~ 30 bytes

*Edit: doesn't beat Robin Ryder's answer but at least (currently) ties it*

```
function(s)el(as.Date(s):1)%%7

```

Try it online!

Semi built-in solution. Thursday is `0`, and then cycles through `1`-`6`.
> 8 votes

# Answer
# , ~~30~~ 27 bytes

-3 bytes thanks to naffetS

```
function(s)strftime(s,"%A")

```

Try it online!

3 bytes shorter than the alternate R solution.

The natural solution would be to use `format(as.Date(s), "%A")`, which converts `s` to the `Date` class then displays only the weekday. Luckily, the `strftime` is a wrapper for this, saving a few bytes.
> 7 votes

# Answer
# 05AB1E, ~~36~~ ~~24~~ ~~22~~ ~~21~~ 19 bytes

```
4Ö2‚I3@è³¹²23*9÷Æ7%

```

-12 bytes thanks to *@DominicVanEssen* (and *@Neil*) for reminding me that the challenge years are guaranteed to be 2000-2002
-2 bytes porting *@Arnauld*'s JavaScript (top) answer, so make sure to upvote him as well!
-1 byte thanks to *@DominicVanEssen* again in *@Arnauld*'s port
-2 bytes taking three loose inputs instead of a triplet

Three loose input-integers in the order `yyyy,MM,dd`; output is an integer where `6` = Sunday, `5` = Monday, ..., `0` = Saturday.

Try it online or verify all test cases.

**Explanation:**

```
4Ö       # Check if the (implicit) first input-year is divisible by 4
  2‚     # Pair this 0 or 1 with 2
    I    # Push the second input-month
     3@  # Check if it's >=3
       è # Use that to index into the pair
³        # Push the third input-day
 ¹       # Push the first input-year
  ²      # Push the second input-month
   23*   # Multiply the month by 23
      9÷ # Integer-divided by 9
Æ        # Reduce the entire stack by subtracting:
         #  [m%4<1,2][m>=3]-d-y-m*23//9
 7%      # Modulo-7, resulting in 6 to 0 for Sunday to Saturday

```

---

**Original ~~36~~ 24 bytes answer:**

```
`UD3‹©12*+>₂*T÷®XαD4÷O7%

```

Try it online or verify all test cases.

**Explanation:**

05AB1E lacks any date builtins (except for the current year/month/day/etc.), so everything is done manually using Zeller's congruence, taken from this earlier 05AB1E answer of mine:

The formula to do this is:

$${\displaystyle h=\left(q+\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor+K+\left\lfloor{\frac{K}{4}}\right\rfloor+\left\lfloor{\frac{J}{4}}\right\rfloor-2J\right){\bmod{7}}}$$

Where for the months March through December:

* \\$q\\$ is the \\$day\\$ of the month (`[1, 31]`)
* \\$m\\$ is the 1-indexed \\$month\\$ (`[3, 12]`)
* \\$K\\$ is the year of the century (\\$year \bmod 100\\$)
* \\$J\\$ is the 0-indexed century (\\$\left\lfloor {\frac {year}{100}}\right\rfloor\\$)

And for the months January and February:

* \\$q\\$ is the \\$day\\$ of the month (`[1, 31]`)
* \\$m\\$ is the 1-indexed \\$month + 12\\$ (`[13, 14]`)
* \\$K\\$ is the year of the century for the previous year (\\$(year - 1) \bmod 100\\$)
* \\$J\\$ is the 0-indexed century for the previous year (\\$\left\lfloor {\frac {year-1}{100}}\right\rfloor\\$)

Resulting in the day of the week \\$h\\$, where 0 = Saturday, 1 = Sunday, ..., 6 = Friday.

But, since the challenge states the year is guaranteed to be 2000-2002, we can simplify the formula to this instead:

$${\displaystyle h=\left(q+\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor+K+\left\lfloor{\frac{K}{4}}\right\rfloor\right){\bmod{7}}}$$

Resulting in the day of the week \\$h\\$, where 0 = Friday, 1 = Saturday, ..., 6 = Thursday.

As for the actual program:

```
`           # Push the day, month, and year of the (implicit) input-triplet to the stack
 U          # Pop and save the year in variable `X`
  D         # Duplicate the month
   3‹       # Check if the month is below 3 (Jan. / Feb.),
            # resulting in 1 or 0 for truthy/falsey respectively
     ©      # Store this in variable `®` (without popping)
      12*   # Multiply it by 12 (either 0 or 12)
         +  # And add it to the month
            # This first part was to make Jan. / Feb. 13 and 14

>           # Month + 1
 ₂*         # Multiplied by 26
   T÷       # Integer-divided by 10
®           # Push month<3 from variable `®` again
 Xα         # Take the absolute difference with the year
D4÷         # mYear, integer-divided by 4
O           # Sum all values on the stack together
 7%         # And then take modulo-7 to complete the formula,
            # resulting in 0 to 6 for Friday to Thursday
            # (which is output implicitly as result)

```
> 7 votes

# Answer
# Red, 13 bytes

```
func[d][d/10]

```

Try it online!

Returns `1` to `7`, Monday is 1

# Red, 46 bytes

```
func[d][take/part system/locale/days/(d/10) 2]

```

Try it online!

Returns `Mo Tu We Th Fr Sa Su`

Red's `date!` datatype has `weekday` accessor that is also aliased by index 10. So for a date `d` we can write `d/weekday` or shorter `d/10`
> 6 votes

# Answer
# JavaScript (ES6), 38 bytes

This is an attempt at solving the challenge without a built-in, using a formula optimized for 2000-2002.

Expects `(year, month, day)`. Returns \\$0\\$ for Sunday, \\$1\\$ for Monday, ..., \\$6\\$ for Saturday.

```
(y,m,d)=>~((m<3?y%4<1:2)-d-y-23*m/9)%7

```

Try it online!

### Commented

This is based on the following C code by Michael Keith and Tom Craver:

```
(d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7

```

Wikipedia article

```
(y, m, d) =>    // y = year, m = month, d = day
~(              // take the ones' complement of:
  (             //   conditional offset:
    m < 3 ?     //     if this is January or February:
      y % 4 < 1 //       use 1 if this is 2000
                //       (which is a leap year)
                //       or 0 otherwise
    :           //     else:
      2         //       use 2
  )             //
  - d           //   subtract the non-conditional offset:
  - y           //     d + y + 23 * m / 9
  - 23 * m / 9  //
) % 7           // apply modulo 7

```
> 5 votes

# Answer
# Python 3, 49 bytes

```
lambda*t:date(*t).weekday()
from datetime import*

```

Try it online!

Represents mon-sun as 0-6
> 4 votes

# Answer
# Bash, ~~14~~ 13 bytes

```
date -d$1 +%u

```

Try it online!

*Saved a byte thanks to Steffan!!!*

Inputs the date as `YYYY-MM-DD` and returns \\$1\\$ for Monday, \\$2\\$ for Tuesday, up to \\$7\\$ for Sunday.
> 4 votes

# Answer
# Mathematica, 7 bytes

```
DayName

```

## Mathematica (without `DayName`), ~~49~~ ~~42~~ 38 bytes

```
First@DateDifference[{1,1,1},#]~Mod~7&

```

View it on Wolfram Cloud!

Takes dates in `MM/DD/YYYY` format (will complain if the date happens to be parsable as `DD/MM/YYYY`, but it still outputs the correct answer). `DayName` returns the full name of the weekday. The other answer returns 0 for Monday, 1 for Tuesday, up to 6 for Sunday.

The non-`DayName` answer can probably still be golfed a decent amount, I'm pretty new to Mathematica.
> 4 votes

# Answer
# Excel, 10 bytes

```
=MOD(A1,7)

```

Returns `0W/01/1900` where `W` is `0``6` for Saturday–Friday.
> 4 votes

# Answer
# JavaScript (Node.js), ~~16~~ 6 bytes

Takes datetime object as input, per OP.

Takes date as `YYYY-MM-DD` and returns 0–6 for Thursday–Wednesday.

```
d=>d%7

```

### Old solution with string input

```
s=>new Date(s)%7

```

Try it online!
> 4 votes

# Answer
# Factor, 11 bytes

```
day-of-week

```

Try it online!

Takes input as a `timestamp`. Outputs an integer `0-6` signifying `Sunday-Saturday`.
> 3 votes

# Answer
# APL(Dyalog Unicode), 7 bytes SBCS

Anonymous tacit prefix function taking date as `YYYY MM DD`.

```
7|1⎕DT⊂

```

Try it on APLgolf!

enclose to make a scalar date

`1⎕DT` convert to Dyalog Day Number (days since 1899-12-31)

`7|` remainder when divided by 7 (gives 0–6 for Sunday–Saturday)
> 3 votes

# Answer
# Ruby, ~~22~~ 21 bytes

Takes input as an array like `[Y,M,D]` and returns a number from `0` (Sunday) to `6` (Saturday).

-1 byte thanks to Dingus

```
->d{Time.gm(*d).wday}

```

Attempt This Online!
> 2 votes

# Answer
# PowerShell, 16 bytes

```
%{date $_|% D*k}

```

Try it online!

Input comes from the pipeline. Straightforward:

```
%{date $_|% D*k}
%{             }  # % is an alias for ForEach-Object; the loop variable in the ScriptBlock "{}" is $_
  date $_         # pass the string as input to Get-Date, which will return a DateTime object
         |% D*k   # pipe the DateTime object to ForEach-Object, this time not with a ScriptBlock, but instead calls the member DayOfWeek
                  # Output is implicit

```

**Disclaimer:** This drops the `Get-` from `Get-Date`; if PS finds no other command with that name, it will try to add `Get-` and find the cmdlet `Get-Date`; don't use this in regular scripts, as the search for the command will slow it down.
> 2 votes

# Answer
## JS, ~~23~~ 13 bytes

Passed as string

```
s=>new Date(s).getDay()

```

Passed as object, per OP

```
d=>d.getDay()

```
> 2 votes

# Answer
# MATL, 3 bytes

```
8XO

```

Input format is `YYYY/MM/DD`.

Try it online! Or verify all test cases.
> 2 votes

# Answer
# Julia 1.0, ~~41~~ 39 bytes

```
using Dates;!d=Dates.dayofweek(Date(d))

```

Try it online!

*Saved 2 bytes thanks to Steffan!*

Returns 1 for Monday, 2 for Tuesday, up to 7 for Sunday.
> 2 votes

# Answer
# Vyxal, ~~29~~ 21 bytes

```
4Ḋ2"?3≥i???23*9ḭWƒ-7%

```

Try it Online!

Port of 05AB1E.
> 2 votes

# Answer
# Go, ~~96~~ 85 bytes

```
import."time"
func f(d string)int{e,_:=Parse("02/01/2006",d);return int(e.Weekday())}

```

Attempt This Online!

Hoo ray for verbose builtins!

* -11 bytes for returning an `int` (@Steffan)
> 1 votes

# Answer
# Nim, 47 bytes

```
import times,sugar
x=>x.parse"ddMMyyyy".weekday

```

Try it online!

It takes the date in the format `ddMMyyyy` and prints the full name of the weekday.
> 1 votes

# Answer
# PHP, 33 bytes

```
<?=date('l',strtotime($argv[1]));

```

Try it online!
> 1 votes

# Answer
# APL(Dyalog Unicode) REPL, 0 bytes

Takes date as `7|1⎕DT⊂YYYY MM DD` and gives 0–6 for Sunday–Saturday

Try it on TryAPL!

This abuses OP ruling that a valid input format can contain the code that solves the problem. For an explanation, see my other APL answer.
> 1 votes

# Answer
# jq, 17 characters

```
strptime("%F")[6]

```

Input: YYYY-MM-DD
Output: 0 = Sunday .. 6 = Saturday

Sample run:

```
bash-5.1$ jq -R 'strptime("%F")[6]' <<< '2012-05-04'   # manatwork joined CGCC
5

```

Try it online! / Try all test cases online!
> 0 votes

# Answer
# Rust + chrono, ~~58~~ 21 bytes

```
chrono::Date::weekday

```

Playground

An expression that can be coerced to a `fn(&Date<Utc>)->Weekday`. It takes a Date object and returns Weekday, an enum with 7 possible values.
> 0 votes

# Answer
# Java, 13 bytes

```
d->d.getDay()

```

A `Function<java.util.Date, Integer>`. Returns 0 for Sunday, 1 for Monday, ..., 6 for Saturday.
> 0 votes

# Answer
# Japt, 4 bytes

Input as a string in the format `yyyy-mm-dd` (or any valid JavaScript date string), output as a 3 letter abbreviation.

```
3îÐU

```

Try it

```
3îÐU     :Implicit input of string U
3î       :Slice to length 3
  ÐU     :Construct date object from U

```

**Note:** This is locale/browser dependent. For the included test case, for example, the date object is expected to return `Mon Nov 12 2001 00:00:00 GMT+0000 (Greenwich Mean Time)`.
> 0 votes

# Answer
# Thunno 2 `t`, 22 bytes

```
4Ḋ2,$3®i⁶°¹23×9÷KrƲ-7%

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
                        # implicit input
4Ḋ                      # divisible by 4
  2,                    # pair with 2
    $                   # next input
     3®                 # greater than or equal to 3
       i                # indexing
        ⁶               # third input
         °              # first input
          ¹             # second input
           23×          # multiply by 23
              9÷        # floor divide by 9
                Kr      # push the stack
                  Ʋ     # cumulative reduce by:
                   -    #  subtraction
                    7%  # modulo 7
                        # implicit output of tail

```
> 0 votes

# Answer
# Python 3, 69 bytes

```
lambda y,m,d:((d+((y+y//4)+(0x562ad0e6c0>>m*3&7)))-(m<3)*(y%4<1)+6)%7

```

Try it online!
> 0 votes

# Answer
# Scala, with java packages, 70 bytes

Golfed version. Try it online!

```
LocalDate.parse(_, DateTimeFormatter.ISO_DATE).getDayOfWeek.getValue%7

```

Ungolfed version. Try it online!

```
import java.time.{LocalDate, ZoneId}
import java.time.format.DateTimeFormatter

object Main {
  def main(args: Array[String]): Unit = {
    println(day("2023-05-27"))
    println(day("today"))
  }

  def day(s: String): Int = {
    val date = s match {
      case "today" => LocalDate.now(ZoneId.systemDefault())
      case _ => LocalDate.parse(s, DateTimeFormatter.ISO_DATE)
    }
    date.getDayOfWeek.getValue % 7
  }
}

```
> 0 votes

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


title: Solve an Anagram

text:
# Question
Title: Solve an Anagram
*See also: Granma loves Ana*

You will be given a string of lowercase ASCII letters. Using this dictionary file (UPDATED), your task is to solve the anagram. To solve an anagram, you must output all words or groups of words that can be formed using each letter from the input string exactly once, separated by newlines. Groups of the same words in a different order are not unique and should not be output separately; however, the order of the words **does not matter**. The order of output solutions also **does not matter**. If the input cannot form a word, output nothing.

Some useful test cases:

```
Input:  viinlg
Output: living

Input:  fceodglo
Output: code golf

Input:  flogflog
Output: golf golf

Input:  ahwhygi
Output: highway
        high way

Input:  bbbbbb
Output:

```

Rules/caveats:

* You may access the dictionary list any way you like. Command line argument, stdin, reading from file, or reading from internet are all acceptable.
* Input will consist of lowercase ASCII letters only. You are not required to output results in any particular case.
* You will not be given a string that already forms a valid word (you may, however, be given a string that forms *multiple* words, such as `bluehouse`).
* Trailing newlines are allowed but not required.
* Standard loopholes apply.

This is . Shortest code in bytes wins. Good luck!

# Answer
# Python 2, ~~341~~ ~~327~~ ~~337~~ 320 bytes

This solution assumes the dictionary is stored in a variable `w` as a set of strings. The first set of `combinations` does not need to use `combinations_with_replacement`, but using the latter saves bytes.

```
from itertools import*
d,o,j,c={},sorted,''.join,combinations_with_replacement
s,w=o(raw_input()),input()
l=len(s)
r=range(l)
for x in w:d.setdefault(j(o(x)),[]).append(x)
b=set(chain(*[d[j(x)]for y in r for x in c(s,y+1)if j(x) in d]))
print'\n'.join(' '.join(x)for y in r for x in c(b,y+1)if(len(j(x)),o(j(x)))==(l,s))

```

Try it online!

**Input -** Anagrammed word followed by the dictionary of words as a set:

```
anagram_word
{'entry1', 'entry2', ...., 'entryN'}

```

**Edit:** Updated Inputs.
> 2 votes

# Answer
# Python 3, ~~248~~ 202 bytes

```
from itertools import*
A=set()
def f(s,*G,i=1,A=A):
 if' '>s:A|={' '.join(sorted(G))}
 for _ in s:s[:i]in S and f(s[i:],s[:i],*G);i+=1
I,*S=iter(input,'')
for p in permutations(I):f(''.join(p))
print(A)

```

Try it online!

### Input is as follows:

```
word_input
dic_entry_1
dic_entry_2
....
dic_entry_N
                 # <<< empty line + \n

```

### Speeding it up:

For testing purposes, if you change from `I,*S=iter(input,'')` to `I=input();S=set(iter(input,''))`, the runtime will be reduced drastically and the output will be the same.

### Explanation:

In every permutation of the input, it tries to split recursively the permutation in all possible locations, starting from left to right, without skipping letters, with words that are in the dictionary. If a split combination matches all the input permutation, the split words are sorted and added to a `set` that will be printed at the and of the evaluation.
> 1 votes

# Answer
# Javascript, ~~139~~ ~~137~~ 129 Bytes

-2 Bytes thanks to @FelipeNardiBatista

-8 Bytes thanks to reading the docs ;)

```
k=>w=>{t=w;return k.reduce((a,v)=>{r=([...v].every(c=>w.includes(c)&&((w=w.replace(c,""))||!0)))?a.concat(v):a;w=t;return r},[])}

```

Takes in the dictionary as input in form of an array of strings.

```
var arr = ["living", "code", "golf", "highway", "high", "way"];

var _=
k=>w=>{t=w;return k.reduce((a,v)=>{r=([...v].every(c=>w.includes(c)&&((w=w.replace(c,""))||!0)))?a.concat(v):a;w=t;return r},[])};

console.log(_(arr)("viinlg"));
console.log(_(arr)("fceodglo"));
```

**Explanation:**

For every word in dictionary, check if every letter is contained in the chosen word, while simultaneously removing it from the word. At the end of every dictionary entry, restore the word to its unaltered state to check for further matches.
> 1 votes

# Answer
# Vyxal `j`, 82 bitsv2, 10.25 bytes

```
ð+Þ×vṠ'sṠ⁰s=

```

Try it Online! Makes sure to output all acronyms with a single space to separate.
> 1 votes

# Answer
# Scala, 156 bytes

Golfed version. Try it online!

```
(l:Seq[String],k:String)=>l.filter(w=>w.foldLeft((k,true)){case((r,b),c)=>val i=r.indexOf(c);if(i>=0)(r.substring(0,i)+r.substring(i+1),b)else(r,false)}._2)

```

Ungolfed version. Try it online!

```
object Main {
  def main(args: Array[String]): Unit = {
    val arr = List("living", "code", "golf", "highway", "high", "way")

    def checkAvailability(str: String, keyword: String): Boolean = {
      keyword.foldLeft((str, true)) { case ((remaining, result), ch) =>
        val idx = remaining.indexOf(ch)
        if (idx >= 0) (remaining.substring(0, idx) + remaining.substring(idx + 1), result && true)
        else (remaining, false)
      }._2
    }

    def filterList(arr: List[String], keyword: String): List[String] = {
      arr.filter(word => checkAvailability(keyword, word))
    }

    println(filterList(arr, "viinlg"))
    println(filterList(arr, "fceodglo"))
  }
}

```
> 1 votes

# Answer
# OCaml, 224 bytes

Golfed version. Try it online!

```
let f s t=List.filter(fun w->List.fold_left(fun(x,y)c->let i=String.index_opt x c in match i with Some j->String.sub x 0 j^String.sub x(j+1) (String.length x-j-1),y|None->x,false)(t,true)(String.to_seq w|>List.of_seq)|>snd)s

```

Ungolfed version. Try it online!

```
let filter_strings lst str =
  let rec filter_chars str char =
    let i = String.index_opt str char in
    match i with
    | Some idx -> String.sub str 0 idx ^ String.sub str (idx + 1) (String.length str - idx - 1), true
    | None -> str, false
  in
  List.filter (fun word ->
    let _, ok = List.fold_left (fun (str, b) c -> let str', b' = filter_chars str c in str', b && b') (str, true) (String.to_seq word |> List.of_seq) in
    ok) lst

let () =
  let arr = ["living"; "code"; "golf"; "highway"; "high"; "way"] in
  let result1 = filter_strings arr "viinlg" in
  let result2 = filter_strings arr "fceodglo" in
  print_endline (List.fold_left (fun a b -> if a = "" then b else a ^ "," ^ b) "" result1);
  print_endline (List.fold_left (fun a b -> if a = "" then b else a ^ "," ^ b) "" result2)

```
> 0 votes

# Answer
# Elixir, 188 bytes

Golfed version. Try it online!

```
f=fn(l,k)->Enum.filter(l,fn w->elem(Enum.reduce(String.graphemes(w),{k,true},fn c,{r,b}->if String.contains?(r,c),do: {String.replace(r,c,"",global: false),b},else: {r,false}end),1)end)end

```

Ungolfed version. Try it online!

```
defmodule Main do
  def run do
    filter_strings = fn (lst, k) ->
      Enum.filter(lst, fn w ->
        str = Enum.reduce(String.graphemes(w), {k, true}, fn c, {r, b} ->
          case String.contains?(r, c) do
            true -> {String.replace(r, c, "", global: false), b}
            _ -> {r, false}
          end
        end)
        elem(str, 1)
      end)
    end

    arr = ["living", "code", "golf", "highway", "high", "way"]
    IO.inspect(filter_strings.(arr, "viinlg"))
    IO.inspect(filter_strings.(arr, "fceodglo"))
  end
end

Main.run

```
> 0 votes

# Answer
# Erlang(escript), 156 bytes

Golfed version. Try it online!

```
f(L,K)->lists:filter(fun(W)->{_,B}=lists:foldl(fun(C,{R,A})->case lists:member(C,R)of true->{lists:delete(C,R),A};_->{R,false}end end,{K,true},W),B end, L).

```

Ungolfed version. Try it online!

```
-module(main).
-export([main/1]).

filter_strings(L, K) ->
    lists:filter(fun(W) ->
        {_, B} = lists:foldl(
            fun(C, {R, Acc}) ->
                case lists:member(C, R) of
                    true -> {lists:delete(C, R), Acc};
                    false -> {R, false}
                end
            end,
            {K, true},
            W
        ),
        B
    end, L).

main(_) ->
    Arr = ["living", "code", "golf", "highway", "high", "way"],
    io:format("~p~n", [filter_strings(Arr, "viinlg")]),
    io:format("~p~n", [filter_strings(Arr, "fceodglo")]).

```
> 0 votes

# Answer
# Racket, 299 bytes

Golfed version. Try it online!

```
(define(i s c)(let f([l(string->list s)][n 0])(if(null? l)#f(if(char=?(car l)c)n(f(cdr l)(+ 1 n))))))
(define(f l k)(filter(λ(w)(let g([r k][b #t][l(string->list w)])(if(null? l)b(let*([c(car l)][n(i r c)])(if(not(eqv? n #f))(g(string-append(substring r 0 n)(substring r(+ n 1)))b(cdr l))#f)))))l))

```

Ungolfed version. Try it online!

```
#lang racket

(define (string-index s c)
  (let loop ([s-list (string->list s)] [index 0])
    (cond
      [(null? s-list) #f]
      [(char=? (car s-list) c) index]
      [else (loop (cdr s-list) (+ 1 index))])))

(define (filter-strings l k)
  (filter (lambda (w)
            (let loop ([r k] [b #t] [wl (string->list w)])
              (if (null? wl)
                  b
                  (let* ([c (car wl)]
                         [i (string-index r c)])
                    (if (not (eqv? i #f))
                        (loop (string-append (substring r 0 i) (substring r (+ i 1))) b (cdr wl))
                        #f))))) l))

(define arr '("living" "code" "golf" "highway" "high" "way"))
(displayln (filter-strings arr "viinlg"))
(displayln (filter-strings arr "fceodglo"))

```
> 0 votes

# Answer
# F#(.NET Core), 171 bytes

Golfed version. Try it online!

```
let f l (k:string) = l |> List.filter(fun w -> let mutable r = k in w |> Seq.forall(fun (c:char) -> match r.IndexOf(c) with | -1 -> false | i -> r <- r.Remove(i,1); true))

```

Ungolfed version. Try it online!

```
open System

let filterStrings (l: string list) (k: string) =
    l |> List.filter(fun (w: string) ->
        let mutable r = k
        let mutable b = true
        for c in w do
            let i = r.IndexOf(c)
            if i >= 0 then
                r <- r.Remove(i, 1)
            else
                b <- false
        b)

let arr = ["living"; "code"; "golf"; "highway"; "high"; "way"]
printfn "%A" (filterStrings arr "viinlg")
printfn "%A" (filterStrings arr "fceodglo")

```
> 0 votes

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