红宝石在2d阵列中获取对角线元素
我在尝试使用我的2D红宝石阵列时遇到了一些问题,并且在进行阵列切片时,我的LOC减少了很多。因此,例如,红宝石在2d阵列中获取对角线元素
require "test/unit"
class LibraryTest < Test::Unit::TestCase
def test_box
array = [[1,2,3,4],[3,4,5,6], [5,6,7,8], [2,3,4,5]]
puts array[1][2..3] # 5, 6
puts array[1..2][1] # 5, 6, 7, 8
end
end
我想知道是否有办法获得对角切片?比方说,我想从[0,0]开始,想要一个3的对角线切片。然后我会从[0,0],[1,1],[2,2]得到元素,我会得到一个数组像例如[1,4,7]。有没有什么可以实现这一点的魔术单线程ruby代码? 3.times做{一些神奇的东西吗?}
puts (0..2).collect { |i| array[i][i] }
!解决方案非常明显!干得好,虽然我会用array.size代替2,因为数组长度可能不同。 – 2010-03-24 10:32:24
真棒:)很酷的答案... {一些神奇的东西?}在Ruby中很明显 – RubyDubee 2010-03-24 10:40:52
不错的一个其实我需要2而不是array.size,因为它可以是任何对角/部分对角片:) – 2010-03-24 11:16:40
更好的可能是一个班轮利用矩阵库:
require 'matrix'
Matrix.rows(array).each(:diagonal).to_a
红宝石片断基础的Get all the diagonals in a matrix/list of lists in Python
这是为了关闭得到所有的对角线。无论如何,这个想法是从不同的侧面排列阵列,以便对角线在行和列中对齐:
arr = [[1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8], [2, 3, 4, 5]]
# pad every row from down all the way up, incrementing the padding.
# so: go through every row, add the corresponding padding it should have.
# then, grab every column, that’s the end result.
padding = arr.size - 1
padded_matrix = []
arr.each do |row|
inverse_padding = arr.size - padding
padded_matrix << ([nil] * inverse_padding) + row + ([nil] * padding)
padding -= 1
end
padded_matrix.transpose.map(&:compact)
您可能知道这一点,但'puts array [1..2] [1]'是等效的到'puts array [2]',而不是'puts array [1..2] .map {| arr | ARR [1]}'。我不确定使用数组数组是否是正确的做事方式,但我还没有能够更好地构建任何东西。 – 2010-03-24 22:42:13
这是我的意图。但你的答案仍然非常有用。谢谢:) – 2010-03-24 23:00:49