0
votes

I get the error "Maximum call stack size exceeded error" when calling this recursive JavaScript.

This is my code:

var num = 12
,maxlength = 50;
var lengths = [5,6,7,8,4,4,5,6,3,3,2,2];

function knap(maxlength,num){
	if(maxlength==0) return 1;
	if(maxlength<0||(maxlength>0&&num<1)){
		return 0;
	}

	if(knap(maxlength-lengths[num],num-1)){
		console.log(lengths[num]+" ")
		return 1;
	}

	return knap(maxlength,num-1);
}

if(knap(maxlength,num)){
	console.log('Yes');
}else{
	console.log('No');
}

How can I figure out this?

2
There's not much to figure out, you have a function that calls itself indefinitely, you pass in 50 so none of the if statements are true, it goes to the end, and calls the function again with 50 and the same thing happens over again. - adeneo
Did you get the terminating condition right? maxlength is same always - Denny Mathew
Aha, after the first iteration maxlength eq NaN. :) So terminating condition always false. - Vasyl Moskalov
Just curious, could you describe (informally) what your function is supposed to do? - Hunan Rostomyan
And Peter, IMHO you spend much less time to solve this issue if you insert something like console.log(maxlength,num) at first string of your function body. :) - Vasyl Moskalov

2 Answers

1
votes

When you first time call you function value of num is exceed the length of lengths array. So expression maxlength-lengths[num] in if(knap(maxlength-lengths[num],num-1)) is NaN. After that all your break recursion conditions alway is false. So, probably, you need to make first call as knap(maxlength,num-1).

0
votes

It means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit and it is most of the time because of recursion.

See Maximum call stack size exceeded error