How can I optimize checking a value in recursion before operating on it? I'm using Array.indexOf
(this is Javascript)
var nums = [], lengths = [];
function findNumLength(n) {
//preliminary check to see if
//we've done this number before
var indexOf = nums.indexOf(n);
if(indexOf !== -1) {
return lengths[indexOf];
}
function even (n2) { return n2%2===0; }
if(n===1) {
return 1;
}
if(even(n)) {
l = findNumLength(n/2) + 1;
if(indexOf===-1) {
lengths.splice(0,0 ,l);
nums.push(n);
}
return l;
}
else {
l = findNumLength(3*n + 1) + 1;
if(indexOf===-1){
lengths.splice(0,0,l);
nums.push(n);
}
return l;
}
}
(note: I've answered my own question with one solution I've found; it is by no means the only solution (though it may be the best. I don't know). Please, still answer.)
return 1
. If it is in the array, you add it again. Are you sure that's the logic you meant? – jfriend00 Mar 18 '12 at 3:55=== -1
instead of!==
– Thomas Shields Mar 18 '12 at 4:02