0

I need to create a recursive function that adds the numbers of any given array, then removes the first element, then adds the array and do this until the array only has element left. my function does this but at the moment I can only see the addition by putting a puts statement but also need the results as the return value like this =>[20,20,19,16,10] and dont know how to go about this as its putting the results separately. Thanks for your help. The function needs to do this recursively: I this is my code:

def parts_sums(ls)
    results_arr=[]
    if( ls.length === 1)
     return ls 
    end
     p results =ls.sum
     parts_sums(ls.drop(1))
     p results_arr << results

end
parts_sums([0, 1, 3, 6, 10])

# ls = [0, 1, 3, 6, 10].sum =>20
# ls = [1, 3, 6, 10].sum => 20
# ls = [3, 6, 10].sum =>19
# ls = [6, 10].sum =>16
# ls = [10]=>10
3
  • 2
    puts returns nil. You're first and foremost concern when writing any method should be its return value. You also don't really need a recursive method unless you're writing it to learn about recursiveness as you can do this with each_with_object. Commented Apr 22, 2020 at 11:36
  • thanks Max, yes i am learning recursion. Commented Apr 22, 2020 at 12:02
  • 1
    I removed the ruby-on-rails tag. This is purely a Ruby question and doesn't pertain to the Ruby on Rails framework. Commented Apr 22, 2020 at 12:30

2 Answers 2

2

You can define a method like this, which is verbose but clear (I think):

def parts_sums(ary, res = [])
  res << [ary.dup, ary.sum]
  if ary.size > 1
    ary.shift
    parts_sums(ary, res)
  else
    return res
  end
end

So, when you call on your array, you get this result:

ary = [0, 1, 3, 6, 10]
parts_sums(ary)
#=> [[[0, 1, 3, 6, 10], 20], [[1, 3, 6, 10], 20], [[3, 6, 10], 19], [[6, 10], 16], [[10], 10]]

Call parts_sums(ary.dup) if you want to preserve the original array.


Which can be rewritten in this shortest way:

def parts_sums_2(ary, res = [])
  return res unless ary.any?
  res << [ary, ary.sum]
  parts_sums_2(ary[1..-1], res)
end
Sign up to request clarification or add additional context in comments.

Comments

1
def parts_sums(ls)
  ls.length == 1 ? ls : ([ls.sum] + parts_sums(ls[1..-1]))
end

puts parts_sums([0, 1, 3, 6, 10]).to_s

3 Comments

Thanks Pavel. This part here (ls[1..-1]) What does it do please?
@FabioAndres It takes elements from ls array starting with index 1 (so, element with index 0 will not be included in result) and to the end: -1 here marks the last element. So, it just takes all elements except the first one. ls[1..2] would take the second and the third elements.
Calling Array#sum in a recursive method doesn't seem right.

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.