【发布时间】:2018-10-24 16:54:29
【问题描述】:
假设我有 10x10 矩阵,包含以下数据:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 _ 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
我的职位是[4][4]。如何列出该位置的对角线值?
例如,预期的结果是:
[56, 67, 78, 89, 100, 1, 12, 23, 34]
[54, 63, 72, 81, 9, 18, 27, 36]
我目前的解决方案
def next?(index, row, size)
(((row + index) % size) + 1 ) % size
end
(1...chess_size).each do |l|
next_el, curr_el = next?(l, row, chess_size), (row + l) % chess_size
# this gets me the first diagnonal. Note that it prints out wrong value
tmp[0] << chess[curr_el][curr_el]
# this gets me the values from current row below to up
tmp[1] << chess[(row + l) % chess_size][row]
tmp[2] << chess[-l][l]
tmp[3] << chess[row][(row + l) % chess_size]
end
我们的矩阵将始终具有相同的行数和列数。
【问题讨论】:
-
尝试使用您的矩阵并执行
Matrix[].each(:diagonal).to_a查看这些链接以获得更好的理解。如果他们帮助您,请告诉我,我将与您一起解决问题 --Matrix.rb Implementation --Ruby Matrix Methods&Documentation --(stackoverflow.com/questions/36417799/…) -
@CarySwoveland 当前的解决方案是否足够?
-
我假设
chess是给定的数组,但chess_size和tmp没有定义。顺便说一句,请确保所有示例输入都是有效的 Ruby 对象并已分配给变量。在这里,您给出了数组的图片,这意味着每个想要运行代码的读者都必须将其转换为实际的数组 ([[1,2,3...)。如果它是一个数组,我们可以直接剪切和粘贴。通过将其分配给变量(例如arr = [[1, 2,....),读者可以通过该变量引用代码中的数组和 cmets,而无需定义它。 -
@CarySwoveland Humbledore 提供了一个无需创建矩阵的解决方案。但他声称它不适用于大型测试用例。
标签: ruby algorithm math matrix diagonal