I have met some difficulties with the understanding how works cycle "for" and recurrence together. I tried to implement the rod cutting problem in JavaScript. (the original code was written in Java).
Problem: The problem is that the recurrence goes down in each cycle i = 1 to bottom until it reaches the lowest value but then it doesn't execute next cycle i=2. What is wrong in this code?
Code:
var p = [2,5,8,9,10,17,17,20,24,30];
function cut_rod(p,n){
console.log(" level=",n);
if(n == 0){
return 0;
}
q = Number.MIN_VALUE;
for(i = 1; i <= n; i++){
console.log(" i=",i);
q = Math.max(q, p[i-1] + cut_rod(p, n-i));
console.log(" q=",q);
}
return q;
}
console.log(cut_rod(p,10));
The same problem was met when I decided to implement the recurrence which just execute each step of each cycle. (just for the understanding of recurrence without solving some problem).
code:
function test(sum){
console.log("i'm here sum",sum);
if (sum < 1) {
console.log(" ",sum," is less then 1, return",1);
return x=1;
}
else{
for(i=1;i<=3;i++){
console.log(" i=",i);
x = test(sum-i)+1;
console.log(" x=",x)
}
}
return x;
}
console.log("----------------->start");
console.log("answer",test(5));
Thank you very much.
This is a scope issue. Your i
and q
variables are global variables, not local variables.
Change for(i = 1; i <= n; i++){ ...
to for(var i = 1; i <= n; i++){ ...
and q = Number.MIN_VALUE;
to var q = Number.MIN_VALUE;
.