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.

Costa Michailidis
  • 7,691
  • 15
  • 72
  • 124

1 Answers1

3

Okay, apparently the answer is quite obvious : )

Use an or statement.

if (n > 1) {
  return recursiveSearch( n-5 ) || recursiveSearch( n/3 )
}
Costa Michailidis
  • 7,691
  • 15
  • 72
  • 124