Recursion Practice Assistance

Recursion Practice Assistance
0

Hey guys, am trying to solve a recursive problem with this problem statement:

Write a function ice_cream_shop (flavors, favorite) that takes in an array of ice cream flavors available at the ice cream shop, as well as the user’s favorite ice cream flavor. Recursively find out whether or not the shop offers their favorite flavor.

I offered up this attempt but it does not seem to work, any guidance please?

My Attempt

function ice_cream_shop(stockArr, userRequest) {
    if (stockArr.length <= 0) return false;
    if (stockArr[stockArr.length - 1] === userRequest) {
        return true;
    } else {
        stockArr.pop();
        ice_cream_shop(stockArr);
    }
}

1 Like

When you call the function to rerun again make sure you pass along the original userRequest

1 Like

Hey @pjonp, thanks for the reply but after I added the userRequest on the recursive call, its now its just logging undefined.

Here are some test cases am supposed to meet

 ice_cream_shop(['vanilla', 'strawberry'], 'blue moon')  # => returns false
  ice_cream_shop(['pistachio', 'green tea', 'chocolate', 'mint chip'], 'green tea')  # => returns true
  ice_cream_shop(['cookies n cream', 'blue moon', 'superman', 'honey lavender', 'sea salt caramel'], 'pistachio')  # => returns false
  ice_cream_shop(['moose tracks'], 'moose tracks')  # => returns true
  ice_cream_shop([], 'honey lavender')  # => returns false

You are missing a return.

3 Likes

ice_cream_shop(stockArr, userRequest); works for me when I test it.

1 Like

Thanks a lot @RandellDawson, the challenges am facing are in Ruby which I heard has implicit return from App Academy Open Curriculum. I guess the syntax stuck on me after seeing their lectures that did not use the return statement in their recursive code.

Do you think this is the best solution though, how would you solve it?

@pjonp What value gets displayed in the console when the following is ran?

console.log('verdict: ' + ice_cream_shop(['cookies n cream', 'blue moon', 'superman', 'honey lavender', 'sea salt caramel'], 'pistachio'));
1 Like

With JavaScript, you must add a return statement before the recursive call or undefined will be returned. I would solve it with almost the same logic, but use a ternary expression.

function ice_cream_shop(stockArr, userRequest) {
  return !stockArr.length
    ? false
    : stockArr.pop() === userRequest
      ? true
      : ice_cream_shop(stockArr, userRequest);
}
1 Like

Thanks @RandellDawson , recursion is quite confusion,I’ll keep practicing

@RandellDawson. I tested it and got undefined has you alluded to. I made a bad assumption that the the other returns would handle it. Thank you :+1:

1 Like