对角线点积


10

这个挑战非常简单。您将得到一个以任何理性方式表示的方阵作为输入,并且您必须输出该矩阵对角线的点积。

具体而言,对角线是从左上角到右下角以及从右上角到左下角的对角线。

测试用例

[[-1, 1], [-2, 1]]  ->  -3
[[824, -65], [-814, -741]]  ->  549614
[[-1, -8, 4], [4, 0, -5], [-3, 5, 2]]  ->  -10
[[0, -1, 0], [1, 0, 2], [1, 0, 1]]  ->  1

Answers:





2

J,21 19字节

[:+/(<0 1)|:(*|."1)

直截了当的方法。

由于@ Lynn节省了2个字节。

用法

输入数组使用进行整形dimensions $ values

   f =: [:+/(<0 1)|:(*|."1)
   f (2 2 $ _1 1 _2 1)
_3
   f (2 2 $ 824 _65 _814 _741)
549614
   f (3 3 $ _1 _8 4 4 0 _5 _3 5 2)
_10
   f (3 3 $ 0 _1 0 1 0 2 1 0 1)
1

说明

[:+/(<0 1)|:(*|."1)    Input: matrix M
              |."1     Reverse each row of M
             *         Multiply element-wise M and the row-reversed M
    (<0 1)|:           Take the diagonal of that matrix
[:+/                   Sum that diagonal and return it=

[:+/(<0 1)|:(*|."1)是19个字节
林恩


1

JavaScript(ES6),45个字节

a=>a.reduce((r,b,i)=>r+b[i]*b.slice(~i)[0],0)
a=>a.reduce((r,b,i)=>r+b[i]*b[b.length+~i],0)




0

Clojure,57个字节

#(apply +(map(fn[i r](*(r i)(nth(reverse r)i)))(range)%))

0

Haskell80 48字节

我更喜欢以前的解决方案,但这要短得多(基本上与Python解决方案相同):

f m=sum[r!!i*r!!(length m-i-1)|(i,r)<-zip[0..]m]

在线尝试!


0

J,18字节

<:@#{+//.@:(*|."1)

说明:

           (     ) | Monadic hook
            *      | Argument times...
             |."1  | The argument mirrored around the y axis
     +//.@:        | Make a list by summing each of the diagonals of the matrix
    {              | Takes element number...
<:@#               | Calculates the correct index (size of the array - 1)

0

05AB1E,5 个字节

í*Å\O

在线尝试验证所有测试用例

说明:

í        # Reverse each row of the (implicit) input-matrix
         #  i.e. [[-1,-8,4],[4,0,-5],[-3,5,2]] → [[4,-8,-1],[-5,0,4],[2,5,-3]]
 *       # Multiply it with the (implicit) input-matrix (at the same positions)
         #  i.e. [[-1,-8,4],[4,0,-5],[-3,5,2]] and [[4,-8,-1],[-5,0,4],[2,5,-3]]
         #   → [[-4,64,-4],[-20,0,-20],[-6,25,-6]]
  Å\     # Get the diagonal-list from the top-left corner towards the bottom-right
         #  i.e. [[-4,64,-4],[-20,0,-20],[-6,25,-6]] → [-4,0,-6]
    O    # Sum it (and output implicitly)
         #  i.e. [-4,0,-6] → -10
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.