代码之家  ›  专栏  ›  技术社区  ›  Kannan Ekanath

Ruby获取2d数组中的对角线元素

  •  8
  • Kannan Ekanath  · 技术社区  · 16 年前

    我试着用我的2druby数组解决一些问题,当我进行数组切片时,我的LOC减少了很多。比如说,

    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.做些神奇的事

    3 回复  |  直到 14 年前
        1
  •  18
  •   Dorian    11 年前
    puts (0..2).collect { |i| array[i][i] }
    
        2
  •  8
  •   zilla    12 年前

    最好是使用矩阵库的一行程序:

    require 'matrix'
    Matrix.rows(array).each(:diagonal).to_a
    
        3
  •  3
  •   Community Mohan Dere    9 年前

    基于 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)
    
        4
  •  1
  •   schmijos Fizer Khan    6 年前

    我正在接受@Shai的答案,并提议让它更实用。

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

    padding = [*0..(arr.length - 1)].map { |i| [nil] * i }
    => [[], [nil], [nil, nil], [nil, nil, nil]]
    

    填充还是第二个取决于你想向下还是向上

    padded = padding.reverse.zip(arr).zip(padding).map(&:flatten)
    => [[nil, nil, nil, 1, 2, 3, 4], [nil, nil, 3, 4, 5, 6, nil], [nil, 5, 6, 7, 8, nil, nil], [2, 3, 4, 5, nil, nil, nil]]
    

    padded.transpose.map(&:compact)
    => [[2], [5, 3], [3, 6, 4], [1, 4, 7, 5], [2, 5, 8], [3, 6], [4]]