1

I have the next issue when am trying to use recursion.

Test Cases

puts exact_sum?(12, [1, 2, 3, 4, 5]) => true (he finds it true but returns false)


puts exact_sum?(11, [1, 5, 9, 13]) => false

The behavior of the function is what I am aiming to do but even if he finds true he always returns false.

def exact_sum?(k, coins, i = 0)
  if (k == 0) then 
    print "there is one true #{k}"
    return true
  elsif (i == coins.length)
    return false
  end
  number = coins[i]
  exact_sum?(k-number,coins, i + 1)
  exact_sum?(k,coins, i + 1)
end
4
  • "I have the next issue [...]" – it this a follow-up question? If so, please provide a link to the previous one. Commented Sep 4, 2019 at 6:38
  • 1
    @Stefan: Some languages express "the following" and "the next" with the same expression - it's likely just a second language issue. Commented Sep 4, 2019 at 6:56
  • @Amadan good point! Commented Sep 4, 2019 at 7:14
  • Am not used to speak English as good as it should be I ll be mind that. :S Commented Sep 4, 2019 at 17:28

1 Answer 1

3

You are returning true or false in the base cases, but the recursive case is wrong. Ruby returns the returned value of the last statement in the method if it doesn't execute an explicit return. In this case the last statement is exact_sum?(k,coins, i + 1). What I think you want is to return true if any of the recursive parts is true, which would be:

exact_sum?(k-number,coins, i + 1) || exact_sum?(k,coins, i + 1)
Sign up to request clarification or add additional context in comments.

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.