我有一个像:
这样的数组[[score, count], [score, count]]
我需要添加所有分数并除以所有计数:)
这是一个例子
[[10, 2], [5, 2]] : (10x2 + 5x2)/4 = 7.5
答案 0 :(得分:2)
arr = [[10, 2], [5, 2]]
#=> [[10, 2], [5, 2]]
arr.reduce(0) { |acc,(x,y)| acc + x * y }.to_f / arr.reduce(0) { |acc,(_,y)| acc + y }
#=> 7.5
答案 1 :(得分:1)
ary = [[10, 2], [5, 2]]
total_score = ary.reduce(0) { |sum, (a, b)| sum + a * b }
total_count = ary.reduce(0) { |sum, a| sum + a.last }
avg = total_score/total_count.to_f
答案 2 :(得分:1)
这使得一次通过数组。
arr = [[10, 2], [5, 2], [3, 4]]
tot, div = arr.reduce([0,0]) { |(tot, div), (score, count)|
[tot + (score * count), div + count] }
#=> [42, 8]
tot/div.to_f #=> 5.25
计算
tot => 0 + 10*2 + 5*2 + 3*4 => 42
div => 0 + 2 + 2 + 4 => 8
答案 3 :(得分:0)
ary = [[400, 5], [240, 4]]
total_score = ary.map{|a| a.first*a.last}.sum
total_count = ary.map(&:last).sum
avg = total_score/total_count.to_f
答案 4 :(得分:0)
data.inject(0) { |score, (x, y)| score + x * y }.to_f / data.inject(0) { |count, (_, y)| count + y }