skip to Main Content

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


  1. Just remove count from your function and declare it one step above the scope like,

    count = 0
    function doesNumAppearKTimes(arr, N, K ) {
        for(let i = 0;i<arr.length; i++) {
            if(Array.isArray(arr[i])) {
            doesNumAppearKTimes(arr[i],N,K)
            } else if(arr[i] === N) {
            count++
            }
            }
        return count === K;
    }
    

    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,

    function doesNumAppearKTimes(arr, N, K ) {
        let count = childFunc( arr,N,K );
        function childFunc(arr, N, K, count=0 ) {
            for(let i = 0;i<arr.length; i++) {
                if(Array.isArray(arr[i])) {
                    count = childFunc(arr[i],N,K,count)
                } else if(arr[i] === N) {
                count++
                }
            }
            return count;
        }
        return count === K;
    }
    
    Login or Signup to reply.
  2. You can define a helper function to get the number of occurrences, then your doesNumAppearKTimes function can just compare the counts.

    function count(arr, n) {
      let s = 0;
      for (const o of arr) s += Array.isArray(o) ? count(o, n) : o === n;
      return s;
    }
    function doesNumAppearKTimes(arr, N, K) {
      return count(arr, N) === K;
    }
    
    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
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search