0

I am doing a Hackerrank challenge 'Manasa and Stones'

I have already done an Looping solution but it took to much time solving tree levels and I need a recursive solution I guess.

function stones(n, a, b) {


    var arr = [0,0];
    var rresult = recursive(0,a,b,arr,n)

    return rresult;
}
function recursive(n,a,b,arr,end){
    if (n == end){ return arr }
    else {
        let arr2 = arr.map(function(x) {
   return x * 2;
});
        arr = arr.map(function(x) {
   return x * 2;
});
        arr = arr.join(arr2)
        recursive(n,a,b,arr,end)
    }

}

It should be working as expected to solve https://www.hackerrank.com/contests/microverse-coding-challenges/challenges/manasa-and-stones/problem (I don't from expect you to do a solution I need to know why my issue is there * It doesn't make sense)

all my code => https://github.com/Macatuz/MHackerrankSamples/blob/master/Manasa_and_Stones.js

1
  • since the else code in recursive does not return anything, chances are rresult will more often than not be undefined (except when stones is called with first argument == 0) - in all other cases however, I believe you'll end up with an infinite recursion, since n == end will never be true (once you fix the issue as noted in the answer below) Commented Jun 26, 2019 at 0:13

1 Answer 1

2

arr = arr.join(arr2) is not doing what you think it does--the .join method joins the elements in an array into a string delimited by the parameter. When you pass this string arr into the recursive function call, you'll get a crash on the next stack frame, because strings don't have a map function.

You probably meant .concat, which puts the elements from the parameter array on the back of the instance array. Here's a snippet to illustrate what's going on.

const arr1 = ["apples", "bananas"];
const arr2 = ["celery", "asparagus"];

const joined = arr1.join(arr2);
const concatted = arr1.concat(arr2);

console.log(joined, typeof joined);  // whoops?
console.log(concatted);              // ah. much better.

Note that this only solves the query in your title but doesn't produce working code that solves the challenge--that's an exercise for the reader.

Sign up to request clarification or add additional context in comments.

4 Comments

note: once you change .join to .concat, the code in the question will result in infinite recursion
Sure. The OP has more work to do to solve the problem beyond this immediate bug, so I'm not contending this will give the correct solution, only that it resolves the question asked in the post title.
true - I wasn't saying your answer was wrong in any way, just warning the OP :p
i finally got to solve the issue, his answer leaded me there basically.

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.