gpt4 book ai didi

arrays - 在二维数组中搜索零并创建相应的行和列 0

转载 作者:数据小太阳 更新时间:2023-10-29 07:06:05 26 4
gpt4 key购买 nike

这是我的代码,可以运行,但它太大了。我想重构它。

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

输入:二维数组

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, 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]]

注意 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]]

关于arrays - 在二维数组中搜索零并创建相应的行和列 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30761910/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com