Cannot return the length of an array from within a recursive function used to create an array of string permutations.

Cannot return the length of an array from within a recursive function used to create an array of string permutations.



I want to return the length of an array produced after recursively finding permutations of a string. The code works fine and produces the correct array of permutations but when I try to return filtered.length I get the following error message: Uncaught TypeError: otherPerms is not iterable.


This same error also occurs when I try to return the length of the array before filtering it for the results I want.


The following works well if I return filtered then call the function:


let permutation = permutate('aab');

console.log(permutation.length); // 2

console.log(permutation); // ["aba", "aba"]


But I want to be able to return the length of array from within the function.


The code as follows works as intended until I try to return the length of the array produced:


function permutate(str) {

    let result = [];


    if (str.length === 1) {

      result.push(str);

    }


    for (let i = 0; i < str.length; i++) {

      var firstChar = str[i];

      var otherChar = str.substring(0, i) + str.substring(i + 1);

      var otherPerms = permutate(otherChar);


      for (let perm of otherPerms) {

        result.push(firstChar + perm);

      }

    } 


    let filtered = result.filter((str) => !(/(\w)\1/).test(str)); // To get permutations with non-repeating adjacent letters

    return filtered;

}


Solution :

If you try to return the length from within the function the recursiveness wont work as you are no longer returning what "otherPerms" needs. If you want it to return the length, you will have to wrap the function inside another one.


function permutate(str) {


 return recursivePermutate(str).length;


 function recursivePermutate(str) {

  let result = [];


     if (str.length === 1) {

       result.push(str);

     }


     for (let i = 0; i < str.length; i++) {

       var firstChar = str[i];

       var otherChar = str.substring(0, i) + str.substring(i + 1);

       var otherPerms = recursivePermutate(otherChar);


       for (let perm of otherPerms) {

         result.push(firstChar + perm);

       }

     } 


     let filtered = result.filter((str) => !(/(\w)(?=\1)/).test(str)); // To get permutations with non-repeating adjacent letters

     return filtered;

 }

    

}


console.log(permutate("ab"))



javascript,arrays,recursion,permutation

No comments

Powered by Blogger.