用Ruby确定矩阵中左上角到右下角对角线值的总和? [英] determining the sum of top-left to bottom-right diagonal values in a matrix with Ruby?

查看:103
本文介绍了用Ruby确定矩阵中左上角到右下角对角线值的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不确定行&的方阵.列长(假设行和列相等,等于一个正方形).

I have a square matrix of indeterminate row & column length (assume rows and columns are equal as befits a square).

我已经绘制了一个示例矩阵,如下所示:

I've plotted out an example matrix as follows:

matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
 ]

我的目标是从对角线值的左上角到右下角求和.

My goal is to get a sum from top-left to bottom-right of the diagonal values.

很明显,在此示例中,这就是我所需要的:

Obviously in this example, this is all i'll need:

diagsum = matrix[0][0]+matrix[1][1]+matrix[2][2]
#=>  15

我看到的模式是每行+1递增&矩阵中的列参数,因此我为不确定长度的矩阵开发的代码(作为方法diagsum的参数提供)最好在矩阵参数上实现某种row_count方法.

I see the pattern where it's a +1 incremental for each row & column argument in the matrix, so the code i've developed for my matrix of indeterminate length (supplied as the argument to my method diagsum would preferably need to implement some sort of row_count method on my matrix argument.

推荐答案

如果

arr = [[1,2,3],
       [4,5,6],
       [7,8,9]]

然后:

require 'matrix'
Matrix[*arr].trace
  #=> 15

这篇关于用Ruby确定矩阵中左上角到右下角对角线值的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆