加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

数组 – 在2D数组中搜索零并生成相应的行和col 0

发布时间:2020-12-16 23:07:02 所属栏目:百科 来源:网络整理
导读:这是我的代码,它有效,但它太大了.我想重构它. req_row = -1req_col = -1a.each_with_index do |row,index| row.each_with_index do |col,i| if col == 0 req_row = index req_col = i break end endendif req_col -1 and req_row -1 a.each_with_index do |r
这是我的代码,它有效,但它太大了.我想重构它.
req_row = -1
req_col = -1

a.each_with_index do |row,index|
  row.each_with_index do |col,i|
     if col == 0
        req_row = index
        req_col = i
        break
     end
  end
end

if req_col > -1 and req_row > -1
  a.each_with_index do |row,index|
    row.each_with_index do |col,i|
      print (req_row == index or i == req_col) ? 0 : col
       print " "
    end
    puts "r"
  end
end

输入:2D数组

1  2  3  4 
5  6  7  8
9  10 0 11
12 13 14 15

所需输出:

1  2  0  4 
5  6  0  8
0  0  0  0
12 13 0  15

解决方法

我很惊讶 Matrix课程的用法不多:
a = [[ 1,2,3,4],[ 5,6,7,8],[ 9,10,11],[12,13,14,15]]

require 'matrix'

m = Matrix.rows(a)
  #=> Matrix[[1,[5,[9,15]]

r,c = m.index(0)
  #=> [2,2]

Matrix.build(m.row_count,m.column_count) {|i,j| (i==r || j==c) ? 0 : m[i,j]}.to_a
  #=> [[ 1,#    [ 5,#    [ 0,0],#    [12,15]]

注意Matrix对象是不可变的.要更改单个元素,您必须创建一个新矩阵.

如果您希望对矩阵中的每个零执行此操作,则需要稍作修改:

a = [[ 1,[ 0,15]]

require 'set'

m = Matrix.rows(a)
  #=> Matrix[[1,[0,15]]

zero_rows = Set.new
zero_columns = Set.new
m.each_with_index { |e,i,j| (zero_rows << i; zero_columns << j) if e.zero? }
zero_rows
  #=> #<Set: {2,3}> 
zero_columns
  #=> #<Set: {2,0}>     

Matrix.build(m.row_count,m.column_count) do |i,j|
  (zero_rows.include?(i) || zero_columns.include?(j)) ? 0 : m[i,j]
end.to_a
  #=> [[0,#    [0,0]]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读