What's the efficient way to multiply two arrays and get sum of multiplied values in Ruby?

前端 未结 9 932
猫巷女王i
猫巷女王i 2021-02-09 12:54

What\'s the efficient way to multiply two arrays and get sum of multiply values in Ruby? I have two arrays in Ruby:

array_A = [1, 2, 1, 4, 5, 3, 2, 6, 5, 8, 9]
a         


        
9条回答
  •  渐次进展
    2021-02-09 13:20

    Since speed is our primary criterion, I'm going to submit this method as it's fastest according to Peter's benchmarks.

    sum, i, size = 0, 0, a1.size
    while i < size
      sum += a1[i] * a2[i]
      i += 1
    end
    sum
    

提交回复
热议问题