我有一个像这样的矩阵:
0 1 0 0 1 0
1 0 1 0 1 0
0 1 0 1 0 0
0 0 1 0 1 1
1 1 0 1 0 0
0 0 0 1 0 0
如何在Ruby中定义矩阵,然后搜索它?
我想编写一个程序,搜索所有行并返回最高总和为" 1"的行。
答案 0 :(得分:3)
在Ruby中定义矩阵的快速方法:
Array.new 6, Array.new(6, 0)
# => [
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]
]
上面的代码初始化一个包含6个项目的数组,并将它们的值默认为第二个参数,这是另一个包含6个项目且默认值为0的数组。
在其他更多命令式语言中,您将使用嵌套循环:
matrix = []
for x in [0,1,2,3,4,5]
for y in [0,1,2,3,4,5]
matrix[x] ||= [] # create the row as an empty array
matrix[x] << y # push the y value to it
end
end
# matrix is now:
# => [
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5]
]
搜索矩阵并找到总和最大的行:
greatest_sum_row_index = 0
greatest_sum = 0
matrix.each_with_index do |row, i|
# row.inject(:+) is a shortcut to adding each int in the array and returning the sum
sum = row.inject(:+)
if sum > greatest_sum
greatest_sum = sum
greatest_sum_row_index = i
end
end
# highest_row is now the index of the greatest sum row
matrix[greatest_sum_row_index] # returns the row with the greatest sum
答案 1 :(得分:1)
如果阵列很大并且需要考虑内存要求,则可以执行以下操作:
def rows_with_most_ones(arr)
arr.each_with_index.with_object([-1, nil]) do |(row,i),best|
tot = row.count(1)
case tot<=>best.first
when 1 then best.replace([tot, [i]])
when 0 then best.last << i
end
end
end
arr = [[0, 1, 0, 0, 1, 0],
[1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 0],
[0, 0, 1, 0, 1, 1],
[1, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0]]
rows_with_most_ones(arr)
#=> [3, [1, 3, 4]]