Ruby inject until sum exceeds a set value and return the index where this occurs

霸气de小男生 提交于 2019-12-06 08:55:54

问题


With the following array and value:

v = 50
a = [10, 20, 25, 10, 15]

I want to iterate through the array adding up the values until the sum of these values exceeds the variable v. And then I want to be able to return the index in the array where that occurred. so...

10 + 20 + 25 = 55 (which is the first point which the sum is greater that 'v') so index = 2

Thanks for your help


回答1:


For the sum:

a.inject do |sum,n|
  break sum if sum > v
  sum + n
end

For the index, idea is the same - you use the memo as an array and keep the sum in the first element:

a.inject([0,-1]) do |memo,n|
  break [memo[0], memo[1]] if memo[0] > v
  [memo[0]+n, memo[1]+1]
end

you need to look at the array after that




回答2:


A couple more ways

a.each_with_index.inject 0 do |acc, (n, idx)|
     break idx - 1 if acc > v
     acc + n
end

or

a.to_enum.with_index(-1).inject 0 do |acc, (n, idx)|
     next acc + n if acc < v
     break idx
end



回答3:


I think you'd have to inject over the indexes and access the outside array, since inject does not pass along the index; like so:

a.each_index.inject do |memo, i|
  break i if memo > v
  memo + a[i]
end


来源:https://stackoverflow.com/questions/30903949/ruby-inject-until-sum-exceeds-a-set-value-and-return-the-index-where-this-occurs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!