0

In this function i am trying to calculate the number of ways, a number can be decoded. 1 ought to be decoded as a, 3 as c, 26 as z . The function calculates the right count, but does only return undefined. I think it should cancel the recursive calls at the right time, and I reach the "escape"-block, but the number is not returned as it should. Can anyone point me towards the reason, why this is happening?

function numWaysDecodable(msg) {
    msg = msg.toString().split("");

    function helper(msg, past = 99, count = 1) {
        if (msg.length === 0) {
            console.log("wtf count is:"+count);
            return count;
        }
        let head = msg.shift();
        if (head < 7 && past < 3) {
            count++
        } 
        //the below return statement was missing           
        return helper(msg, head, count);
    }
    return helper(msg);
}

console.log(numWaysDecodable(123));
The fixed code is still faulty, as the algorithm is flawed for other input. For example for the input 1212 we return 4, even though we should recieve the result 5:
  1. 12 1 2;
  2. 1 2 12;
  3. 12 12;
  4. 1 2 1 2;
  5. 1 21 2;

I think the code misses to count nr.3,12 12; I am unsure how to fix that as of yet. Some more thinking to do

LeT
  • 37
  • 5
  • 3
    You're missing a `return` at the recursive call. – Pointy Jun 26 '18 at 15:56
  • 1
    @Barmar, the dupe is about c#, maybe [this](https://stackoverflow.com/questions/10719480/javascript-return-of-recursive-function) fits it better – Luca Kiebel Jun 26 '18 at 15:59
  • 1
    @Luca I don't bother having a different dupe for every language, the problem and solution are the same for all of them. – Barmar Jun 26 '18 at 16:00
  • True, I just saw a lot of confusion in beginners when linking questions of other languages. Granted, JS and C# are pretty close – Luca Kiebel Jun 26 '18 at 16:01
  • sorry for the dupe, and thank you for linking a solution – LeT Jun 26 '18 at 17:02

1 Answers1

1

You have to return value in each call of the recursive function like:

return helper(msg, head, count);

function numWaysDecodable(msg) {
    msg = msg.toString().split("");

    function helper(msg, past = 99, count = 1) {
        if (msg.length === 0) {
            console.log("wtf count is:"+count);
            return count;
        }
        let head = msg.shift();
        if (head < 7 && past < 3) {
            count++
        }            
        return helper(msg, head, count);
    }
    return helper(msg);
}

console.log(numWaysDecodable(123));
Mamun
  • 66,969
  • 9
  • 47
  • 59