tags:

views:

81

answers:

2

I have an array that contains values that I'm working on (in a specific order) something like the following:

myArray = [3,6,5,6,2,1]

I need to evaluate the elements in the array and determine the number of the elements to copy.

The rules are: I need to copy the elements where the sum of those elements is not greater than the previous element.

I can kind of express it like this:

if myArray[-3] > (myArray[-2] + myArray[-1])
   elements_to_copy = [myArray[-2],myArray[-1]]
else
   elements_to_copy = [myArray[-1]]
end

Which feels very crappy, as I can't work out how to make it work as an iterative function, so that I can continue up the chain till the comparison fails.

Can anyone help?

A: 
elements_to_copy = []
array = myArray.reverse
array.each_with_index do |item, index|
  if array.values_at[0..[index-1,0].max].sum <= item
    elements_to_copy << item
  end
end

Should do the trick, if I understand you correctly.

Toms Mikoss
+1  A: 
myArray = [3,5,6,2,1]
i = 0
myArray.reverse.inject do |sum, cur|
  break if cur < sum
  i -= 1
  sum + cur
end

The range to copy is i..-1.

Pesto
Ace, thanks Pesto - I'm learning a lot from your answers!
Les