Reputation: 118
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
Upvotes: 0
Views: 934
Reputation: 57344
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.
Upvotes: 2