determining the sum of top-left to bottom-right diagonal values in a matrix with Ruby?

自闭症网瘾萝莉.ら 提交于 2019-12-25 17:18:22

问题


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

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.


回答1:


If

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

then:

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



回答2:


This will sum the diagonal values.

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

def diagsum(mat)
  sum = 0
  mat.each_with_index { |row,i| sum += row[i]  }
  sum
end

puts (diagsum matrix) # 15



回答3:


  1. Not clear what x is.
  2. But assuming that it is the number of columns/rows, you have 0..x, while the index only goes up to x - 1. You should change it to 0...x.
  3. You are assigning to variable i, whose scope is only in the block.
  4. You are only using i once, perhaps intended to correspond to either row or column, but not both.
  5. You are adding the indices instead of the corresponding elements.
  6. each will return the receiver regardless of whatever you get in the blocks.
  7. puts will return nil regardless of whatever you get.


来源:https://stackoverflow.com/questions/32853157/determining-the-sum-of-top-left-to-bottom-right-diagonal-values-in-a-matrix-with

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!