ruby - Search for zero in 2D array and make a corresponding row and col 0 -
this code, works, it's big. want refactor it.
req_row = -1 req_col = -1 a.each_with_index |row, index| row.each_with_index |col, i| if col == 0 req_row = index req_col = break end end end if req_col > -1 , req_row > -1 a.each_with_index |row,index| row.each_with_index |col, i| print (req_row == index or == req_col) ? 0 : col print " " end puts "\r" end end
input: 2d array
1 2 3 4 5 6 7 8 9 10 0 11 12 13 14 15
required output:
1 2 0 4 5 6 0 8 0 0 0 0 12 13 0 15
i'm surprised matrix class not used more:
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]]
note matrix
objects immutable. change individual elements must create new matrix.
a slight modification required if wish every 0 in 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) |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]]
Comments
Post a Comment