2

I was wondering how you can sum from one point of an array to another point, for example:

array = [1,3,5,6,1]

assuming i is a moving variable, for example

i = 2

assuming k is a moving variable, for example

k = 4

The solution I'm looking for is to sum from array[2] to array[4], so 5+6+1 = 12

I've tried using (array[i]..array[k]).reduce(:+) but it doesn't seem to work.

Any help is appreciated!

2 Answers 2

3

Almost! But you're creating a range between two integer array values when you want to be indexing an array!

array[i..k].reduce(:+)
Sign up to request clarification or add additional context in comments.

Comments

1

The solution given by @glennmcdonald is the normal way to do a partial sum, but it does create another array:

array[first_index..last_index]

If that array is sufficiently large, you may prefer or be required to compute the sum without creating a new array. Here are two of many ways you could do that:

def sum_range1(array, first_index, last_index)
  (first_index..last_index).reduce(0) { |tot,i| tot+array[i] }
end

or this:

def sum_range2(array, first_index, last_index)
  array.each_with_index.reduce(0) { |tot,(n,i)|
    tot + ((first_index..last_index).cover?(i) ? n : 0) }
end     

arr = [1,3,5,6,1]
sum_range1(arr, 2, 4) #=> 12 
sum_range2(arr, 2, 4) #=> 12 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.