23
\$\begingroup\$

Inspired by a question (now closed) at Stack Overflow.

Given a square matrix, let its double trace be defined as the sum of the entries from its main diagonal and its anti-diagonal. These are marked with X in the following examples:

X · · X
· X X · 
· X X ·
X · · X
X · · · X
· X · X ·
· · X · ·
· X · X ·
X · · · X

Note that for odd n, the central entry, which belongs to both diagonals, is counted only once.

Rules

  • The matrix size can be any positive integer.
  • The matrix will only contain non-negative integers.
  • Any reasonable input format can be used. If the matrix is taken as an array (even a flat one) its size cannot be taken as a separate input.
  • Input and output means are flexible as usual. Programs or functions are allowed. Standard loopholes are forbidden.
  • Shortest wins.

Test cases

5
   ->  5
3 5
4 0
     ->  12
 7  6 10
20 13 44
 5  0  1
          ->  36
4 4 4 4
4 4 4 4
4 4 4 4
4 4 4 4
          ->  32
23  4 21  5
24  7  0  7
14 22 24 16
 4  7  9 12
             ->  97
22 12 10 11  1
 8  9  0  5 17
 5  7 15  4  3
 5  3  7  0 25
 9 15 19  3 21
                -> 85

Inputs in other formats:

[[5]]
[[3,5],[4,0]]
[[7,6,10],[20,13,44],[5,0,1]]
[[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]
[[23,4,21,5],[24,7,0,7],[14,22,24,16],[4,7,9,12]]
[[22,12,10,11,1],[8,9,0,5,17],[5,7,15,4,3],[5,3,7,0,25],[9,15,19,3,21]]
[5]
[3 5; 4 0]
[7 6 10; 20 13 44; 5 0 1]
[4 4 4 4; 4 4 4 4; 4 4 4 4; 4 4 4 4]
[23 4 21 5; 24 7 0 7; 14 22 24 16; 4 7 9 12]
[22 12 10 11 1; 8 9 0 5 17; 5 7 15 4 3; 5 3 7 0 25; 9 15 19 3 21]
[5]
[3,5,4,0]
[7,6,10,20,13,44,5,0,1]
[4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4]
[23,4,21,5,24,7,0,7,14,22,24,16,4,7,9,12]
[22,12,10,11,1,8,9,0,5,17,5,7,15,4,3,5,3,7,0,25,9,15,19,3,21]
\$\endgroup\$
5
  • \$\begingroup\$ Loosely related: Sum the diagonals, Transposes and diagonals, Generalized matrix trace \$\endgroup\$
    – Luis Mendo
    Oct 24, 2021 at 10:39
  • \$\begingroup\$ I suggest adding a test case for [[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]. In J, (+.|.)@= works to create a mask of the traces for most arrays, except for arrays with repeated rows. \$\endgroup\$ Oct 26, 2021 at 0:08
  • \$\begingroup\$ @ConorO'Brien Added \$\endgroup\$
    – Luis Mendo
    Oct 26, 2021 at 11:29
  • \$\begingroup\$ is there a challenge for just the anti-diagonal? and maybe a problem to check if a matrix is a band matrix would be interesting. \$\endgroup\$
    – qwr
    Oct 27, 2021 at 2:07
  • 1
    \$\begingroup\$ @qwr The second one you propose sounds interesting! \$\endgroup\$
    – Luis Mendo
    Oct 27, 2021 at 9:13

18 Answers 18

7
\$\begingroup\$

APL (Dyalog 18.0), 17 bytes

Anonymous lambda.

{≢⍸⍵×∨∘⌽⍨∘.=⍨⍳≢⍵}

Try it online!

{}dfn; argument is

≢⍵ number of rows (and columns) in the argument

indices 1 through that

∘.=⍨ equality table (gives identity matrix)

∨∘⌽⍨ OR with mirrored self (indicates both diagonals)

⍵× multiply with argument

≢⍸ sum (lit. length of list of indices where each index is repeated as many times as its corresponding number in that)

\$\endgroup\$
6
\$\begingroup\$

K (ngn/k), 15 bytes

{+//x*|/|:\=#x}

Try it online!

Useful to have an identity matrix primitive.

Explanation:

{+//x*|/|:\=#x}
           =#x    / identity matrix with size of x
        |:\       / append reverse                          
      |/          / OR both matrices
    x*            / multiply by original matrix
 +//              / sum all elements
\$\endgroup\$
5
\$\begingroup\$

Jelly, 8 bytes

TżU$Ṭḋ⁸S

Try it online!

T         -- truthy indices of the argument, since every row is non-empty, this is [1 .. len(z)]
 żU$      -- zip with its reverse
    Ṭ     -- for each pair of integers, create a list with 1's at those two indices
     ḋ⁸   -- for each resulting list, take the dot product with the corresponding row vector of the input matrix
       S  -- sum the results
\$\endgroup\$
5
\$\begingroup\$

R, 47 bytes

function(m)sum(m[(z=diag(y<-nrow(m)))|z[y:1,]])

Try it online!

\$\endgroup\$
5
\$\begingroup\$

Python 3, 62 bytes

lambda m:sum(r[i]+r[~i]*(i!=len(m)+~i)for i,r in enumerate(m))

Try it online!

Explanation

lambda m:
                                      for i,r in enumerate(m)  # iterate m with i = row index and r = row
                 +r[~i]*(i!=len(m)+~i)                         # add r[len(m) - i - 1] if the index does not equal i
             r[i]                                              # add r[i]
         sum(                                                ) # sum numbers generated by the loop

Python 3.10, 59 58 bytes

lambda m,i=0:sum(r[i:=i-1]+r[~i]*(~i!=len(m)+i)for r in m)

If you know a online python 3.10 executor which allows sharing code snippets please leave a comment.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Interestingly this alternative using a set also ties at 62 \$\endgroup\$
    – xnor
    Oct 25, 2021 at 6:48
  • \$\begingroup\$ Wouldn't the 2nd program work for python 3.8+. I am not sure which feature requires only python 3.10. \$\endgroup\$
    – Mohammad
    Oct 26, 2021 at 13:10
  • 1
    \$\begingroup\$ @Mohammad, The use of assignment expressions in sequence indexes was only introduced in python 3.10 \$\endgroup\$ Oct 26, 2021 at 13:17
4
\$\begingroup\$

Octave, 36 34 bytes

This uses logical indexing. As an index we use an identity matrix of the size of the input and or it with it's flipped version. Thanks @LuisMendo for -2 bytes!

@(x)sum(x(flip(e=eye(size(x)))|e))

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ @LuisMendo It does! Thanks:) \$\endgroup\$
    – flawr
    Oct 24, 2021 at 11:33
4
\$\begingroup\$

MATL, 13 11 bytes

This uses logical indexing. As an index we use an identity matrix of the size of the input and or it with it's flipped version, just like in my Octave answer. Thanks @LuisMendo for -2 bytes:)

tZyXytPY|)s

Explanation

t            push input twice to stack
 Zy          get size of matrix
   Xy        get an identity matrix of that size
     t       duplicate the identity matrix
      P      flip one of the identty matrices
       Y|    logical OR the two identity matrices
         )   perform (logical) indexing to the original matrix
          s  compute the sum

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Pari/GP, 42 bytes

m->sum(i=1,#m,m[i,i]+m[i,j=#m+1-i]*(i!=j))

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Vyxal d, 12 bytes

ż:Ẋv≈?Lẇ:R⋎*

Try it Online!

Some of Vyxal's behaviour is cursed.

ż            # 1...length
 :Ẋ          # Cartesian product with self
   v≈        # Vectorised all_same 
             # Only values along the diagonal will be truthy, the rest will be falsy, creating an identity matriix
     ?Lẇ     # Make it a square (molding doesn't work, for some reason)
        :R⋎  # Or with reversed copy
           * # Multiply (vectorised)
             # (d flag) deep sum of this
\$\endgroup\$
2
\$\begingroup\$

05AB1E, 9 bytes

āDδQÂ~*˜O

Try it online!

-1 thanks to @KevinCruijssen

Wish to have the identity matrix builtin

g               Length
 L              Range
  D             Dup
   δ            Outer product with
    Q           Equals?
     Â          Bifurcate
      ~         Bitwise OR
       *        Multiply with input
        ˜       Flatten
         O      Sum
\$\endgroup\$
6
  • \$\begingroup\$ ovs is right, which is why all those other answers are awkwardly long. (Otherwise Jelly would be 4 bytes) \$\endgroup\$
    – Bubbler
    Oct 25, 2021 at 7:45
  • 2
    \$\begingroup\$ (To clarify: the one that doesn't work is the 7-byter at the top. The 10-byter works fine with odd sizes.) \$\endgroup\$
    – Bubbler
    Oct 25, 2021 at 7:56
  • 1
    \$\begingroup\$ @ovs fixed by now \$\endgroup\$
    – Wasif
    Oct 25, 2021 at 8:43
  • \$\begingroup\$ @Bubbler yeah check now it is the same long looking answer now \$\endgroup\$
    – Wasif
    Oct 25, 2021 at 8:44
  • \$\begingroup\$ @KevinCruijssen thanks for the 1 byte save! new builtin learned \$\endgroup\$
    – Wasif
    Oct 25, 2021 at 8:44
2
\$\begingroup\$

Ruby, 64 bytes

->m{(r=0...l=m.size).sum{|y|r.sum{|x|x==y||x-~y==l ?m[y][x]:0}}}

Try it online!

->m{              # lambda taking a 2d array and returning diagonal sum
(r=0...l=m.size)  # range 0..length 
.sum{|y|r.sum{|x| # sum the result of passing each coordinates

x==y||x-~y==l ?   # if on diagonals 
m[y][x]:0         # take value else 0
\$\endgroup\$
2
\$\begingroup\$

C (gcc), 81 \$\cdots\$ 71 59 bytes

i;f(m,l)int*m;{for(i=l*l;--i;)*m+=i%~l&&i%~-l?0:m[i];l=*m;}

Try it online!

Saved a bytes thanks to att!!!
Saved 12 bytes thanks to AZTECCO!!!

Inputs a pointer to a flattened square array and the number of rows (because pointers in C carry no length info).
Returns its double trace.

\$\endgroup\$
5
  • \$\begingroup\$ i;s;f(m,l)int*m;{for(s=i=-l;i;)s+=m[i-i*l]-~m[++i*~l];s-=l%2*m[l*l/2];} for 71 \$\endgroup\$
    – att
    Oct 25, 2021 at 18:08
  • \$\begingroup\$ @att Oh, that's sweet - thanks! :D \$\endgroup\$
    – Noodle9
    Oct 25, 2021 at 18:17
  • \$\begingroup\$ 61 bytes by using my Ruby approach \$\endgroup\$
    – AZTECCO
    Oct 25, 2021 at 20:44
  • \$\begingroup\$ 59 Bytes by using *m+=i%~l&&i%~-l?.. \$\endgroup\$
    – AZTECCO
    Oct 26, 2021 at 7:55
  • \$\begingroup\$ @AZTECCO Fantastic - thanks! :D \$\endgroup\$
    – Noodle9
    Oct 26, 2021 at 10:39
2
\$\begingroup\$

tinylisp, 132 109 bytes

(load library
(d L length
(d f(q((M)(s(a(trace M)(trace(reverse M)))(*(odd?(L M))(nth(nth M(/(L M)2))(/(L M)2

Try it online!

-23 bytes thanks to DLosc.

\$\endgroup\$
1
  • \$\begingroup\$ @DLosc Thanks! I must have been thinking about a different problem when I did this. \$\endgroup\$
    – Giuseppe
    Feb 3 at 19:54
2
\$\begingroup\$

Pip -x, 24 21 20 bytes

YEY#a$+$+a*HV:y+1+Ry

Attempt This Online! The matrix should be given as a command-line argument in the following form:

[[7;6;10];[20;13;44];[5;0;1]]

Or, verify all test cases.

Explanation

YEY#a$+$+a*HV:y+1+Ry
   #a                 Size of the matrix
 EY                   Identity matrix of that size
Y                     Yank into the y variable
                  Ry  y reversed (backward identity matrix)
                1+    Add 1 to each value
              y+      Add to y (identity matrix)
           HV:        Each value halved (rounded down)
                      This creates a matrix where both diagonals are 1's and
                      everything else is 0's
         a*           Multiply the input matrix itemwise by the 1/0 matrix
       $+             Fold on addition (sum each column)
     $+               Fold on addition (sum that list of sums)
\$\endgroup\$
1
\$\begingroup\$

Charcoal, 18 bytes

IΣEθΣΦι∨⁼κμ⁼⁺κμ⊖Lθ

Try it online! Link is to verbose version of code. Explanation: Filters out elements not on either main diagonal, then takes the sum.

   θ                Input matrix
  E                 Map over rows
      ι             Current row
     Φ              Filtered where
         κ          Row index
        ⁼           Equals
          μ         Column index
       ∨            Logical Or
             κ      Row index
            ⁺       Plus
              μ     Column index
           ⁼        Equals
                 θ  Input matrix
                L   Length
               ⊖    Decremented
    Σ               Take the sum
 Σ                  Take the sum
I                   Cast to string
                    Implicitly print
\$\endgroup\$
1
\$\begingroup\$

Raku, 43 bytes

{sum .kv.flatmap:{@^v[unique $^k,@v-$k-1]}}

Try it online!

A function which takes its input in $_ as a list-of-lists.

  • .kv returns an interleaved sequence of each row's index and the row, ie: 0, the first row, 1, the second row, etc.
  • .flatmap: { ... } passes the key and value to the brace-delimited anonymous function and flattens the return values. That function takes the index of each row in $k and the row itself in @v, each argument declared with a "twigil" $^/@^ on its first lexical appearance.
  • $k and @v - $k - 1 are the indices of the elements of each row that go into the double trace. @v, the row, evaluates to its number of elements in a numerical context (the subtraction operator).
  • unique selects only the unique indices. This eliminates the double index at the center of the matrix, if it has an odd dimension.
  • @v[...] is a slice that returns the row elements at the unique indices.
\$\endgroup\$
1
\$\begingroup\$

Pyth, 18 bytes

s.e+@bk&-hyklb@_bk

Try it online!

Explanation

s.e+@bk&-hyklb@_bk
 .e                 # Iterate through implicit input with (b = row, k = index)
    @bk             # b[k]
       &-hyklb      # if ((2 * k) + 1) - len(b) != 0
   +          @_bk  #   plus b[::-1][k]
s                   # sum results from the iteration

The ((2 * k) + 1) - len(b) is derived from rearranging k - (len(b) - (k + 1))

\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6), 51 bytes

m=>m.reduce((t,r,i)=>t+r[i]+r.reverse(r[i]=0)[i],0)

Try it online!

Commented

m =>         // m[] = matrix
m.reduce(    // reduce():
  ( t,       //   t   = sum
    r,       //   r[] = current row
    i        //   i   = row index, used as a column index
  ) =>       //
  t + r[i] + //   add r[i] to t
  r.reverse( //   reverse r[] ...
    r[i] = 0 //     ... but only once r[i] has been cleared
             //     so that it's not counted twice
  )[i],      //   add r[i] again
  0          //   start with t = 0
)            // end of reduce()

JavaScript ES2022, 46 bytes

Suggested by @tsh:

m=>m.reduce((t,r,i)=>t+r[i]+r.at(~i,r[i]=0),0)

(Doesn't work on TIO.)

\$\endgroup\$
1
  • \$\begingroup\$ You can give Array.prototype.at a try which is introduced by ES2022: m=>m.reduce((t,r,i)=>t+r[i]+r.at(~i,r[i]=0),0) \$\endgroup\$
    – tsh
    Oct 26, 2021 at 2:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.