Search code examples
javascriptfunctionrecursionpalindrome

Counting Palindromes using recursion


I currently have a code which counts the palindromes in a given string and it was working fine till I tested it with "appal" the function returned 0 when it should return 2 (appa and pp) I would really appreciate it if someone can edit my current code so that it meets that requirement, thank you! Here's my code:

function countPalindromes(string, count) {
  if (string.length <= 1) {
    return count;
  }

  let [ firstLetter ] = string;
  let lastLetter = string[string.length - 1];

  if (firstLetter === lastLetter) {
    let stringWithoutFirstAndLastLetters = string.substring(1, string.length - 1);
    return countPalindromes(stringWithoutFirstAndLastLetters, count + 1);
  } else {
    return 0;
  }
}

console.log(countPalindromes("kayak", 0));
console.log(countPalindromes("aya", 0));
console.log(countPalindromes("appal", 0));

Solution

  • I think this function does the trick. Happy to refactor and explain it later. I'd rather write a new function because I don't think your code is close to executing the task.

    function returnNumberOfPalindromes(word) {
        function isPalindrome(chunk) { 
            return [...chunk].reverse().join('') === chunk;
        }
        let tally = 0;
      
        for (let index1 = 0; index1 <= word.length; index1++) {
          for (index2 = index1 + 2; index2 <= word.length; index2++) { 
            let chunk = word.slice(index1, index2); 
            if (isPalindrome(chunk)) {
                tally += 1;
            };
          }
        }
        console.log(tally);
    }
    
    returnNumberOfPalindromes("kayak");
    returnNumberOfPalindromes("aya");
    returnNumberOfPalindromes("appal");
    returnNumberOfPalindromes("addadaadd");