I have an array with an unknown amount of nested arrays. I have a number that I am looking for N, and a number to see if it is present K amount of times. I need to use recursion to figure out if N is equal to K.
The code below is what I have come up with so far, there are test cases also provided below.
function doesNumAppearKTimes(arr, N, K, count = 0) {
for(let i = 0;i<arr.length; i++) {
if(Array.isArray(arr[i])) {
doesNumAppearKTimes(arr[i],N,K,count)
} else if(arr[i] === N) {
count++
}
}
return count === K;
}
an example of a test case:
console.log(doesNumAppearKTimes([1,2,[3,4,[5],6],3,7],3,3)); // 'false' console.log(doesNumAppearKTimes([[0,-8,1,[-2,2]],[11,[4],6],2,2],2,3)); // 'true' console.log(doesNumAppearKTimes([10,21,4,9,3,7,4,1],4,1)); // 'false'
2
Answers
Just remove count from your function and declare it one step above the scope like,
As every recursive function counts but never returns, only the main function counting reflects at the end. But don’t forget to make count=0 before every case,
Or simply use this solution,
You can define a helper function to get the number of occurrences, then your
doesNumAppearKTimes
function can just compare the counts.