s = [[1,2],[4,6],[2,7]]
數組我怎麼能在一個聲明中
最大= 7選擇每行第2列的最大值和sum
總和= 15
我知道,
sum = 0
max = 0
s.each{ |a,b| sum+=b;if max<b then max = b end }
會工作。
s = [[1,2],[4,6],[2,7]]
數組我怎麼能在一個聲明中
最大= 7選擇每行第2列的最大值和sum
總和= 15
我知道,
sum = 0
max = 0
s.each{ |a,b| sum+=b;if max<b then max = b end }
會工作。
s.map{|e| e[1]}.max
給你最大
s.map{|e| e[1]}.reduce(:+)
給你總和。
second_elements = s.map { |el| el[1] }
sum = second_elements.inject{|sum,x| sum + x }
max = second_elements.max
更清楚: inject{|sum,x| sum + x }
返回nil,如果數組是空的,所以如果你想爲空數組得到0然後用inject(0, :+)
s = [[1,2],[4,6],[2,7]]
second_max = s.max_by(&:last).last
# => 7
sum = s.reduce(0){|sum,a| sum + a.last}
# => 15
我喜歡'max_by' :) – tessi
The transpose method是好的訪問「列」:
s = [[1,2],[4,6],[2,7]]
col = s.transpose[1]
p col.max #=> 7
p col.inject(:+) #=> 15
Hash[s].values.inject :+
# => 15
Hash[s].values.max
# => 7
s.flatten.max返回所有數組的最大。例如在[[3,2]]我想返回2而不是3 – NewMrd
好吧,我更新了它。 –