0

Got stuck in a weird JavaScript functional programming hole.

Here it is:

// Given an integer n, can n be reached by some combination of plus five and times three?

function recursiveSearch (n) {
  // if attempt matches return success
  // if attempt produces neutral keep trying
  // if attempt matches less than 1 return failure
  if (n === 1) return true
  if (n > 1) {
    return recursiveSearch( n-5 ), recursiveSearch( n/3 )
  }
  else return false
}

console.log(1, recursiveSearch(1) )
console.log(3, recursiveSearch(3) )
console.log(6, recursiveSearch(6) )
console.log(7, recursiveSearch(7) )
console.log(9, recursiveSearch(9) )
console.log(13, recursiveSearch(13) )
console.log(51, recursiveSearch(51) )
console.log(247, recursiveSearch(247) )

I obviously can't return two different things from a function, but if I don't return, I can't branch out in my search:

  if (n > 1) {
    recursiveSearch( n-5 )
    recursiveSearch( n/3 )
  }

That just produces undefineds.

1

1 Answer 1

3

Okay, apparently the answer is quite obvious : )

Use an or statement.

if (n > 1) {
  return recursiveSearch( n-5 ) || recursiveSearch( n/3 )
}
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.