在2D数组中搜索零并创建相应的行和col 0

6 ruby arrays logic

这是我的代码,它有效,但它太大了.我想重构它.

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
Run Code Online (Sandbox Code Playgroud)

输入:2D数组

1  2  3  4 
5  6  7  8
9  10 0 11
12 13 14 15  
Run Code Online (Sandbox Code Playgroud)

所需输出:

1  2  0  4 
5  6  0  8
0  0  0  0
12 13 0  15  
Run Code Online (Sandbox Code Playgroud)

Car*_*and 4

我很惊讶Matrix类没有被更多地使用:

a = [[ 1,  2,  3,  4],
     [ 5,  6,  7,  8],
     [ 9, 10,  0, 11],
     [12, 13, 14, 15]]

require 'matrix'

m = Matrix.rows(a)
  #=> Matrix[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 0, 11], [12, 13, 14, 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,  2, 0,  4],
  #    [ 5,  6, 0,  8],
  #    [ 0,  0, 0,  0],
  #    [12, 13, 0, 15]] 
Run Code Online (Sandbox Code Playgroud)

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

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

a = [[ 1,  2,  3,  4],
     [ 5,  6,  7,  8],
     [ 9, 10,  0, 11],
     [ 0, 13, 14, 15]]

require 'set'

m = Matrix.rows(a)
  #=> Matrix[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 0, 11], [0, 13, 14, 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, 2, 0, 4],
  #    [0, 6, 0, 8],
  #    [0, 0, 0, 0],
  #    [0, 0, 0, 0]] 
Run Code Online (Sandbox Code Playgroud)