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

1k views Asked by At

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

3

There are 3 answers

4
Mircea On BEST ANSWER

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

0
Mike Manfrin On

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
0
John La Rooy On

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