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

我与影子孤独终老i 提交于 2019-12-04 16:24:53

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

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

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