我有一個數組,如:在Ruby中,如何獲得奇怪元素的總和?
["4|23", "1", "3|10", "2"]
我想要得到的奇數元素的總和,即,1 + 2 = 3時,或許與inject
?
這是Redis ZRANGE WITHSCORES對排序集的迴應。理想情況下,我想get the sum of the SCORES in a sorted set。
我有一個數組,如:在Ruby中,如何獲得奇怪元素的總和?
["4|23", "1", "3|10", "2"]
我想要得到的奇數元素的總和,即,1 + 2 = 3時,或許與inject
?
這是Redis ZRANGE WITHSCORES對排序集的迴應。理想情況下,我想get the sum of the SCORES in a sorted set。
感謝大家的回答。他們都非常酷,&啓發。
我想出了自己的答案。這是很簡單的...
sum = 0; gifts.each_with_index { |s, i| sum += s.to_i if i % 2 == 1 }; sum
我做了性能檢查:
require "benchmark"
MANY = 50000
gifts = [
"4|2323", "1",
"3|102343", "2",
"0|12330", "1",
"3|10234873", "2",
"5|2343225", "1",
"5|23423744", "1",
"2|987", "4",
"0|987345", "1",
"2|46593", "1",
"4|78574839", "3",
"3|4756848578", "1",
"3|273483", "3"
]
Benchmark.bmbm do |x|
x.report("each_with_index") { MANY.times { sum = 0; gifts.each_with_index { |s, i| sum += s.to_i if i % 2 == 1 }; sum } }
x.report("each_with_index") { MANY.times { sum = 0; gifts.each_with_index { |s, i| sum += s.to_i if i.odd? }; sum } }
x.report("values_at") { MANY.times { gifts.values_at(*(1..gifts.length).step(2)).inject(0) { |s, n| s += n.to_i } } }
x.report("each_slice") { MANY.times { gifts.each_slice(2).inject(0) { |i, (j,k)| i += k.to_i } } }
x.report("values_at") { MANY.times { gifts.values_at(*gifts.each_index.select { |i| i.odd? }).map(&:to_i).inject(&:+) } }
x.report("hash") { MANY.times { Hash[*gifts].values.map(&:to_i).reduce(:+) } }
end
運行上面的輸出腳本我的Mac上執行以下操作:
user system total real
each_with_index 0.300000 0.000000 0.300000 ( 0.305377)
each_with_index 0.340000 0.000000 0.340000 ( 0.334806)
values_at 0.370000 0.000000 0.370000 ( 0.371520)
each_slice 0.380000 0.000000 0.380000 ( 0.376020)
values_at 0.540000 0.000000 0.540000 ( 0.539633)
hash 0.560000 0.000000 0.560000 ( 0.560519)
看起來像我的回答是最快的。哈哈。 Suckas! :P
Ruby數組是基於0的,所以也許你試圖總結奇數索引的值?如果是這樣,以下將做一些濾波(i.odd?
)和消毒(i.to_i
):
>> a = ["4|23", "1", "3|10", "2"]
>> a.values_at(*a.each_index.select{|i| i.odd?}).map{|i| i.to_i}.inject(&:+)
=> 3
這,一步步
# Your array
ary = ["4|23", "1", "3|10", "2"]
# the enumerator to iterate through it
enum = (1..ary.length).step(2)
# your scores
scores = ary.values_at(*enum)
# and the sum
sum = scores.inject(0){ |s,n| s = s + n.to_i }
其也可以寫成這樣
sum = ary.values_at(*(1..ary.length).step(2)).inject(0){ |s,n| s = s + n.to_i }
爲什麼選擇投票? – edgerunner 2011-02-01 04:43:08
["4|23", "1", "3|10", "2"].each_slice(2).inject(0) { |i, (j,k)| i += k.to_i }
Hash[*a].values.map(&:to_i).reduce(:+)
array = ["4|23", "1", "3|10", "2"]
array.select.with_index {|e,i|i.odd?}.map(&:to_i).inject(:+)
=> 3
是的,你說得對,很奇怪。我更新了我的問題。謝謝!酷解決方案! – ma11hew28 2011-01-31 03:44:12