javascript - Counting number of occurrences recursively -
why recursive countoccurence function not working? has subroutine. there way without subroutine? seems in javascript have have closure (subroutine function) counter variable, otherwise gets rewritten every time!
function numoccurencesrecursive(arr, val) { //base case. check if has length of 1 var count = 0; function docount(arr, val) { if (arr[0] === val) { count++; } else { count += docount(arr.slice(1), val) } return count; } return docount(arr, val); } console.log(numoccurencesrecursive([2, 7, 4, 4, 1, 4], 4)); // should return 3 returns 1
i think problem thinking iteratively used recursive approach.
the iterative approach has global variable may updated @ each step:
function numoccurencesiterative(arr, val) { var count = 0; for(var i=0; i<arr.length; ++i) if(arr[i] === val) ++count; return count; }
however, when using recursive approaches, better avoid global variables.
function numoccurencesrecursive(arr, val) { if(!arr.length) return 0; return (arr[0] === val) + numoccurencesrecursive(arr.slice(1), val); }
Comments
Post a Comment